@puzzmo/sdk 1.0.61 → 1.0.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{createSimulator-PNeBoNux.cjs → createSimulator-CJ8LJCe4.cjs} +190 -40
- package/dist/createSimulator-CJ8LJCe4.cjs.map +1 -0
- package/dist/{createSimulator-CdInpCHG.js → createSimulator-DqxQK61P.js} +572 -297
- package/dist/createSimulator-DqxQK61P.js.map +1 -0
- package/dist/{lua-C3M-mB0u.js → lua-DKb2Tu2V.js} +2 -2
- package/dist/{lua-C3M-mB0u.js.map → lua-DKb2Tu2V.js.map} +1 -1
- package/dist/{lua-D5xtGGen.cjs → lua-QeU9Rzet.cjs} +2 -2
- package/dist/{lua-D5xtGGen.cjs.map → lua-QeU9Rzet.cjs.map} +1 -1
- package/dist/pico8/index.cjs +1 -1
- package/dist/pico8/index.js +1 -1
- package/dist/pico8/lua.d.ts +1 -1
- package/dist/simulator/checklistProgress.d.ts +23 -0
- package/dist/simulator/checklistProgress.d.ts.map +1 -0
- package/dist/simulator/checklistProgress.spec.d.ts +2 -0
- package/dist/simulator/checklistProgress.spec.d.ts.map +1 -0
- package/dist/simulator/createSimulator.d.ts.map +1 -1
- package/dist/simulator/index.cjs +1 -1
- package/dist/simulator/index.js +1 -1
- package/dist/simulator/standalone.cjs +1 -1
- package/dist/simulator/standalone.js +1 -1
- package/dist/simulator/styles.d.ts +1 -1
- package/dist/simulator/styles.d.ts.map +1 -1
- package/dist/simulator/types.d.ts +25 -0
- package/dist/simulator/types.d.ts.map +1 -1
- package/dist/simulator/views/ChecklistView.d.ts +4 -0
- package/dist/simulator/views/ChecklistView.d.ts.map +1 -0
- package/dist/simulator/views/index.d.ts +1 -0
- package/dist/simulator/views/index.d.ts.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/vite.cjs +3 -3
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.ts +3 -1
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js +18 -5
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
- package/dist/createSimulator-CdInpCHG.js.map +0 -1
- package/dist/createSimulator-PNeBoNux.cjs.map +0 -1
package/dist/vite.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.cjs","names":[],"sources":["../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an ` ` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/ (?!;)/g, \" \")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const bundleEntry = resolveBundleEntry(dir, \"src/appBundle\")\n let appBundle: string | null = null\n if (bundleEntry) {\n const relative = path.relative(viteRoot, bundleEntry)\n appBundle = \"/\" + relative.split(path.sep).join(\"/\")\n }\n games.set(data.game.slug, { dir, slug: data.game.slug, displayName: data.game.displayName, appBundlePath: appBundle })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = { ...config, ...(game?.slug ? { slug: game.slug } : {}) }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile } = { ...defaults, ...options }\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir: \"dist\",\n emptyOutDir: false,\n },\n })\n } catch (error) {\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\"app-bundle\", { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\" })\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", { entry: \"src/editorBundle.js\", outputFile: \"editor-bundle.js\" })\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n"],"mappings":"2zBAiCA,SAAgB,EAAc,EAAa,EAAoC,EAAE,CAAoB,OACnG,IAAI,EACJ,GAAI,EAAQ,KAAM,EAAO,EAAA,QAAK,QAAQ,EAAK,EAAQ,KAAK,KACnD,CACH,IAAM,EAAU,EAAA,QAAK,KAAK,EAAK,OAAO,CAChC,EAAQ,EAAA,QAAG,WAAW,EAAQ,CAAG,EAAA,QAAG,YAAY,EAAQ,CAAC,OAAQ,GAAM,EAAE,SAAS,MAAM,CAAC,CAAG,EAAE,CACpG,GAAI,EAAM,OAAS,EAAG,MAAU,MAAM,wBAAwB,EAAM,OAAO,YAAY,EAAQ,qCAAqC,CAChI,EAAM,SAAW,IAAG,EAAO,EAAA,QAAK,KAAK,EAAS,EAAM,GAAG,EAE7D,GAAI,CAAC,GAAQ,CAAC,EAAA,QAAG,WAAW,EAAK,CAAE,OAAO,KAC1C,IAAM,EAAO,EAAA,QAAK,SAAS,EAAM,MAAM,CACjC,EAAY,EAAA,QAAK,QAAQ,GAAA,EAAK,EAAQ,YAAA,KAAa,SAAb,EAAsB,CAClE,MAAO,CAAE,MAAK,OAAM,OAAM,WAAY,EAAA,QAAK,KAAK,EAAW,GAAG,EAAK,OAAO,CAAE,SAAU,EAAA,QAAK,KAAK,EAA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MAAO,EACP,QAAS,CAAC,KAAK,CACf,aAAgB,EACjB,CACD,OAAQ,OACR,YAAa,GACd,CACF,CAAC,OACK,EAAO,CAEd,MADA,QAAQ,MAAM,IAAI,EAAW,iBAAkB,EAAM,CAC/C,QAGX,EAKL,IAAM,EAAkB,GAAc,EAAE,QAAQ,cAAe,GAAG,CAG5D,GAAsB,EAAa,IAAwC,CAE/E,IAAK,IAAM,IAAO,CAAC,MAAO,MAAO,OAAQ,OAAO,CAAE,CAChD,IAAM,EAAY,EAAA,QAAK,KAAK,EAAK,EAAe,EAAI,CACpD,GAAI,EAAA,QAAG,WAAW,EAAU,CAAE,OAAO,EAEvC,OAAO,MAiBT,MAAa,EAAkB,EAAmB,aAAc,CAAE,MAAO,mBAAoB,WAAY,gBAAiB,CAAC,CAU9G,EAAqB,EAAmB,gBAAiB,CAAE,MAAO,sBAAuB,WAAY,mBAAoB,CAAC,CAO1H,GAAsB,EAAc,EAAkB,EAAQ,IAAgB,CACzF,GAAI,GAAS,EAAU,MAAO,EAAE,CAChC,IAAM,EAAoB,EAAE,CACxB,EACJ,GAAI,CACF,EAAU,EAAA,QAAG,YAAY,EAAM,CAAE,cAAe,GAAM,CAAC,SACjD,CACN,OAAO,EAET,IAAK,IAAM,KAAS,EAAS,CAC3B,GAAI,CAAC,EAAM,aAAa,EAAI,EAAM,KAAK,WAAW,IAAI,EAAI,EAAM,OAAS,eAAgB,SACzF,IAAM,EAAM,EAAA,QAAK,KAAK,EAAM,EAAM,KAAK,CACnC,EAAA,QAAG,WAAW,EAAA,QAAK,KAAK,EAAK,cAAc,CAAC,EAC9C,EAAQ,KAAK,EAAI,CAEnB,EAAQ,KAAK,GAAG,EAAmB,EAAK,EAAU,EAAQ,EAAE,CAAC,CAE/D,OAAO"}
|
|
1
|
+
{"version":3,"file":"vite.cjs","names":[],"sources":["../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an ` ` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/ (?!;)/g, \" \")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset, SimulatorIntegrations } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n /** `integrations` from the puzzmo.json, passed to simulator tabs that preview them */\n integrations?: SimulatorIntegrations\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const bundleEntry = resolveBundleEntry(dir, \"src/appBundle\")\n let appBundle: string | null = null\n if (bundleEntry) {\n const relative = path.relative(viteRoot, bundleEntry)\n appBundle = \"/\" + relative.split(path.sep).join(\"/\")\n }\n const integrations = data.integrations && typeof data.integrations === \"object\" ? data.integrations : undefined\n games.set(data.game.slug, { dir, slug: data.game.slug, displayName: data.game.displayName, appBundlePath: appBundle, integrations })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = {\n ...config,\n ...(game?.slug ? { slug: game.slug } : {}),\n ...(game?.integrations ? { integrations: game.integrations } : {}),\n }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n // Re-read puzzmo.json on edit and reload the page so the simulator picks up its changes\n for (const g of games.values()) server.watcher.add(path.join(g.dir, \"puzzmo.json\"))\n server.watcher.on(\"change\", (file) => {\n if (path.basename(file) !== \"puzzmo.json\") return\n games = discoverGames(viteRoot)\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n if (mod.id?.startsWith(\"\\0\" + virtualID)) server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: \"full-reload\" })\n })\n\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile } = { ...defaults, ...options }\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir: \"dist\",\n emptyOutDir: false,\n },\n })\n } catch (error) {\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\"app-bundle\", { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\" })\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", { entry: \"src/editorBundle.js\", outputFile: \"editor-bundle.js\" })\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n"],"mappings":"2zBAiCA,SAAgB,EAAc,EAAa,EAAoC,EAAE,CAAoB,OACnG,IAAI,EACJ,GAAI,EAAQ,KAAM,EAAO,EAAA,QAAK,QAAQ,EAAK,EAAQ,KAAK,KACnD,CACH,IAAM,EAAU,EAAA,QAAK,KAAK,EAAK,OAAO,CAChC,EAAQ,EAAA,QAAG,WAAW,EAAQ,CAAG,EAAA,QAAG,YAAY,EAAQ,CAAC,OAAQ,GAAM,EAAE,SAAS,MAAM,CAAC,CAAG,EAAE,CACpG,GAAI,EAAM,OAAS,EAAG,MAAU,MAAM,wBAAwB,EAAM,OAAO,YAAY,EAAQ,qCAAqC,CAChI,EAAM,SAAW,IAAG,EAAO,EAAA,QAAK,KAAK,EAAS,EAAM,GAAG,EAE7D,GAAI,CAAC,GAAQ,CAAC,EAAA,QAAG,WAAW,EAAK,CAAE,OAAO,KAC1C,IAAM,EAAO,EAAA,QAAK,SAAS,EAAM,MAAM,CACjC,EAAY,EAAA,QAAK,QAAQ,GAAA,EAAK,EAA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AiB,CAAE,MAAO,sBAAuB,WAAY,mBAAoB,CAAC,CAO1H,GAAsB,EAAc,EAAkB,EAAQ,IAAgB,CACzF,GAAI,GAAS,EAAU,MAAO,EAAE,CAChC,IAAM,EAAoB,EAAE,CACxB,EACJ,GAAI,CACF,EAAU,EAAA,QAAG,YAAY,EAAM,CAAE,cAAe,GAAM,CAAC,SACjD,CACN,OAAO,EAET,IAAK,IAAM,KAAS,EAAS,CAC3B,GAAI,CAAC,EAAM,aAAa,EAAI,EAAM,KAAK,WAAW,IAAI,EAAI,EAAM,OAAS,eAAgB,SACzF,IAAM,EAAM,EAAA,QAAK,KAAK,EAAM,EAAM,KAAK,CACnC,EAAA,QAAG,WAAW,EAAA,QAAK,KAAK,EAAK,cAAc,CAAC,EAC9C,EAAQ,KAAK,EAAI,CAEnB,EAAQ,KAAK,GAAG,EAAmB,EAAK,EAAU,EAAQ,EAAE,CAAC,CAE/D,OAAO"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Plugin } from "vite";
|
|
2
2
|
import type { HostContext } from "./types";
|
|
3
|
-
import type { HostContextPreset } from "./simulator/types";
|
|
3
|
+
import type { HostContextPreset, SimulatorIntegrations } from "./simulator/types";
|
|
4
4
|
export { puzzmoPico8, type PuzzmoPico8PluginOptions } from "./pico8/vitePlugin";
|
|
5
5
|
export type PuzzmoSimulatorPluginOptions = {
|
|
6
6
|
/** Whether to auto-start the game after READY (default: true) */
|
|
@@ -49,6 +49,8 @@ export type GameInfo = {
|
|
|
49
49
|
displayName: string;
|
|
50
50
|
/** Vite-root-relative path to app bundle entry, if it exists */
|
|
51
51
|
appBundlePath: string | null;
|
|
52
|
+
/** `integrations` from the puzzmo.json, passed to simulator tabs that preview them */
|
|
53
|
+
integrations?: SimulatorIntegrations;
|
|
52
54
|
};
|
|
53
55
|
/**
|
|
54
56
|
* Discover all games from puzzmo.json files under a root directory.
|
package/dist/vite.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAA;AAIlD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAC1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;
|
|
1
|
+
{"version":3,"file":"vite.d.ts","sourceRoot":"","sources":["../src/vite.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAkB,MAAM,MAAM,CAAA;AAIlD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAA;AAC1C,OAAO,KAAK,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAA;AAEjF,OAAO,EAAE,WAAW,EAAE,KAAK,wBAAwB,EAAE,MAAM,oBAAoB,CAAA;AAE/E,MAAM,MAAM,4BAA4B,GAAG;IACzC,iEAAiE;IACjE,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,8CAA8C;IAC9C,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB;;;;OAIG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,KAAK,CAAA;IAC7B;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,WAAW,EAAE,CAAA;IAC3B;;;;;;OAMG;IACH,kBAAkB,CAAC,EAAE,iBAAiB,EAAE,CAAA;IACxC;;;;;OAKG;IACH,aAAa,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;CACrD,CAAA;AAKD,gBAAgB;AAChB,MAAM,MAAM,QAAQ,GAAG;IACrB,2CAA2C;IAC3C,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAA;IACZ,WAAW,EAAE,MAAM,CAAA;IACnB,gEAAgE;IAChE,aAAa,EAAE,MAAM,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,GAAI,MAAM,MAAM,EAAE,UAAU,MAAM,EAAE,cAAS,KAAG,MAAM,EAkBpF,CAAA"}
|
package/dist/vite.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as e } from "./objectWithoutProperties-Bjd1IAMi.js";
|
|
2
2
|
import { t } from "./objectSpread2-BQwrzeNG.js";
|
|
3
3
|
import { t as n } from "./asyncToGenerator-BotOOyB7.js";
|
|
4
|
-
import { t as r } from "./lua-
|
|
4
|
+
import { t as r } from "./lua-DKb2Tu2V.js";
|
|
5
5
|
import { build as i } from "vite";
|
|
6
6
|
import a from "path";
|
|
7
7
|
import o from "fs";
|
|
@@ -186,11 +186,14 @@ function _(e) {
|
|
|
186
186
|
let n = JSON.parse(o.readFileSync(a.join(i, "puzzmo.json"), "utf-8"));
|
|
187
187
|
if (!(!(n == null || (r = n.game) == null) && r.slug)) continue;
|
|
188
188
|
let s = C(i, "src/appBundle"), c = null;
|
|
189
|
-
s && (c = "/" + a.relative(e, s).split(a.sep).join("/"))
|
|
189
|
+
s && (c = "/" + a.relative(e, s).split(a.sep).join("/"));
|
|
190
|
+
let l = n.integrations && typeof n.integrations == "object" ? n.integrations : void 0;
|
|
191
|
+
t.set(n.game.slug, {
|
|
190
192
|
dir: i,
|
|
191
193
|
slug: n.game.slug,
|
|
192
194
|
displayName: n.game.displayName,
|
|
193
|
-
appBundlePath: c
|
|
195
|
+
appBundlePath: c,
|
|
196
|
+
integrations: l
|
|
194
197
|
});
|
|
195
198
|
} catch (e) {}
|
|
196
199
|
return t;
|
|
@@ -219,7 +222,7 @@ function y(n, r) {
|
|
|
219
222
|
let { fixturesGlob: i, viewFactories: a } = n, o = e(n, m), s = i === !1 ? null : i == null ? "/fixtures/puzzles/**/*.{json,toml}" : i, c = ["import { createSimulator } from \"@puzzmo/sdk/simulator\""];
|
|
220
223
|
for (let e of a == null ? [] : a) c.push(`import { ${e.export} } from ${JSON.stringify(e.module)}`);
|
|
221
224
|
s && c.push(`const fixtures = import.meta.glob(${JSON.stringify(s)}, { query: "?raw", import: "default", eager: true })`), r != null && r.appBundlePath && (c.push(`import(${JSON.stringify(r.appBundlePath)}).then(m => {`), c.push(" if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail"), c.push(" if (m.getShareString) globalThis.getShareString = m.getShareString"), c.push("}).catch(() => {})"));
|
|
222
|
-
let l = t(t({}, o), r != null && r.slug ? { slug: r.slug } : {}), u = Object.entries(l).filter(([, e]) => e !== void 0).map(([e, t]) => `${e}: ${JSON.stringify(t)}`);
|
|
225
|
+
let l = t(t(t({}, o), r != null && r.slug ? { slug: r.slug } : {}), r != null && r.integrations ? { integrations: r.integrations } : {}), u = Object.entries(l).filter(([, e]) => e !== void 0).map(([e, t]) => `${e}: ${JSON.stringify(t)}`);
|
|
223
226
|
return s && u.push("fixtures"), a != null && a.length && u.push(`views: [${a.map((e) => `${e.export}()`).join(", ")}]`), c.push(`createSimulator({ ${u.join(", ")} })`), c.join("\n");
|
|
224
227
|
}
|
|
225
228
|
/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */
|
|
@@ -244,7 +247,17 @@ function b(e = {}) {
|
|
|
244
247
|
return y(e, r ? t.get(r) : t.size === 1 ? t.values().next().value : void 0);
|
|
245
248
|
},
|
|
246
249
|
configureServer(e) {
|
|
247
|
-
e.
|
|
250
|
+
for (let n of t.values()) e.watcher.add(a.join(n.dir, "puzzmo.json"));
|
|
251
|
+
e.watcher.on("change", (n) => {
|
|
252
|
+
if (a.basename(n) === "puzzmo.json") {
|
|
253
|
+
t = _(r);
|
|
254
|
+
for (let t of e.moduleGraph.idToModuleMap.values()) {
|
|
255
|
+
var i;
|
|
256
|
+
(i = t.id) != null && i.startsWith("\0" + g) && e.moduleGraph.invalidateModule(t);
|
|
257
|
+
}
|
|
258
|
+
e.ws.send({ type: "full-reload" });
|
|
259
|
+
}
|
|
260
|
+
}), e.middlewares.use("/oauth/callback", (e, t) => {
|
|
248
261
|
t.setHeader("Content-Type", "text/html"), t.end("<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n<\/script></body></html>");
|
|
249
262
|
}), e.middlewares.use(function() {
|
|
250
263
|
var i = n(function* (n, i, a) {
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":[],"sources":["../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an ` ` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/ (?!;)/g, \" \")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const bundleEntry = resolveBundleEntry(dir, \"src/appBundle\")\n let appBundle: string | null = null\n if (bundleEntry) {\n const relative = path.relative(viteRoot, bundleEntry)\n appBundle = \"/\" + relative.split(path.sep).join(\"/\")\n }\n games.set(data.game.slug, { dir, slug: data.game.slug, displayName: data.game.displayName, appBundlePath: appBundle })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = { ...config, ...(game?.slug ? { slug: game.slug } : {}) }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile } = { ...defaults, ...options }\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir: \"dist\",\n emptyOutDir: false,\n },\n })\n } catch (error) {\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\"app-bundle\", { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\" })\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", { entry: \"src/editorBundle.js\", outputFile: \"editor-bundle.js\" })\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,EAAc,GAAa,IAAoC,EAAE,EAAoB;;CACnG,IAAI;AACJ,KAAI,EAAQ,KAAM,KAAO,EAAK,QAAQ,GAAK,EAAQ,KAAK;MACnD;EACH,IAAM,IAAU,EAAK,KAAK,GAAK,OAAO,EAChC,IAAQ,EAAG,WAAW,EAAQ,GAAG,EAAG,YAAY,EAAQ,CAAC,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AACpG,MAAI,EAAM,SAAS,EAAG,OAAU,MAAM,wBAAwB,EAAM,OAAO,YAAY,EAAQ,qCAAqC;AACpI,EAAI,EAAM,WAAW,MAAG,IAAO,EAAK,KAAK,GAAS,EAAM,GAAG;;AAE7D,KAAI,CAAC,KAAQ,CAAC,EAAG,WAAW,EAAK,CAAE,QAAO;CAC1C,IAAM,IAAO,EAAK,SAAS,GAAM,MAAM,EACjC,IAAY,EAAK,QAAQ,IAAA,IAAK,EAAQ,cAAA,OAAa,WAAb,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AAW,kBAAkB,EAAM,EAC/C;;;;GAGX;;;;AAKL,IAAM,KAAkB,MAAc,EAAE,QAAQ,eAAe,GAAG,EAG5D,KAAsB,GAAa,MAAwC;AAE/E,MAAK,IAAM,KAAO;EAAC;EAAO;EAAO;EAAQ;EAAO,EAAE;EAChD,IAAM,IAAY,EAAK,KAAK,GAAK,IAAe,EAAI;AACpD,MAAI,EAAG,WAAW,EAAU,CAAE,QAAO;;AAEvC,QAAO;;;;;;;;;AAiBT,MAAa,IAAkB,EAAmB,cAAc;CAAE,OAAO;CAAoB,YAAY;CAAiB,CAAC,EAU9G,IAAqB,EAAmB,iBAAiB;CAAE,OAAO;CAAuB,YAAY;CAAoB,CAAC,EAO1H,KAAsB,GAAc,GAAkB,IAAQ,MAAgB;AACzF,KAAI,KAAS,EAAU,QAAO,EAAE;CAChC,IAAM,IAAoB,EAAE,EACxB;AACJ,KAAI;AACF,MAAU,EAAG,YAAY,GAAM,EAAE,eAAe,IAAM,CAAC;aACjD;AACN,SAAO;;AAET,MAAK,IAAM,KAAS,GAAS;AAC3B,MAAI,CAAC,EAAM,aAAa,IAAI,EAAM,KAAK,WAAW,IAAI,IAAI,EAAM,SAAS,eAAgB;EACzF,IAAM,IAAM,EAAK,KAAK,GAAM,EAAM,KAAK;AAIvC,EAHI,EAAG,WAAW,EAAK,KAAK,GAAK,cAAc,CAAC,IAC9C,EAAQ,KAAK,EAAI,EAEnB,EAAQ,KAAK,GAAG,EAAmB,GAAK,GAAU,IAAQ,EAAE,CAAC;;AAE/D,QAAO"}
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/pico8/vitePlugin.ts","../src/vite.ts"],"sourcesContent":["import type { Plugin, ResolvedConfig } from \"vite\"\nimport { execFileSync } from \"child_process\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport { puzzmoLua } from \"./lua\"\n\nexport type PuzzmoPico8PluginOptions = {\n /** The cart, relative to the page. Defaults to the only `.p8` file in `cart/`. */\n cart?: string\n /** Where PICO-8's HTML export lives, relative to the page. Defaults to `export`. Commit it, so builds don't need PICO-8. */\n exportDir?: string\n /**\n * The PICO-8 binary used to re-export the cart when it changes. Defaults to `$PICO8`, then `pico8` on your PATH,\n * then where PICO-8's installers put it. When it can't be found the committed export is used as-is. Pass false to\n * never export.\n */\n pico8?: string | false\n /** Keep `puzzmo.lua` next to the cart up to date. Defaults to true. */\n writeLua?: boolean\n}\n\n/** @internal */\nexport type Pico8Game = {\n /** The directory holding the page */\n dir: string\n cart: string\n /** The cart's name, which PICO-8 also uses for its export */\n name: string\n exportHTML: string\n exportJS: string\n}\n\n/** @internal Finds the PICO-8 game served by the page in `dir`, if there is one. */\nexport function findPico8Game(dir: string, options: PuzzmoPico8PluginOptions = {}): Pico8Game | null {\n let cart: string | undefined\n if (options.cart) cart = path.resolve(dir, options.cart)\n else {\n const cartDir = path.join(dir, \"cart\")\n const carts = fs.existsSync(cartDir) ? fs.readdirSync(cartDir).filter((f) => f.endsWith(\".p8\")) : []\n if (carts.length > 1) throw new Error(`[puzzmo-pico8] found ${carts.length} carts in ${cartDir}, pick one with the \\`cart\\` option`)\n if (carts.length === 1) cart = path.join(cartDir, carts[0])\n }\n if (!cart || !fs.existsSync(cart)) return null\n const name = path.basename(cart, \".p8\")\n const exportDir = path.resolve(dir, options.exportDir ?? \"export\")\n return { dir, cart, name, exportHTML: path.join(exportDir, `${name}.html`), exportJS: path.join(exportDir, `${name}.js`) }\n}\n\n/**\n * @internal\n * Turns PICO-8's exported page into a Puzzmo game's page. PICO-8's shell is a thousand lines of globals and handlers\n * its runtime expects to find, and it changes between versions, so rather than keep a copy we adjust theirs.\n */\nexport function patchPico8Export(html: string, name: string, scripts: string[]): string {\n const escaped = name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n\n // PICO-8 loads its runtime from a script element it builds itself. Point it at the copy we serve next to the page,\n // relative because Puzzmo serves games from a subfolder.\n const runtime = new RegExp(`((?:\\\\.src\\\\s*=\\\\s*|\\\\ssrc=)[\"'])[^\"']*${escaped}\\\\.js([\"'])`)\n if (!runtime.test(html)) throw new Error(`[puzzmo-pico8] couldn't find where PICO-8's page loads ${name}.js`)\n html = html.replace(runtime, `$1./${name}.js$2`)\n\n // Boot straight away. Otherwise the cart waits for a click on PICO-8's play button and the host never hears that\n // the game loaded. (Browsers which need a tap before audio can start, like iOS Safari, still show the button.)\n html = html.replace(/var\\s+p8_autoplay\\s*=\\s*false/, \"var p8_autoplay = true\")\n\n // The GPIO array, for shells old enough not to declare it themselves.\n if (!/var\\s+pico8_gpio\\s*=/.test(html)) html = html.replace(/<head>/i, \"<head>\\n<script>var pico8_gpio = new Array(128)</script>\")\n\n // Things a browser shrugs off and Vite doesn't: an HTML comment wrapped around the stylesheet, a stray\n // `-repeat center;` in it, and an ` ` without its semicolon.\n html = html.replace(\n /(<style[^>]*>)([\\s\\S]*?)(<\\/style>)/gi,\n (_, open: string, css: string, close: string) =>\n open + css.replace(/<!--|-->/g, \"\").replace(/^[ \\t]*-repeat[^;\\n]*;[ \\t]*$/gm, \"\") + close,\n )\n html = html.replace(/ (?!;)/g, \" \")\n\n const bodyEnd = html.lastIndexOf(\"</body>\")\n if (bodyEnd === -1) throw new Error(\"[puzzmo-pico8] that doesn't look like a PICO-8 export, it has no </body>\")\n return html.slice(0, bodyEnd) + scripts.join(\"\\n\") + \"\\n\" + html.slice(bodyEnd)\n}\n\n/** Where PICO-8's own installers put it, for people who never added it to their PATH. */\nconst usualPico8Locations = [\n \"/Applications/PICO-8.app/Contents/MacOS/pico8\",\n \"C:\\\\Program Files (x86)\\\\PICO-8\\\\pico8.exe\",\n \"C:\\\\Program Files\\\\PICO-8\\\\pico8.exe\",\n]\n\n/** Finds an executable on the PATH without running it: `pico8` with no export arguments opens the whole app. */\nconst findExecutable = (bin: string): string | null => {\n if (bin.includes(\"/\") || bin.includes(\"\\\\\")) return fs.existsSync(bin) ? bin : null\n for (const dir of (process.env.PATH ?? \"\").split(path.delimiter)) {\n for (const ext of process.platform === \"win32\" ? [\".exe\", \".cmd\", \"\"] : [\"\"]) {\n const candidate = path.join(dir, bin + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n }\n if (bin === \"pico8\") return usualPico8Locations.find((p) => fs.existsSync(p)) ?? null\n return null\n}\n\nconst mtime = (file: string) => (fs.existsSync(file) ? fs.statSync(file).mtimeMs : 0)\n\n/**\n * Vite plugin for games written as PICO-8 carts. Your `index.html` only needs your own script tag, the plugin swaps\n * in PICO-8's exported page around it, serves the PICO-8 runtime next to it, and copies it into the build.\n *\n * When PICO-8 is installed it also re-exports the cart whenever it (or a `.lua` file next to it) changes, and reloads\n * the page, so saving in PICO-8 is enough to see the change in the simulator.\n */\nexport function puzzmoPico8(options: PuzzmoPico8PluginOptions = {}): Plugin {\n let config: ResolvedConfig\n const games = new Map<string, Pico8Game>()\n const binary = options.pico8 === false ? null : (options.pico8 ?? process.env.PICO8 ?? \"pico8\")\n\n const log = (message: string) => config.logger.info(`\\x1b[33m\\x1b[1m PICO-8 \\x1b[22m\\x1b[39m${message}`)\n\n const writeLua = (game: Pico8Game) => {\n if (options.writeLua === false) return\n const file = path.join(path.dirname(game.cart), \"puzzmo.lua\")\n if (fs.existsSync(file) && fs.readFileSync(file, \"utf8\") === puzzmoLua) return\n fs.writeFileSync(file, puzzmoLua)\n log(`wrote ${path.relative(config.root, file)}`)\n }\n\n /** Re-exports the cart when it's newer than the export and PICO-8 is around to do it. */\n const exportIfStale = (game: Pico8Game) => {\n const cartDir = path.dirname(game.cart)\n const newest = Math.max(\n ...fs\n .readdirSync(cartDir)\n .filter((f) => /\\.(p8|lua)$/.test(f))\n .map((f) => mtime(path.join(cartDir, f))),\n )\n if (fs.existsSync(game.exportJS) && mtime(game.exportJS) >= newest) return\n\n const pico8 = binary ? findExecutable(binary) : null\n if (!pico8) {\n if (fs.existsSync(game.exportHTML)) {\n config.logger.warn(\n `[puzzmo-pico8] ${path.relative(config.root, game.cart)} is newer than its export, and PICO-8 isn't around to re-export it. Using the old export.`,\n )\n return\n }\n throw new Error(\n `[puzzmo-pico8] there's no export of ${path.relative(config.root, game.cart)} yet, and PICO-8 isn't on your PATH to make one.\\n` +\n `Export it inside PICO-8 with EXPORT ${game.name}.html into ${path.relative(config.root, path.dirname(game.exportHTML))}/, or set PICO8=/path/to/pico8.`,\n )\n }\n\n fs.mkdirSync(path.dirname(game.exportHTML), { recursive: true })\n const before = mtime(game.exportJS)\n let output = \"\"\n try {\n output = execFileSync(pico8, [game.cart, \"-export\", game.exportHTML], {\n encoding: \"utf8\",\n timeout: 60_000,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n })\n } catch (error) {\n output = String((error as { stdout?: string }).stdout ?? error)\n }\n if (mtime(game.exportJS) === before) {\n const hint = /label/i.test(output) ? \"\\nHTML exports need a label: run the cart in PICO-8, press CTRL-7, and save.\" : \"\"\n throw new Error(`[puzzmo-pico8] PICO-8 didn't export ${path.relative(config.root, game.cart)}:\\n${output.trim()}${hint}`)\n }\n log(`exported ${path.relative(config.root, game.cart)}`)\n }\n\n const gameForPage = (htmlFile: string) => {\n const dir = path.dirname(htmlFile)\n if (!games.has(dir)) {\n const game = findPico8Game(dir, options)\n if (!game) return null\n games.set(dir, game)\n }\n return games.get(dir)!\n }\n\n return {\n name: \"puzzmo-pico8\",\n\n config() {\n // The export is rewritten on every save, and Vite reloads the page for any .html it sees change. The plugin\n // reloads once the export is done, so Vite reloading too would boot the cart twice.\n const exportDir = options.exportDir ?? \"export\"\n const isExport = (file: string) =>\n /\\.(html|js)$/.test(file) &&\n path.basename(path.dirname(file)) === path.basename(exportDir) &&\n fs.existsSync(path.join(path.dirname(path.dirname(file)), \"cart\"))\n return { server: { watch: { ignored: [isExport] } } }\n },\n\n configResolved(resolved) {\n config = resolved\n },\n\n transformIndexHtml: {\n order: \"pre\",\n handler(html, ctx) {\n const game = gameForPage(ctx.filename)\n if (!game) return\n writeLua(game)\n exportIfStale(game)\n // Keep the page's own module scripts: that's the game code.\n const scripts = html.match(/<script\\b[^>]*type=[\"']module[\"'][^>]*>[\\s\\S]*?<\\/script>/gi) ?? []\n return patchPico8Export(fs.readFileSync(game.exportHTML, \"utf8\"), game.name, scripts)\n },\n },\n\n configureServer(devServer) {\n // Serve the runtime next to the page, untouched by Vite's transforms: it is a megabyte of emscripten output\n // which only works exactly as PICO-8 wrote it.\n devServer.middlewares.use((req, res, next) => {\n const url = decodeURIComponent((req.url ?? \"\").split(\"?\")[0])\n if (!url.endsWith(\".js\")) return next()\n const game = [...games.values()].find(\n (g) =>\n url ===\n \"/\" +\n path\n .relative(config.root, path.join(g.dir, `${g.name}.js`))\n .split(path.sep)\n .join(\"/\"),\n )\n if (!game || !fs.existsSync(game.exportJS)) return next()\n res.setHeader(\"Content-Type\", \"text/javascript\")\n res.end(fs.readFileSync(game.exportJS))\n })\n\n // Saving the cart in PICO-8 re-exports it and reloads the page.\n devServer.watcher.on(\"change\", (file) => {\n const game = [...games.values()].find((g) => path.dirname(file) === path.dirname(g.cart) && /\\.(p8|lua)$/.test(file))\n if (!game || path.basename(file) === \"puzzmo.lua\") return\n try {\n exportIfStale(game)\n devServer.ws.send({ type: \"full-reload\" })\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n config.logger.error(message)\n devServer.ws.send({ type: \"error\", err: { message, stack: \"\" } })\n }\n })\n },\n\n generateBundle() {\n for (const game of games.values()) {\n const fileName = path\n .relative(config.root, path.join(game.dir, `${game.name}.js`))\n .split(path.sep)\n .join(\"/\")\n this.emitFile({ type: \"asset\", fileName, source: fs.readFileSync(game.exportJS) })\n }\n },\n }\n}\n","import type { Plugin, ResolvedConfig } from \"vite\"\nimport { build } from \"vite\"\nimport path from \"path\"\nimport fs from \"fs\"\nimport type { HostContext } from \"./types\"\nimport type { HostContextPreset, SimulatorIntegrations } from \"./simulator/types\"\n\nexport { puzzmoPico8, type PuzzmoPico8PluginOptions } from \"./pico8/vitePlugin\"\n\nexport type PuzzmoSimulatorPluginOptions = {\n /** Whether to auto-start the game after READY (default: true) */\n autoStart?: boolean\n /** Initial collapsed state (default: true) */\n collapsed?: boolean\n /**\n * Glob pattern for fixture files, passed to import.meta.glob which is relative to the closest puzzmo.json. Defaults\n * to `\"/fixtures/puzzles/**\\/*.{json,toml}\"`. Fixtures are loaded as raw strings (any text format works — JSON,\n * TOML, or a custom format) and delivered to the game verbatim, so the game parses them itself. Pass false to disable.\n */\n fixturesGlob?: string | false\n /**\n * The `hostContext` array the simulator sends in READY_DATA, so host-context-dependent features\n * (embed settings, sandbox mode, mobile layout, …) can be exercised locally. Must be\n * JSON-serializable. Defaults to a single desktop \"app\" context; the simulator's Host tab can\n * override it at runtime (persisted per-browser, applied on restart).\n *\n * @internal\n */\n hostContext?: HostContext[]\n /**\n * Extra named `hostContext` presets for the simulator's Host tab, alongside the generic\n * built-ins — how a game ships its own scenarios (e.g. crossword's partner-embed toolbar\n * settings). Must be JSON-serializable.\n *\n * @internal\n */\n hostContextPresets?: HostContextPreset[]\n /**\n * Plugin-provided simulator tabs, named rather than passed directly because this config is\n * serialized into a virtual module. Each entry is imported and called with no arguments, so the\n * export must be a `() => SimulatorView` factory — e.g.\n * `{ module: \"@puzzmo-com/shared/sdkPlugins\", export: \"createCollabSimulatorView\" }`.\n */\n viewFactories?: { module: string; export: string }[]\n}\n\nconst simulatorURL = \"/@puzzmo-simulator-init.js\"\nconst virtualID = \"virtual:puzzmo-simulator\"\n\n/** @internal */\nexport type GameInfo = {\n /** Directory containing the puzzmo.json */\n dir: string\n slug: string\n displayName: string\n /** Vite-root-relative path to app bundle entry, if it exists */\n appBundlePath: string | null\n /** `integrations` from the puzzmo.json, passed to simulator tabs that preview them */\n integrations?: SimulatorIntegrations\n}\n\n/**\n * Discover all games from puzzmo.json files under a root directory.\n *\n * @internal\n */\nexport function discoverGames(viteRoot: string): Map<string, GameInfo> {\n const games = new Map<string, GameInfo>()\n const candidates = findPuzzmoJsonDirs(viteRoot, 3)\n if (fs.existsSync(path.join(viteRoot, \"puzzmo.json\"))) {\n candidates.unshift(viteRoot)\n }\n for (const dir of candidates) {\n try {\n const data = JSON.parse(fs.readFileSync(path.join(dir, \"puzzmo.json\"), \"utf-8\"))\n if (!data?.game?.slug) continue\n const bundleEntry = resolveBundleEntry(dir, \"src/appBundle\")\n let appBundle: string | null = null\n if (bundleEntry) {\n const relative = path.relative(viteRoot, bundleEntry)\n appBundle = \"/\" + relative.split(path.sep).join(\"/\")\n }\n const integrations = data.integrations && typeof data.integrations === \"object\" ? data.integrations : undefined\n games.set(data.game.slug, { dir, slug: data.game.slug, displayName: data.game.displayName, appBundlePath: appBundle, integrations })\n } catch {\n // skip invalid files\n }\n }\n return games\n}\n\n/**\n * Resolve which game a request belongs to using the referer URL.\n *\n * @internal\n */\nexport function resolveGameFromReferer(referer: string | undefined, games: Map<string, GameInfo>, viteRoot: string): GameInfo | undefined {\n if (referer) {\n try {\n const refPath = new URL(referer).pathname\n for (const g of games.values()) {\n const relDir = \"/\" + path.relative(viteRoot, g.dir).split(path.sep).join(\"/\")\n if (refPath.startsWith(relDir + \"/\") || refPath === relDir) return g\n }\n } catch {\n // ignore malformed referer\n }\n }\n if (games.size === 1) return games.values().next().value\n return undefined\n}\n\n/**\n * Generate the virtual module code for the simulator.\n *\n * @internal\n */\nexport function generateSimulatorCode(options: PuzzmoSimulatorPluginOptions, game: GameInfo | undefined): string {\n const { fixturesGlob: fixturesOpt, viewFactories, ...config } = options\n const fixturesGlob = fixturesOpt === false ? null : (fixturesOpt ?? \"/fixtures/puzzles/**/*.{json,toml}\")\n\n const lines = [`import { createSimulator } from \"@puzzmo/sdk/simulator\"`]\n for (const view of viewFactories ?? []) {\n lines.push(`import { ${view.export} } from ${JSON.stringify(view.module)}`)\n }\n\n // Load fixtures as raw strings so any text format reaches the game verbatim; the game does its own parsing.\n if (fixturesGlob) {\n lines.push(`const fixtures = import.meta.glob(${JSON.stringify(fixturesGlob)}, { query: \"?raw\", import: \"default\", eager: true })`)\n }\n\n if (game?.appBundlePath) {\n lines.push(`import(${JSON.stringify(game.appBundlePath)}).then(m => {`)\n lines.push(` if (m.renderThumbnail) globalThis.renderThumbnail = m.renderThumbnail`)\n lines.push(` if (m.getShareString) globalThis.getShareString = m.getShareString`)\n lines.push(`}).catch(() => {})`)\n }\n\n const simConfig = {\n ...config,\n ...(game?.slug ? { slug: game.slug } : {}),\n ...(game?.integrations ? { integrations: game.integrations } : {}),\n }\n const configEntries = Object.entries(simConfig).filter(([, v]) => v !== undefined)\n const configParts = configEntries.map(([k, v]) => `${k}: ${JSON.stringify(v)}`)\n if (fixturesGlob) configParts.push(\"fixtures\")\n if (viewFactories?.length) configParts.push(`views: [${viewFactories.map((v) => `${v.export}()`).join(\", \")}]`)\n\n lines.push(`createSimulator({ ${configParts.join(\", \")} })`)\n\n return lines.join(\"\\n\")\n}\n\n/** Vite plugin that injects the Puzzmo simulator in dev mode and handles OAuth callbacks. */\nexport function puzzmoSimulator(options: PuzzmoSimulatorPluginOptions = {}): Plugin {\n let games = new Map<string, GameInfo>()\n let viteRoot: string\n\n return {\n name: \"puzzmo-simulator\",\n apply: \"serve\",\n\n configResolved(config: ResolvedConfig) {\n viteRoot = config.root\n games = discoverGames(viteRoot)\n\n if (games.size === 0) {\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m\\x1b[2m no puzzmo.json files found\\x1b[22m`)\n } else {\n const names = [...games.values()].map((g) => `\\x1b[36m${g.slug}\\x1b[39m`)\n const label = games.size === 1 ? \"game\" : \"games\"\n config.logger.info(`\\x1b[33m\\x1b[1m PUZZMO \\x1b[22m\\x1b[39m found ${games.size} ${label}: ${names.join(\"\\x1b[2m, \\x1b[22m\")}`)\n }\n },\n\n resolveId(id) {\n if (id === virtualID || id.startsWith(virtualID + \"?\")) return \"\\0\" + id\n },\n\n load(id) {\n if (!id.startsWith(\"\\0\" + virtualID)) return\n const params = new URLSearchParams(id.split(\"?\")[1] || \"\")\n const gameSlug = params.get(\"game\")\n const game = gameSlug ? games.get(gameSlug) : games.size === 1 ? games.values().next().value : undefined\n return generateSimulatorCode(options, game)\n },\n\n configureServer(server) {\n // Re-read puzzmo.json on edit and reload the page so the simulator picks up its changes\n for (const g of games.values()) server.watcher.add(path.join(g.dir, \"puzzmo.json\"))\n server.watcher.on(\"change\", (file) => {\n if (path.basename(file) !== \"puzzmo.json\") return\n games = discoverGames(viteRoot)\n for (const mod of server.moduleGraph.idToModuleMap.values()) {\n if (mod.id?.startsWith(\"\\0\" + virtualID)) server.moduleGraph.invalidateModule(mod)\n }\n server.ws.send({ type: \"full-reload\" })\n })\n\n server.middlewares.use(\"/oauth/callback\", (_req, res) => {\n res.setHeader(\"Content-Type\", \"text/html\")\n res.end(`<!DOCTYPE html>\n<html><head><title>Puzzmo OAuth</title></head>\n<body><script>\nvar params = new URLSearchParams(window.location.search);\nvar returnUrl = sessionStorage.getItem(\"oauth_return_url\") || \"/\";\nvar url = new URL(returnUrl);\nparams.forEach(function(v, k) { url.searchParams.set(k, v); });\nwindow.location.href = url.toString();\n</script></body></html>`)\n })\n\n // Serve the simulator init module, resolving the game from the referer\n server.middlewares.use(async (req, res, next) => {\n if (req.url?.split(\"?\")[0] !== simulatorURL) return next()\n\n const game = resolveGameFromReferer(req.headers.referer, games, viteRoot)\n const moduleID = virtualID + (game ? `?game=${game.slug}` : \"\")\n const result = await server.transformRequest(moduleID)\n if (!result) return next()\n res.setHeader(\"Content-Type\", \"application/javascript\")\n res.end(result.code)\n })\n },\n\n transformIndexHtml() {\n return [\n {\n tag: \"script\",\n attrs: { type: \"module\", src: simulatorURL },\n injectTo: \"head\",\n },\n ]\n },\n }\n}\n\ntype BundlePluginOptions = {\n /** Entry file for the bundle */\n entry: string\n /** Output file name */\n outputFile: string\n}\n\nfunction createBundlePlugin(pluginName: string, defaults: BundlePluginOptions) {\n return (options: Partial<BundlePluginOptions> = {}): Plugin => {\n const { entry, outputFile } = { ...defaults, ...options }\n return {\n name: pluginName,\n apply: \"build\",\n async closeBundle() {\n // If the caller overrode `entry`, honor it as-is. Otherwise try `.js` first, then `.ts`.\n const resolvedEntry = options.entry\n ? path.isAbsolute(entry)\n ? entry\n : path.resolve(process.cwd(), entry)\n : (resolveBundleEntry(process.cwd(), stripBundleExt(entry)) ?? path.resolve(process.cwd(), entry))\n try {\n await build({\n configFile: false,\n logLevel: \"warn\",\n build: {\n lib: {\n entry: resolvedEntry,\n formats: [\"es\"],\n fileName: () => outputFile,\n },\n outDir: \"dist\",\n emptyOutDir: false,\n },\n })\n } catch (error) {\n console.error(`[${pluginName}] build failed:`, error)\n throw error\n }\n },\n }\n }\n}\n\n/** Strip the trailing extension from a default entry path so we can probe siblings. */\nconst stripBundleExt = (p: string) => p.replace(/\\.[jt]sx?$/i, \"\")\n\n/** Returns the absolute path to the first matching extension under `dir`, or null. */\nconst resolveBundleEntry = (dir: string, baseRelative: string): string | null => {\n // JSX last: a bundle written as JSX still needs the plain entry to win if both somehow exist.\n for (const ext of [\".js\", \".ts\", \".tsx\", \".jsx\"]) {\n const candidate = path.join(dir, baseRelative + ext)\n if (fs.existsSync(candidate)) return candidate\n }\n return null\n}\n\nexport type AppBundlePluginOptions = {\n /** Entry file for the app bundle (default: `src/appBundle.js`) */\n entry?: string\n /** Output file name (default: `app-bundle.js`) */\n outputFile?: string\n}\n\n/**\n * Vite plugin that produces dist/app-bundle.js after the main build for app-level integrations.\n *\n * The bundle exports `renderThumbnail(puzzleString, inputString?, config?)` — a pure renderer\n * returning the SVG and its dimensions (`{ svg, width, height }`), used by the Puzzmo\n * platform for puzzle previews.\n */\nexport const appBundlePlugin = createBundlePlugin(\"app-bundle\", { entry: \"src/appBundle.js\", outputFile: \"app-bundle.js\" })\n\nexport type EditorBundlePluginOptions = {\n /** Entry file for the editor bundle (default: `src/editorBundle.js`) */\n entry?: string\n /** Output file name (default: `editor-bundle.js`) */\n outputFile?: string\n}\n\n/** Vite plugin that produces dist/editor-bundle.js after the main build for editor-level integrations. */\nexport const editorBundlePlugin = createBundlePlugin(\"editor-bundle\", { entry: \"src/editorBundle.js\", outputFile: \"editor-bundle.js\" })\n\n/**\n * Recursively find directories containing puzzmo.json, up to `maxDepth` levels deep.\n *\n * @internal\n */\nexport const findPuzzmoJsonDirs = (root: string, maxDepth: number, depth = 0): string[] => {\n if (depth >= maxDepth) return []\n const results: string[] = []\n let entries: fs.Dirent[]\n try {\n entries = fs.readdirSync(root, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"node_modules\") continue\n const dir = path.join(root, entry.name)\n if (fs.existsSync(path.join(dir, \"puzzmo.json\"))) {\n results.push(dir)\n }\n results.push(...findPuzzmoJsonDirs(dir, maxDepth, depth + 1))\n }\n return results\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAgB,EAAc,GAAa,IAAoC,EAAE,EAAoB;;CACnG,IAAI;AACJ,KAAI,EAAQ,KAAM,KAAO,EAAK,QAAQ,GAAK,EAAQ,KAAK;MACnD;EACH,IAAM,IAAU,EAAK,KAAK,GAAK,OAAO,EAChC,IAAQ,EAAG,WAAW,EAAQ,GAAG,EAAG,YAAY,EAAQ,CAAC,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,GAAG,EAAE;AACpG,MAAI,EAAM,SAAS,EAAG,OAAU,MAAM,wBAAwB,EAAM,OAAO,YAAY,EAAQ,qCAAqC;AACpI,EAAI,EAAM,WAAW,MAAG,IAAO,EAAK,KAAK,GAAS,EAAM,GAAG;;AAE7D,KAAI,CAAC,KAAQ,CAAC,EAAG,WAAW,EAAK,CAAE,QAAO;CAC1C,IAAM,IAAO,EAAK,SAAS,GAAM,MAAM,EACjC,IAAY,EAAK,QAAQ,IAAA,IAAK,EAAQ,cAAA,OAAa,WAAb,EAAsB;AAClE,QAAO;EAAE;EAAK;EAAM;EAAM,YAAY,EAAK,KAAK,GAAW,GAAG,EAAK,OAAO;EAAE,UAAU,EAAK,KAAK,GAAW,GAAG,EAAK,KAAK;EAAE;;;;;;;AAQ5H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