skybridge 1.3.3 → 1.3.4

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.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ // @vitest-environment node
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { build } from "vite";
6
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
7
+ import { skybridge } from "./plugin.js";
8
+ /**
9
+ * Full `vite build` over a fixture whose stylesheet contains a `url()`. The
10
+ * unit test pins the `renderBuiltUrl` contract; this one proves Vite actually
11
+ * accepts what the plugin returns.
12
+ */
13
+ describe("skybridge plugin build", () => {
14
+ let root;
15
+ beforeEach(() => {
16
+ root = mkdtempSync(join(tmpdir(), "skybridge-build-"));
17
+ mkdirSync(join(root, "views"), { recursive: true });
18
+ mkdirSync(join(root, "src"), { recursive: true });
19
+ writeFileSync(join(root, "src/demo.woff2"), Buffer.alloc(64, 1));
20
+ writeFileSync(join(root, "src/styles.css"), [
21
+ "@font-face {",
22
+ ' font-family: "Demo";',
23
+ ' src: url("./demo.woff2") format("woff2");',
24
+ "}",
25
+ ].join("\n"));
26
+ writeFileSync(join(root, "src/entry.js"), `import "./styles.css";\n`);
27
+ });
28
+ afterEach(() => {
29
+ rmSync(root, { recursive: true, force: true });
30
+ });
31
+ it("builds a view stylesheet that references a font", async () => {
32
+ const result = await build({
33
+ root,
34
+ logLevel: "silent",
35
+ plugins: [skybridge({ viewsDir: join(root, "views") })],
36
+ build: {
37
+ // Force the font to be emitted as a file rather than inlined, so the
38
+ // stylesheet actually carries a `url()`.
39
+ assetsInlineLimit: 0,
40
+ rollupOptions: { input: { entry: join(root, "src/entry.js") } },
41
+ },
42
+ });
43
+ const outputs = (Array.isArray(result) ? result : [result]).flatMap((bundle) => ("output" in bundle ? bundle.output : []));
44
+ const css = outputs.find((chunk) => chunk.type === "asset" && chunk.fileName.endsWith(".css"));
45
+ if (css?.type !== "asset") {
46
+ throw new Error("no CSS asset was emitted");
47
+ }
48
+ // The font resolves relative to the stylesheet, which the server hands out
49
+ // from `${serverUrl}/assets/` — no runtime expression, which CSS can't run.
50
+ expect(String(css.source)).toMatch(/url\(\.\/demo-[\w-]+\.woff2\)/);
51
+ expect(String(css.source)).not.toContain("window.skybridge");
52
+ });
53
+ });
54
+ //# sourceMappingURL=plugin-build.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin-build.test.js","sourceRoot":"","sources":["../../../src/web/plugin/plugin-build.test.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,MAAM,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAExC;;;;GAIG;AACH,QAAQ,CAAC,wBAAwB,EAAE,GAAG,EAAE;IACtC,IAAI,IAAY,CAAC;IAEjB,UAAU,CAAC,GAAG,EAAE;QACd,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,kBAAkB,CAAC,CAAC,CAAC;QACvD,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QACpD,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;QAElD,aAAa,CAAC,IAAI,CAAC,IAA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ACF,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CACtB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,IAAI,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CACrE,CAAC;QACF,IAAI,GAAG,EAAE,IAAI,KAAK,OAAO,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;QAC9C,CAAC;QAED,2EAA2E;QAC3E,4EAA4E;QAC5E,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,+BAA+B,CAAC,CAAC;QACpE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,kBAAkB,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// @vitest-environment node\nimport { mkdirSync, mkdtempSync, rmSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { build } from \"vite\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\nimport { skybridge } from \"./plugin.js\";\n\n/**\n * Full `vite build` over a fixture whose stylesheet contains a `url()`. The\n * unit test pins the `renderBuiltUrl` contract; this one proves Vite actually\n * accepts what the plugin returns.\n */\ndescribe(\"skybridge plugin build\", () => {\n let root: string;\n\n beforeEach(() => {\n root = mkdtempSync(join(tmpdir(), \"skybridge-build-\"));\n mkdirSync(join(root, \"views\"), { recursive: true });\n mkdirSync(join(root, \"src\"), { recursive: true });\n\n writeFileSync(join(root, \"src/demo.woff2\"), Buffer.alloc(64, 1));\n writeFileSync(\n join(root, \"src/styles.css\"),\n [\n \"@font-face {\",\n ' font-family: \"Demo\";',\n ' src: url(\"./demo.woff2\") format(\"woff2\");',\n \"}\",\n ].join(\"\\n\"),\n );\n writeFileSync(join(root, \"src/entry.js\"), `import \"./styles.css\";\\n`);\n });\n\n afterEach(() => {\n rmSync(root, { recursive: true, force: true });\n });\n\n it(\"builds a view stylesheet that references a font\", async () => {\n const result = await build({\n root,\n logLevel: \"silent\",\n plugins: [skybridge({ viewsDir: join(root, \"views\") })],\n build: {\n // Force the font to be emitted as a file rather than inlined, so the\n // stylesheet actually carries a `url()`.\n assetsInlineLimit: 0,\n rollupOptions: { input: { entry: join(root, \"src/entry.js\") } },\n },\n });\n\n const outputs = (Array.isArray(result) ? result : [result]).flatMap(\n (bundle) => (\"output\" in bundle ? bundle.output : []),\n );\n const css = outputs.find(\n (chunk) => chunk.type === \"asset\" && chunk.fileName.endsWith(\".css\"),\n );\n if (css?.type !== \"asset\") {\n throw new Error(\"no CSS asset was emitted\");\n }\n\n // The font resolves relative to the stylesheet, which the server hands out\n // from `${serverUrl}/assets/` — no runtime expression, which CSS can't run.\n expect(String(css.source)).toMatch(/url\\(\\.\\/demo-[\\w-]+\\.woff2\\)/);\n expect(String(css.source)).not.toContain(\"window.skybridge\");\n });\n});\n"]}
@@ -101,10 +101,21 @@ export function skybridge(options) {
101
101
  include: ["react", "react-dom/client", "react/jsx-runtime"],
102
102
  },
103
103
  experimental: {
104
- renderBuiltUrl: (filename) => {
105
- return {
106
- runtime: `window.skybridge.serverUrl + "/assets/${filename}"`,
107
- };
104
+ renderBuiltUrl: (filename, { hostType }) => {
105
+ // Views render inside a host sandbox iframe, so `import.meta.url`
106
+ // points at the sandbox domain rather than the Skybridge server.
107
+ // JS asset references have to be resolved at runtime against
108
+ // `window.skybridge.serverUrl` so they follow tunnels too.
109
+ if (hostType === "js") {
110
+ return {
111
+ runtime: `window.skybridge.serverUrl + "/assets/${filename}"`,
112
+ };
113
+ }
114
+ // CSS has nowhere to evaluate a runtime expression — `vite:css-post`
115
+ // throws on one. It doesn't need it either: the stylesheet is served
116
+ // from `${serverUrl}/assets/…` and a relative `url()` resolves
117
+ // against the stylesheet's own URL, tunnel origin included.
118
+ return { relative: true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ClE,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { isAbsolute, relative, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n assertUniqueViewNames,\n type DiscoveredView,\n discoverViewsSync,\n scanViewsSync,\n writeViewsDts,\n} from \"./scan-views.js\";\nimport { transform as dataLlmTransform } from \"./transform-data-llm.js\";\nimport { hasDefaultExport } from \"./validate-view.js\";\n\nconst VIRTUAL_PREFIX = \"/_skybridge/view/\";\nconst VIRTUAL_MODULE_PREFIX = \"\\0skybridge:view:\";\n\n/** Options for the {@link skybridge} Vite plugin. */\nexport interface SkybridgePluginOptions {\n /** Directory scanned for view modules. Defaults to `\"src/views\"`. */\n viewsDir?: string;\n /**\n * Package names to leave unbundled when `skybridge build` bundles the server\n * for deployment. Use it for dependencies esbuild can't resolve or load —\n * typically optional native modules pulled in by a transitive dependency.\n */\n serverExternal?: string[];\n}\n\nfunction buildVirtualEntry(viewFilePath: string): string {\n const normalized = viewFilePath.replace(/\\\\/g, \"/\");\n return [\n `import { mountView } from \"skybridge/web\";`,\n `import Component from \"${normalized}\";`,\n `import { createElement } from \"react\";`,\n `mountView(createElement(Component));`,\n ].join(\"\\n\");\n}\n\nfunction getViewEntryPattern(viewsDir: string): RegExp {\n const escaped = viewsDir.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(\n `${escaped}\\\\/(?:[^/]+\\\\.(?:jsx|tsx)|[^/]+\\\\/index\\\\.(?:tsx|jsx))(?:\\\\?.*)?$`,\n );\n}\n\n/**\n * Vite plugin that wires a Skybridge project's view files into Vite.\n *\n * For each `.tsx` / `.jsx` file in `viewsDir` with a default export, the\n * plugin:\n * - exposes a virtual entry that calls {@link mountView} with the view's\n * default export,\n * - generates `.skybridge/views.d.ts` to augment {@link ViewNameRegistry} so\n * {@link ViewName} narrows to the actual view names,\n * - rewrites `<DataLLM>` JSX so the host can extract its content,\n * - warns in dev if a view file is missing a default export.\n *\n * Add it to your `vite.config.ts` alongside `@vitejs/plugin-react`.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from \"vite\";\n * import react from \"@vitejs/plugin-react\";\n * import { skybridge } from \"skybridge/vite\";\n *\n * export default defineConfig({\n * plugins: [react(), skybridge({ viewsDir: \"src/views\" })],\n * });\n * ```\n */\nexport function skybridge(options?: SkybridgePluginOptions): Plugin {\n const rawViewsDir = options?.viewsDir ?? \"src/views\";\n let resolvedViewsDir: string;\n let projectRoot: string;\n let viewMap = new Map<string, DiscoveredView>();\n let viewEntryPattern: RegExp;\n\n return {\n name: \"skybridge\",\n enforce: \"pre\",\n // Read by `skybridge build` to resolve viewsDir before `tsc -b` runs, and\n // to feed esbuild's external list when bundling the server.\n api: { viewsDir: rawViewsDir, serverExternal: options?.serverExternal },\n\n config(config) {\n projectRoot = config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(projectRoot, rawViewsDir);\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n\n const views = discoverViewsSync(resolvedViewsDir);\n viewMap = new Map(views.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, views);\n\n const input: Record<string, string> = {};\n for (const view of views) {\n input[view.name] = `${VIRTUAL_PREFIX}${view.name}`;\n }\n\n return {\n base: \"/assets\",\n // Fixes \"Invalid hook call\" on createStore by forcing a single\n // copy of React. Under pnpm's isolated node_modules, zustand\n // inside `skybridge` resolves React from skybridge's own\n // dependencies while the host app loads its own copy\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n },\n build: {\n outDir: \"dist/assets\",\n emptyOutDir: true,\n manifest: true,\n minify: true,\n cssCodeSplit: false,\n rollupOptions: {\n input,\n },\n },\n // Pre-bundle view deps at startup so the first tool invocation\n // doesn't hit Vite's on-demand re-optimization path (which sends\n // `full-reload` over HMR — in our iframe flow the parent host\n // can't honour a reload, and the view silently never mounts).\n optimizeDeps: {\n // Scan view files so transitive user deps (zod, tailwind, etc.)\n // get pre-bundled at startup.\n entries: [\n `${resolvedViewsDir}/*.{tsx,jsx}`,\n `${resolvedViewsDir}/*/index.{tsx,jsx}`,\n ],\n include: [\"react\", \"react-dom/client\", \"react/jsx-runtime\"],\n },\n experimental: {\n renderBuiltUrl: (filename) => {\n return {\n runtime: `window.skybridge.serverUrl + \"/assets/${filename}\"`,\n };\n },\n },\n };\n },\n\n resolveId(id) {\n if (id.startsWith(VIRTUAL_PREFIX)) {\n const name = id.slice(VIRTUAL_PREFIX.length);\n if (viewMap.has(name)) {\n return `${VIRTUAL_MODULE_PREFIX}${name}`;\n }\n }\n return null;\n },\n\n load(id) {\n if (id.startsWith(VIRTUAL_MODULE_PREFIX)) {\n const name = id.slice(VIRTUAL_MODULE_PREFIX.length);\n const view = viewMap.get(name);\n if (view) {\n return buildVirtualEntry(view.filePath);\n }\n }\n return null;\n },\n\n configureServer(server: ViteDevServer) {\n if (!resolvedViewsDir) {\n const root = server.config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(root, rawViewsDir);\n projectRoot = root;\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n }\n\n server.watcher.add(resolvedViewsDir);\n // Track which view files we've already warned about so a rescan\n // triggered by an unrelated edit doesn't re-emit the same warning.\n let knownInvalid = new Set<string>();\n const rescan = () => {\n try {\n // Surface broken view files. Without this, files lacking a\n // default export are silently dropped from the input and the\n // user has no idea why their widget never mounts.\n const { valid, invalid } = scanViewsSync(resolvedViewsDir);\n const nextInvalid = new Set(invalid.map((v) => v.filePath));\n\n for (const filePath of nextInvalid) {\n if (!knownInvalid.has(filePath)) {\n server.config.logger.warn(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" is missing a default export — it won't be served until fixed.`,\n );\n }\n }\n for (const filePath of knownInvalid) {\n if (!nextInvalid.has(filePath)) {\n server.config.logger.info(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" resolved.`,\n );\n }\n }\n knownInvalid = nextInvalid;\n\n assertUniqueViewNames(valid);\n viewMap = new Map(valid.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, valid);\n } catch (err) {\n // assertUniqueViewNames throws on duplicate view names. Catch so\n // chokidar's listener chain doesn't surface it as unhandled and\n // crash the dev server — previous viewMap stays active until\n // the user fixes the conflict.\n const message = err instanceof Error ? err.message : String(err);\n server.config.logger.error(\n `[skybridge] view rescan failed: ${message}`,\n );\n }\n };\n\n // Initial scan emits warnings for broken files that exist at startup.\n rescan();\n server.watcher.on(\"add\", rescan);\n server.watcher.on(\"change\", rescan);\n server.watcher.on(\"unlink\", rescan);\n },\n\n async transform(code, id) {\n if (viewEntryPattern?.test(id) && !hasDefaultExport(code, id)) {\n this.warn(\n `View file \"${id.split(\"/\").pop()}\" is missing a default export.`,\n );\n }\n\n return await dataLlmTransform(code, id);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../../../src/web/plugin/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAE1D,OAAO,EACL,qBAAqB,EAErB,iBAAiB,EACjB,aAAa,EACb,aAAa,GACd,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,IAAI,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,cAAc,GAAG,mBAAmB,CAAC;AAC3C,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAclD,SAAS,iBAAiB,CAAC,YAAoB;IAC7C,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACpD,OAAO;QACL,4CAA4C;QAC5C,0BAA0B,UAAU,IAAI;QACxC,w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;oBACb,iEAAiE;oBACjE,gEAAgE;oBAChE,6DAA6D;oBAC7D,+BAA+B;oBAC/B,MAAM,OAAO,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;oBACjE,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CACxB,mCAAmC,OAAO,EAAE,CAC7C,CAAC;gBACJ,CAAC;YACH,CAAC,CAAC;YAEF,sEAAsE;YACtE,MAAM,EAAE,CAAC;YACT,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;YACjC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YACpC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;QACtC,CAAC;QAED,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE;YACtB,IAAI,gBAAgB,EAAE,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC;gBAC9D,IAAI,CAAC,IAAI,CACP,cAAc,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,gCAAgC,CAClE,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,gBAAgB,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1C,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { isAbsolute, relative, resolve } from \"node:path\";\nimport type { Plugin, ViteDevServer } from \"vite\";\nimport {\n assertUniqueViewNames,\n type DiscoveredView,\n discoverViewsSync,\n scanViewsSync,\n writeViewsDts,\n} from \"./scan-views.js\";\nimport { transform as dataLlmTransform } from \"./transform-data-llm.js\";\nimport { hasDefaultExport } from \"./validate-view.js\";\n\nconst VIRTUAL_PREFIX = \"/_skybridge/view/\";\nconst VIRTUAL_MODULE_PREFIX = \"\\0skybridge:view:\";\n\n/** Options for the {@link skybridge} Vite plugin. */\nexport interface SkybridgePluginOptions {\n /** Directory scanned for view modules. Defaults to `\"src/views\"`. */\n viewsDir?: string;\n /**\n * Package names to leave unbundled when `skybridge build` bundles the server\n * for deployment. Use it for dependencies esbuild can't resolve or load —\n * typically optional native modules pulled in by a transitive dependency.\n */\n serverExternal?: string[];\n}\n\nfunction buildVirtualEntry(viewFilePath: string): string {\n const normalized = viewFilePath.replace(/\\\\/g, \"/\");\n return [\n `import { mountView } from \"skybridge/web\";`,\n `import Component from \"${normalized}\";`,\n `import { createElement } from \"react\";`,\n `mountView(createElement(Component));`,\n ].join(\"\\n\");\n}\n\nfunction getViewEntryPattern(viewsDir: string): RegExp {\n const escaped = viewsDir.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(\n `${escaped}\\\\/(?:[^/]+\\\\.(?:jsx|tsx)|[^/]+\\\\/index\\\\.(?:tsx|jsx))(?:\\\\?.*)?$`,\n );\n}\n\n/**\n * Vite plugin that wires a Skybridge project's view files into Vite.\n *\n * For each `.tsx` / `.jsx` file in `viewsDir` with a default export, the\n * plugin:\n * - exposes a virtual entry that calls {@link mountView} with the view's\n * default export,\n * - generates `.skybridge/views.d.ts` to augment {@link ViewNameRegistry} so\n * {@link ViewName} narrows to the actual view names,\n * - rewrites `<DataLLM>` JSX so the host can extract its content,\n * - warns in dev if a view file is missing a default export.\n *\n * Add it to your `vite.config.ts` alongside `@vitejs/plugin-react`.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { defineConfig } from \"vite\";\n * import react from \"@vitejs/plugin-react\";\n * import { skybridge } from \"skybridge/vite\";\n *\n * export default defineConfig({\n * plugins: [react(), skybridge({ viewsDir: \"src/views\" })],\n * });\n * ```\n */\nexport function skybridge(options?: SkybridgePluginOptions): Plugin {\n const rawViewsDir = options?.viewsDir ?? \"src/views\";\n let resolvedViewsDir: string;\n let projectRoot: string;\n let viewMap = new Map<string, DiscoveredView>();\n let viewEntryPattern: RegExp;\n\n return {\n name: \"skybridge\",\n enforce: \"pre\",\n // Read by `skybridge build` to resolve viewsDir before `tsc -b` runs, and\n // to feed esbuild's external list when bundling the server.\n api: { viewsDir: rawViewsDir, serverExternal: options?.serverExternal },\n\n config(config) {\n projectRoot = config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(projectRoot, rawViewsDir);\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n\n const views = discoverViewsSync(resolvedViewsDir);\n viewMap = new Map(views.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, views);\n\n const input: Record<string, string> = {};\n for (const view of views) {\n input[view.name] = `${VIRTUAL_PREFIX}${view.name}`;\n }\n\n return {\n base: \"/assets\",\n // Fixes \"Invalid hook call\" on createStore by forcing a single\n // copy of React. Under pnpm's isolated node_modules, zustand\n // inside `skybridge` resolves React from skybridge's own\n // dependencies while the host app loads its own copy\n resolve: {\n dedupe: [\"react\", \"react-dom\"],\n },\n build: {\n outDir: \"dist/assets\",\n emptyOutDir: true,\n manifest: true,\n minify: true,\n cssCodeSplit: false,\n rollupOptions: {\n input,\n },\n },\n // Pre-bundle view deps at startup so the first tool invocation\n // doesn't hit Vite's on-demand re-optimization path (which sends\n // `full-reload` over HMR — in our iframe flow the parent host\n // can't honour a reload, and the view silently never mounts).\n optimizeDeps: {\n // Scan view files so transitive user deps (zod, tailwind, etc.)\n // get pre-bundled at startup.\n entries: [\n `${resolvedViewsDir}/*.{tsx,jsx}`,\n `${resolvedViewsDir}/*/index.{tsx,jsx}`,\n ],\n include: [\"react\", \"react-dom/client\", \"react/jsx-runtime\"],\n },\n experimental: {\n renderBuiltUrl: (filename, { hostType }) => {\n // Views render inside a host sandbox iframe, so `import.meta.url`\n // points at the sandbox domain rather than the Skybridge server.\n // JS asset references have to be resolved at runtime against\n // `window.skybridge.serverUrl` so they follow tunnels too.\n if (hostType === \"js\") {\n return {\n runtime: `window.skybridge.serverUrl + \"/assets/${filename}\"`,\n };\n }\n // CSS has nowhere to evaluate a runtime expression — `vite:css-post`\n // throws on one. It doesn't need it either: the stylesheet is served\n // from `${serverUrl}/assets/…` and a relative `url()` resolves\n // against the stylesheet's own URL, tunnel origin included.\n return { relative: true };\n },\n },\n };\n },\n\n resolveId(id) {\n if (id.startsWith(VIRTUAL_PREFIX)) {\n const name = id.slice(VIRTUAL_PREFIX.length);\n if (viewMap.has(name)) {\n return `${VIRTUAL_MODULE_PREFIX}${name}`;\n }\n }\n return null;\n },\n\n load(id) {\n if (id.startsWith(VIRTUAL_MODULE_PREFIX)) {\n const name = id.slice(VIRTUAL_MODULE_PREFIX.length);\n const view = viewMap.get(name);\n if (view) {\n return buildVirtualEntry(view.filePath);\n }\n }\n return null;\n },\n\n configureServer(server: ViteDevServer) {\n if (!resolvedViewsDir) {\n const root = server.config.root || process.cwd();\n resolvedViewsDir = isAbsolute(rawViewsDir)\n ? rawViewsDir\n : resolve(root, rawViewsDir);\n projectRoot = root;\n viewEntryPattern = getViewEntryPattern(resolvedViewsDir);\n }\n\n server.watcher.add(resolvedViewsDir);\n // Track which view files we've already warned about so a rescan\n // triggered by an unrelated edit doesn't re-emit the same warning.\n let knownInvalid = new Set<string>();\n const rescan = () => {\n try {\n // Surface broken view files. Without this, files lacking a\n // default export are silently dropped from the input and the\n // user has no idea why their widget never mounts.\n const { valid, invalid } = scanViewsSync(resolvedViewsDir);\n const nextInvalid = new Set(invalid.map((v) => v.filePath));\n\n for (const filePath of nextInvalid) {\n if (!knownInvalid.has(filePath)) {\n server.config.logger.warn(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" is missing a default export — it won't be served until fixed.`,\n );\n }\n }\n for (const filePath of knownInvalid) {\n if (!nextInvalid.has(filePath)) {\n server.config.logger.info(\n `[skybridge] view file \"${relative(projectRoot, filePath)}\" resolved.`,\n );\n }\n }\n knownInvalid = nextInvalid;\n\n assertUniqueViewNames(valid);\n viewMap = new Map(valid.map((v) => [v.name, v]));\n writeViewsDts(projectRoot, valid);\n } catch (err) {\n // assertUniqueViewNames throws on duplicate view names. Catch so\n // chokidar's listener chain doesn't surface it as unhandled and\n // crash the dev server — previous viewMap stays active until\n // the user fixes the conflict.\n const message = err instanceof Error ? err.message : String(err);\n server.config.logger.error(\n `[skybridge] view rescan failed: ${message}`,\n );\n }\n };\n\n // Initial scan emits warnings for broken files that exist at startup.\n rescan();\n server.watcher.on(\"add\", rescan);\n server.watcher.on(\"change\", rescan);\n server.watcher.on(\"unlink\", rescan);\n },\n\n async transform(code, id) {\n if (viewEntryPattern?.test(id) && !hasDefaultExport(code, id)) {\n this.warn(\n `View file \"${id.split(\"/\").pop()}\" is missing a default export.`,\n );\n }\n\n return await dataLlmTransform(code, id);\n },\n };\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,61 @@
1
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
+ import { skybridge } from "./plugin.js";
6
+ function getRenderBuiltUrl(root) {
7
+ const plugin = skybridge({ viewsDir: join(root, "views") });
8
+ const hook = plugin.config;
9
+ if (!hook) {
10
+ throw new Error("plugin.config is not defined");
11
+ }
12
+ const handler = typeof hook === "function" ? hook : hook.handler;
13
+ const config = handler.call(
14
+ // biome-ignore lint/suspicious/noExplicitAny: vitest harness for plugin hook
15
+ {}, { root }, { command: "build", mode: "production" });
16
+ const renderBuiltUrl = config.experimental?.renderBuiltUrl;
17
+ if (!renderBuiltUrl) {
18
+ throw new Error("experimental.renderBuiltUrl is not defined");
19
+ }
20
+ return renderBuiltUrl;
21
+ }
22
+ describe("skybridge plugin renderBuiltUrl", () => {
23
+ let root;
24
+ beforeEach(() => {
25
+ root = mkdtempSync(join(tmpdir(), "skybridge-plugin-"));
26
+ mkdirSync(join(root, "views"), { recursive: true });
27
+ });
28
+ afterEach(() => {
29
+ rmSync(root, { recursive: true, force: true });
30
+ });
31
+ // Assets referenced from JS can't use `import.meta.url`: views render in a
32
+ // host sandbox iframe (web-sandbox.oaiusercontent.com), so the module origin
33
+ // doesn't point back at the Skybridge server. They have to be resolved at
34
+ // runtime against `window.skybridge.serverUrl` instead.
35
+ it("resolves JS asset references against window.skybridge.serverUrl", () => {
36
+ const renderBuiltUrl = getRenderBuiltUrl(root);
37
+ expect(renderBuiltUrl("assets/logo-BXtQ8kd2.png", {
38
+ hostId: "assets/view-CwF9pQ1a.js",
39
+ hostType: "js",
40
+ type: "asset",
41
+ ssr: false,
42
+ })).toEqual({
43
+ runtime: `window.skybridge.serverUrl + "/assets/assets/logo-BXtQ8kd2.png"`,
44
+ });
45
+ });
46
+ // Reproducer for the CSS build failure: Vite has nowhere to evaluate a
47
+ // runtime expression inside a stylesheet, so `{ runtime }` makes
48
+ // `vite:css-post` throw for any `url()` in CSS. It isn't needed either — the
49
+ // stylesheet is served from `${serverUrl}/assets/…`, and a relative `url()`
50
+ // resolves against the stylesheet's own URL, tunnel origin included.
51
+ it("resolves CSS asset references relatively", () => {
52
+ const renderBuiltUrl = getRenderBuiltUrl(root);
53
+ expect(renderBuiltUrl("assets/demo-0IQFxQqs.woff2", {
54
+ hostId: "assets/style-DmQ2xY7b.css",
55
+ hostType: "css",
56
+ type: "asset",
57
+ ssr: false,
58
+ })).toEqual({ relative: true });
59
+ });
60
+ });
61
+ //# sourceMappingURL=plugin.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.test.js","sourceRoot":"","sources":["../../../src/web/plugin/plugin.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACzD,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,SAAS,EAAE,UAA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CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IACjD,CAAC,CAAC,CAAC;IAEH,2EAA2E;IAC3E,6EAA6E;IAC7E,0EAA0E;IAC1E,wDAAwD;IACxD,EAAE,CAAC,iEAAiE,EAAE,GAAG,EAAE;QACzE,MAAM,cAAc,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;QAE/C,MAAM,CACJ,cAAc,CAAC,0BAA0B,EAAE;YACzC,MAAM,EAAE,yBAAyB;YACjC,QAAQ,EAAE,IAAI;YACd,IAAI,EAAE,OAAO;YACb,GAAG,EAAE,KAAK;SACX,CAAC,CACH,CAAC,OAAO,CAAC;YACR,OAAO,EAAE,iEAAiE;SAC3E,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,uEAAuE;IACvE,iEAAiE;IACjE,6EAA6E;IAC7E,4EAA4E;IAC5E,qEAAqE;IACrE,EAAE,CAAC,0CAA0C,EAAE,GAAG,EAAE;QAClD,MAAM,cAAc,GAAG,iBAAiB,CAAC,IAAI,CAAC,CAAC;QAE/C,MAAM,CACJ,cAAc,CAAC,4BAA4B,EAAE;YAC3C,MAAM,EAAE,2BAA2B;YACnC,QAAQ,EAAE,KAAK;YACf,IAAI,EAAE,OAAO;YACb,GAAG,EAAE,KAAK;SACX,CAAC,CACH,CAAC,OAAO,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { mkdirSync, mkdtempSync, rmSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { UserConfig } from \"vite\";\nimport { afterEach, beforeEach, describe, expect, it } from \"vitest\";\nimport { skybridge } from \"./plugin.js\";\n\ntype RenderBuiltUrl = NonNullable<\n NonNullable<UserConfig[\"experimental\"]>[\"renderBuiltUrl\"]\n>;\n\nfunction getRenderBuiltUrl(root: string): RenderBuiltUrl {\n const plugin = skybridge({ viewsDir: join(root, \"views\") });\n const hook = plugin.config;\n if (!hook) {\n throw new Error(\"plugin.config is not defined\");\n }\n const handler = typeof hook === \"function\" ? hook : hook.handler;\n const config = handler.call(\n // biome-ignore lint/suspicious/noExplicitAny: vitest harness for plugin hook\n {} as any,\n { root },\n { command: \"build\", mode: \"production\" },\n ) as UserConfig;\n\n const renderBuiltUrl = config.experimental?.renderBuiltUrl;\n if (!renderBuiltUrl) {\n throw new Error(\"experimental.renderBuiltUrl is not defined\");\n }\n return renderBuiltUrl;\n}\n\ndescribe(\"skybridge plugin renderBuiltUrl\", () => {\n let root: string;\n\n beforeEach(() => {\n root = mkdtempSync(join(tmpdir(), \"skybridge-plugin-\"));\n mkdirSync(join(root, \"views\"), { recursive: true });\n });\n\n afterEach(() => {\n rmSync(root, { recursive: true, force: true });\n });\n\n // Assets referenced from JS can't use `import.meta.url`: views render in a\n // host sandbox iframe (web-sandbox.oaiusercontent.com), so the module origin\n // doesn't point back at the Skybridge server. They have to be resolved at\n // runtime against `window.skybridge.serverUrl` instead.\n it(\"resolves JS asset references against window.skybridge.serverUrl\", () => {\n const renderBuiltUrl = getRenderBuiltUrl(root);\n\n expect(\n renderBuiltUrl(\"assets/logo-BXtQ8kd2.png\", {\n hostId: \"assets/view-CwF9pQ1a.js\",\n hostType: \"js\",\n type: \"asset\",\n ssr: false,\n }),\n ).toEqual({\n runtime: `window.skybridge.serverUrl + \"/assets/assets/logo-BXtQ8kd2.png\"`,\n });\n });\n\n // Reproducer for the CSS build failure: Vite has nowhere to evaluate a\n // runtime expression inside a stylesheet, so `{ runtime }` makes\n // `vite:css-post` throw for any `url()` in CSS. It isn't needed either — the\n // stylesheet is served from `${serverUrl}/assets/…`, and a relative `url()`\n // resolves against the stylesheet's own URL, tunnel origin included.\n it(\"resolves CSS asset references relatively\", () => {\n const renderBuiltUrl = getRenderBuiltUrl(root);\n\n expect(\n renderBuiltUrl(\"assets/demo-0IQFxQqs.woff2\", {\n hostId: \"assets/style-DmQ2xY7b.css\",\n hostType: \"css\",\n type: \"asset\",\n ssr: false,\n }),\n ).toEqual({ relative: true });\n });\n});\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skybridge",
3
- "version": "1.3.3",
3
+ "version": "1.3.4",
4
4
  "description": "Skybridge is a framework for building ChatGPT and MCP Apps",
5
5
  "repository": {
6
6
  "type": "git",