/*
 * runtime.js — the JS a JSX preview needs in scope, as a string.
 *
 * It has to be a string because the preview frame is on an opaque origin: it
 * cannot fetch this app's assets, and it cannot read a blob: URL the parent
 * created either. Anything a preview needs must be handed to it as bytes,
 * which is what makes payload size the real currency here.
 *
 * Preact rather than React for exactly that reason - ~15 KB of UMD against
 * ~140 KB, per preview. The alternative of re-rendering the whole tree on every
 * state change and skipping the vdom entirely was rejected on behaviour, not
 * size: it would wipe <canvas> contents on each update, and canvas is what most
 * of these previews draw into.
 */
// Imported by file path, not by package specifier: preact's exports map puts
// the UMD builds behind a "umd" condition that a bundler targeting ESM never
// asks for, so `preact/dist/preact.umd.js` does not resolve. UMD is what we
// want here precisely because it has no module system - it assigns globals when
// loaded as a plain <script>, which is all the sandbox can offer it.
import preactSrc from "../../node_modules/preact/dist/preact.umd.js?raw";
import hooksSrc from "../../node_modules/preact/hooks/dist/hooks.umd.js?raw";

// Both UMD builds fall back to a global (`preact`, `preactHooks`) when there is
// no module system, which is the case inside an inline <script>. This lifts
// what transformed JSX expects - h/Fragment/render and the hooks - to bare
// globals, and mirrors them onto `React` so a model that writes React.useState
// or forgets to remove its import still works.
const GLUE = `
;(function (p, hooks) {
  window.h = p.h;
  window.Fragment = p.Fragment;
  window.render = p.render;
  window.createElement = p.h;
  for (var k in hooks) window[k] = hooks[k];
  window.React = Object.assign({}, p, hooks, { createElement: p.h, Fragment: p.Fragment });
  window.ReactDOM = { render: function (v, el) { p.render(v, el); }, createRoot: function (el) {
    return { render: function (v) { p.render(v, el); } };
  } };
})(preact, preactHooks);
`;

export const PREACT_RUNTIME = `${preactSrc}\n${hooksSrc}\n${GLUE}`;
