Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to use this library without new Function? #230

Open
lilouartz opened this issue Jun 11, 2024 · 1 comment
Open

Is there a way to use this library without new Function? #230

lilouartz opened this issue Jun 11, 2024 · 1 comment

Comments

@lilouartz
Copy link

It fails to run on my website because of CSP policy, and I do not want to allow unsafe-inline. Is there a way to somehow use it without eval even if it means that not all functions will be supported?

@nichtsam
Copy link

I was experimenting this today, and I've come up with a workaround to make it work with 'strict-dynamic' instead of 'unsafe-eval. It's super hacky and not really a solution because it's async and creates a gap between server render and client render.

Anyway, just for your reference, this is the snippet:

const trickEval = (x: string, scope = {}) => {
	// @ts-ignore
	globalThis['trickEval'] = scope
	const code = `
      const scope = globalThis['trickEval'];
      ${Object.keys(scope)
				.map((key) => `const ${key} = scope['${key}'];`)
				.join('\n')}
      const result = (() => {${x}})();
      delete globalThis['trickEval'];
      export default result;
    `

	return import(`data:text/javascript,${encodeURIComponent(code)}`)
}

async function getMDXComponent(code: string, globals = {}) {
	const mdxExport = await getMDXExport(code, globals)
	return mdxExport.default
}

async function getMDXExport(
	code: string,
	globals = {},
): Promise<MDXExport<any>> {
	const jsxGlobals = { React, ReactDOM, _jsx_runtime }
	const scope = { ...jsxGlobals, ...globals }
	const fn = await trickEval(
		`return function(${Object.keys(scope)}) {${code}}`,
	).then((m) => m.default)
	return fn(...Object.values(scope))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants