@jami-studio/core 0.92.23 → 0.92.25

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.
@@ -1,5 +1,17 @@
1
1
  # @agent-native/core
2
2
 
3
+ ## 0.92.25
4
+
5
+ ### Patch Changes
6
+
7
+ - faf05e0: Cloudflare worker bundles the real @anthropic-ai/sdk instead of an empty-class stub. The SDK is pure fetch-based JS that runs on workerd, and the BYOK Anthropic agent engine constructs it at runtime — the stub made every agent chat run on a Cloudflare deployment die with "Cannot read properties of undefined (reading 'stream')". The WASM tokenizer stays stubbed (token counts degrade to estimates).
8
+
9
+ ## 0.92.24
10
+
11
+ ### Patch Changes
12
+
13
+ - 300ff1a: Dedupe Yjs in Cloudflare worker bundles. The per-app cloudflare_pages build keeps `yjs` external and emits it as a standalone `_worker.js/_libs/yjs.mjs` (bare imports rewritten to it); unified workspace deploys then hoist ONE shared copy to `dist/_yjs/yjs.mjs` and shim every app's lib to re-export it, so wrangler's final re-bundle instantiates Yjs exactly once. Fixes the "Yjs was already imported. This breaks constructor checks" error logged once per extra app copy per isolate and removes the cross-copy instanceof risk in real-time collab.
14
+
3
15
  ## 0.92.23
4
16
 
5
17
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-native/core",
3
- "version": "0.92.23",
3
+ "version": "0.92.25",
4
4
  "description": "Framework for agent-native application development — where AI agents and UI share SQL state, actions, and context",
5
5
  "homepage": "https://github.com/studio-jami/jami-studio#readme",
6
6
  "bugs": {
@@ -134,7 +134,12 @@ export const CLOUDFLARE_WORKER_STUB_MODULES: Record<string, string> = {
134
134
  chokidar: "export default {}; export const watch = () => ({ close() {} });\n",
135
135
  fsevents: "export default {}; export const watch = () => ({ close() {} });\n",
136
136
  dotenv: "export default {}; export const config = () => ({ parsed: {} });\n",
137
- "@anthropic-ai/sdk": "export default class Anthropic {}\n",
137
+ // NOTE: @anthropic-ai/sdk is deliberately NOT stubbed. It is pure
138
+ // fetch-based JS that runs fine on workerd, and the BYOK Anthropic engine
139
+ // (agent chat) constructs it at runtime — an empty-class stub makes every
140
+ // agent run die with "Cannot read properties of undefined (reading
141
+ // 'stream')". Only its tokenizer (WASM, unbundleable) stays stubbed; the
142
+ // token-count call sites degrade to char/4 estimates.
138
143
  "@anthropic-ai/tokenizer":
139
144
  "export default {}; export const countTokens = undefined;\n",
140
145
  "@sentry/node": [
@@ -1826,6 +1831,13 @@ async function buildCloudflarePages() {
1826
1831
  "--conditions=workerd,worker,import",
1827
1832
  // The ssr-handler imports a virtual module that only exists at dev time
1828
1833
  "--external:virtual:react-router/server-build",
1834
+ // Keep Yjs out of the monolithic bundle so it can be emitted as a
1835
+ // standalone _libs/yjs.mjs below. On unified workspace deploys the
1836
+ // workspace assembly step points every app's lib at ONE shared copy so
1837
+ // wrangler's final re-bundle instantiates Yjs exactly once — inlining it
1838
+ // here would put N copies in a single isolate (Yjs logs "Yjs was already
1839
+ // imported" per extra copy and cross-copy instanceof checks break).
1840
+ "--external:yjs",
1829
1841
  `--alias:#nitro/virtual/server-assets=${nitroServerAssetsStub}`,
1830
1842
  // Banner: override the __require shim that esbuild generates for CJS modules.
1831
1843
  // This provides a real require() backed by ESM imports of node builtins.
@@ -1845,6 +1857,15 @@ async function buildCloudflarePages() {
1845
1857
  cwd,
1846
1858
  });
1847
1859
 
1860
+ // Bundle the one real Yjs copy into _libs/yjs.mjs and rewrite the bare
1861
+ // imports the --external:yjs flag left behind (see the flag comment above).
1862
+ bundleSharedYjsLibForWorkerOutput({
1863
+ workerOutDir,
1864
+ esbuildBin,
1865
+ projectCwd: cwd,
1866
+ tmpDir,
1867
+ });
1868
+
1848
1869
  // Clean up tmp
1849
1870
  fs.rmSync(tmpDir, { recursive: true });
1850
1871
 
@@ -2694,6 +2715,112 @@ export function rewriteBareYjsImportsForServerlessOutput(
2694
2715
  return bareImports;
2695
2716
  }
2696
2717
 
2718
+ /**
2719
+ * Resolve Yjs's ESM entry for bundling into a worker `_libs/yjs.mjs`.
2720
+ * Templates don't depend on `yjs` directly (it's a core dependency), so when
2721
+ * the project itself can't resolve it, resolve through the installed
2722
+ * `@agent-native/core` package location instead.
2723
+ */
2724
+ export function resolveYjsEsmEntry(projectCwd: string): string | null {
2725
+ const resolveFrom = (base: string): string | null => {
2726
+ try {
2727
+ return createRequire(path.join(base, "package.json")).resolve("yjs");
2728
+ } catch {
2729
+ return null;
2730
+ }
2731
+ };
2732
+ let resolved = resolveFrom(projectCwd);
2733
+ if (!resolved) {
2734
+ try {
2735
+ const corePkg = createRequire(
2736
+ path.join(projectCwd, "package.json"),
2737
+ ).resolve("@agent-native/core/package.json");
2738
+ resolved = resolveFrom(path.dirname(fs.realpathSync(corePkg)));
2739
+ } catch {
2740
+ resolved = null;
2741
+ }
2742
+ }
2743
+ if (!resolved) return null;
2744
+ // require.resolve returns the CJS entry; prefer the sibling ESM build so
2745
+ // `export * from` re-exports Yjs's real named exports statically.
2746
+ const esmSibling = resolved.replace(/\.c?js$/, ".mjs");
2747
+ return esmSibling !== resolved && fs.existsSync(esmSibling)
2748
+ ? esmSibling
2749
+ : resolved;
2750
+ }
2751
+
2752
+ /**
2753
+ * Emit Yjs as a standalone `_libs/yjs.mjs` in the Cloudflare worker output
2754
+ * and rewrite every bare `yjs` import (left external by the main esbuild
2755
+ * bundle) to it. Keeping Yjs in its own module file is what lets the unified
2756
+ * workspace assembly (`workspace-deploy.ts`) collapse all apps onto ONE
2757
+ * shared copy — wrangler's final re-bundle dedupes modules by file path, so
2758
+ * N inlined copies would otherwise land in a single isolate and trip Yjs's
2759
+ * "Yjs was already imported. This breaks constructor checks" guard.
2760
+ */
2761
+ export function bundleSharedYjsLibForWorkerOutput(opts: {
2762
+ workerOutDir: string;
2763
+ esbuildBin: string;
2764
+ projectCwd: string;
2765
+ tmpDir: string;
2766
+ }): string[] {
2767
+ const { workerOutDir, esbuildBin, projectCwd, tmpDir } = opts;
2768
+
2769
+ // Fail loud on CJS require sites — the import rewrite below cannot fix a
2770
+ // `require("yjs")`, and leaving one would crash at runtime instead.
2771
+ const requireSites: string[] = [];
2772
+ let hasBareImport = false;
2773
+ walkServerJavaScriptFiles(workerOutDir, (filePath) => {
2774
+ const source = fs.readFileSync(filePath, "utf-8");
2775
+ if (/\brequire\(\s*["']yjs["']\s*\)/.test(source)) {
2776
+ requireSites.push(filePath);
2777
+ }
2778
+ if (hasBareYjsRuntimeImport(source)) hasBareImport = true;
2779
+ });
2780
+ if (requireSites.length > 0) {
2781
+ throw new Error(
2782
+ `[deploy] Cloudflare worker output left CJS require("yjs") sites the Yjs lib rewrite cannot fix: ${requireSites.join(", ")}`,
2783
+ );
2784
+ }
2785
+ if (!hasBareImport) return [];
2786
+
2787
+ const yjsEntry = resolveYjsEsmEntry(projectCwd);
2788
+ if (!yjsEntry) {
2789
+ throw new Error(
2790
+ "[deploy] Cloudflare worker output imports yjs but the package could not be resolved for _libs bundling",
2791
+ );
2792
+ }
2793
+
2794
+ const libsDir = path.join(workerOutDir, "_libs");
2795
+ fs.mkdirSync(libsDir, { recursive: true });
2796
+ const entryFile = path.join(tmpDir, "_yjs-lib-entry.js");
2797
+ // Forward slashes: backslashes in an import specifier are escape sequences.
2798
+ fs.writeFileSync(
2799
+ entryFile,
2800
+ `export * from "${yjsEntry.split(path.sep).join("/")}";\n`,
2801
+ );
2802
+ const command = esbuildSpawnCommand(esbuildBin, [
2803
+ entryFile,
2804
+ "--bundle",
2805
+ `--outfile=${path.join(libsDir, "yjs.mjs")}`,
2806
+ "--format=esm",
2807
+ "--platform=browser",
2808
+ "--target=es2022",
2809
+ "--minify",
2810
+ "--conditions=workerd,worker,import",
2811
+ ]);
2812
+ execFileSync(command.file, command.args, {
2813
+ stdio: "inherit",
2814
+ cwd: projectCwd,
2815
+ });
2816
+
2817
+ const rewritten = rewriteBareYjsImportsForServerlessOutput(workerOutDir);
2818
+ console.log(
2819
+ `[deploy] Bundled yjs into _libs/yjs.mjs (${rewritten.length} import site file(s) rewritten)`,
2820
+ );
2821
+ return rewritten;
2822
+ }
2823
+
2697
2824
  export function assertSingleTemplateNetlifyBuildOutput(
2698
2825
  projectCwd: string,
2699
2826
  ): void {
@@ -178,6 +178,7 @@ export async function runWorkspaceDeploy(
178
178
  } else if (preset === "vercel") {
179
179
  writeVercelBuildConfig(vercelOutputDir, apps);
180
180
  } else {
181
+ dedupeCloudflareWorkspaceYjs(distDir, apps);
181
182
  writeCloudflareRoutingManifest(distDir, apps);
182
183
  }
183
184
 
@@ -405,6 +406,58 @@ function copyVercelAppBuildIntoWorkspace(
405
406
  patchVercelFunctionEntry(functionDest, app, workspaceApps);
406
407
  }
407
408
 
409
+ /**
410
+ * Collapse every app's Yjs copy onto ONE shared module in the unified
411
+ * Cloudflare artifact. wrangler re-bundles all app workers into a single
412
+ * final bundle behind the dispatcher, so per-app Yjs copies all land in one
413
+ * isolate — Yjs's own guard logs "Yjs was already imported. This breaks
414
+ * constructor checks" once per extra copy, and Yjs objects crossing copies
415
+ * fail instanceof checks (real-time collab risk). Per-app builds emit Yjs as
416
+ * a standalone `dist/<app>/_worker.js/_libs/yjs.mjs` (see deploy/build.ts);
417
+ * here the first copy is hoisted to `dist/_yjs/yjs.mjs` and every app's lib
418
+ * becomes a re-export shim of it, so esbuild's path-keyed module dedupe
419
+ * instantiates Yjs exactly once.
420
+ */
421
+ export function dedupeCloudflareWorkspaceYjs(
422
+ distDir: string,
423
+ apps: string[],
424
+ ): string[] {
425
+ const libPaths = apps
426
+ .map((app) => path.join(distDir, app, "_worker.js", "_libs", "yjs.mjs"))
427
+ .filter((libPath) => fs.existsSync(libPath));
428
+ if (libPaths.length === 0) return [];
429
+
430
+ const sharedFile = path.join(distDir, "_yjs", "yjs.mjs");
431
+ fs.mkdirSync(path.dirname(sharedFile), { recursive: true });
432
+ fs.copyFileSync(libPaths[0], sharedFile);
433
+ for (const libPath of libPaths) {
434
+ const rel = path
435
+ .relative(path.dirname(libPath), sharedFile)
436
+ .split(path.sep)
437
+ .join("/");
438
+ fs.writeFileSync(
439
+ libPath,
440
+ `export * from "${rel.startsWith(".") ? rel : `./${rel}`}";\n`,
441
+ );
442
+ }
443
+
444
+ // Keep the shared module (and the dispatcher worker) out of the public
445
+ // static asset set. `.assetsignore` is only honored at the output root.
446
+ const assetsIgnorePath = path.join(distDir, ".assetsignore");
447
+ const existing = fs.existsSync(assetsIgnorePath)
448
+ ? fs.readFileSync(assetsIgnorePath, "utf-8")
449
+ : "";
450
+ const lines = new Set(existing.split(/\r?\n/).filter(Boolean));
451
+ lines.add("_worker.js");
452
+ lines.add("_yjs");
453
+ fs.writeFileSync(assetsIgnorePath, [...lines].join("\n") + "\n");
454
+
455
+ console.log(
456
+ `[workspace-deploy] Deduped yjs across ${libPaths.length} app worker(s) into _yjs/yjs.mjs`,
457
+ );
458
+ return libPaths;
459
+ }
460
+
408
461
  /**
409
462
  * Write the Cloudflare Pages `_routes.json` and a dispatcher `_worker.js` at
410
463
  * the workspace dist root so each app is reachable under /<app>/*.
@@ -435,8 +488,7 @@ function writeCloudflareRoutingManifest(distDir: string, apps: string[]): void {
435
488
  const dedupedInclude = [
436
489
  ...new Set(
437
490
  include.filter(
438
- (r) =>
439
- !splatPrefixes.some((p) => r !== `${p}*` && r.startsWith(p)),
491
+ (r) => !splatPrefixes.some((p) => r !== `${p}*` && r.startsWith(p)),
440
492
  ),
441
493
  ),
442
494
  ];
@@ -179,6 +179,28 @@ export declare function emitSingleTemplateNetlifyBackgroundFunction(projectCwd:
179
179
  * bundled copy before its function is packaged.
180
180
  */
181
181
  export declare function rewriteBareYjsImportsForServerlessOutput(serverDir: string): string[];
182
+ /**
183
+ * Resolve Yjs's ESM entry for bundling into a worker `_libs/yjs.mjs`.
184
+ * Templates don't depend on `yjs` directly (it's a core dependency), so when
185
+ * the project itself can't resolve it, resolve through the installed
186
+ * `@agent-native/core` package location instead.
187
+ */
188
+ export declare function resolveYjsEsmEntry(projectCwd: string): string | null;
189
+ /**
190
+ * Emit Yjs as a standalone `_libs/yjs.mjs` in the Cloudflare worker output
191
+ * and rewrite every bare `yjs` import (left external by the main esbuild
192
+ * bundle) to it. Keeping Yjs in its own module file is what lets the unified
193
+ * workspace assembly (`workspace-deploy.ts`) collapse all apps onto ONE
194
+ * shared copy — wrangler's final re-bundle dedupes modules by file path, so
195
+ * N inlined copies would otherwise land in a single isolate and trip Yjs's
196
+ * "Yjs was already imported. This breaks constructor checks" guard.
197
+ */
198
+ export declare function bundleSharedYjsLibForWorkerOutput(opts: {
199
+ workerOutDir: string;
200
+ esbuildBin: string;
201
+ projectCwd: string;
202
+ tmpDir: string;
203
+ }): string[];
182
204
  export declare function assertSingleTemplateNetlifyBuildOutput(projectCwd: string): void;
183
205
  /**
184
206
  * Strip the harmful single-template catch-all rewrite that points at
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/deploy/build.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;;GAYG;AAmCH,OAAO,EAML,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,qBAAqB,CAAC;AAI7B,eAAO,MAAM,6BAA6B,UAiBzC,CAAC;AAEF,eAAO,MAAM,mCAAmC,UAiB/C,CAAC;AACF,eAAO,MAAM,8BAA8B,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAkIjE,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,uBAAuB,UAUnC,CAAC;AAEF,wBAAgB,6BAA6B,CAC3C,MAAM,EAAE,MAAM,GACb,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAaxB;AAoCD,eAAO,MAAM,2CAA2C,EAAE,MAAM,CAC9D,MAAM,EACN,MAAM,CAmSP,CAAC;AAEF,MAAM,WAAW,0BAA0B;IACzC,qBAAqB,CAAC,EAAE,OAAO,CAAC;CACjC;AAED,UAAU,wBAAwB;IAChC,KAAK,EAAE,6BAA6B,CAAC;I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I,CAAC,CAAC;CAC3C;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,GAAG,CAAC;IACX,KAAK,EAAE,eAAe,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,qBAAqB,CACzC,IAAI,EAAE,yBAAyB,GAC9B,OAAO,CAAC,IAAI,CAAC,CA+Bf;AAkBD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,iCAAiC,YAAI,KAAK,CAAU,CAAC;AAElE;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,YAAY,EAAE,MAAM,GACnB,IAAI,GAAG,SAAS,MAAM,EAAE,CAK1B"}
@@ -96,7 +96,12 @@ export const CLOUDFLARE_WORKER_STUB_MODULES = {
96
96
  chokidar: "export default {}; export const watch = () => ({ close() {} });\n",
97
97
  fsevents: "export default {}; export const watch = () => ({ close() {} });\n",
98
98
  dotenv: "export default {}; export const config = () => ({ parsed: {} });\n",
99
- "@anthropic-ai/sdk": "export default class Anthropic {}\n",
99
+ // NOTE: @anthropic-ai/sdk is deliberately NOT stubbed. It is pure
100
+ // fetch-based JS that runs fine on workerd, and the BYOK Anthropic engine
101
+ // (agent chat) constructs it at runtime — an empty-class stub makes every
102
+ // agent run die with "Cannot read properties of undefined (reading
103
+ // 'stream')". Only its tokenizer (WASM, unbundleable) stays stubbed; the
104
+ // token-count call sites degrade to char/4 estimates.
100
105
  "@anthropic-ai/tokenizer": "export default {}; export const countTokens = undefined;\n",
101
106
  "@sentry/node": [
102
107
  "export const init = () => {};",
@@ -1508,6 +1513,13 @@ async function buildCloudflarePages() {
1508
1513
  "--conditions=workerd,worker,import",
1509
1514
  // The ssr-handler imports a virtual module that only exists at dev time
1510
1515
  "--external:virtual:react-router/server-build",
1516
+ // Keep Yjs out of the monolithic bundle so it can be emitted as a
1517
+ // standalone _libs/yjs.mjs below. On unified workspace deploys the
1518
+ // workspace assembly step points every app's lib at ONE shared copy so
1519
+ // wrangler's final re-bundle instantiates Yjs exactly once — inlining it
1520
+ // here would put N copies in a single isolate (Yjs logs "Yjs was already
1521
+ // imported" per extra copy and cross-copy instanceof checks break).
1522
+ "--external:yjs",
1511
1523
  `--alias:#nitro/virtual/server-assets=${nitroServerAssetsStub}`,
1512
1524
  // Banner: override the __require shim that esbuild generates for CJS modules.
1513
1525
  // This provides a real require() backed by ESM imports of node builtins.
@@ -1526,6 +1538,14 @@ async function buildCloudflarePages() {
1526
1538
  stdio: "inherit",
1527
1539
  cwd,
1528
1540
  });
1541
+ // Bundle the one real Yjs copy into _libs/yjs.mjs and rewrite the bare
1542
+ // imports the --external:yjs flag left behind (see the flag comment above).
1543
+ bundleSharedYjsLibForWorkerOutput({
1544
+ workerOutDir,
1545
+ esbuildBin,
1546
+ projectCwd: cwd,
1547
+ tmpDir,
1548
+ });
1529
1549
  // Clean up tmp
1530
1550
  fs.rmSync(tmpDir, { recursive: true });
1531
1551
  // Rewrite the external virtual import to a local stub.
@@ -2245,6 +2265,95 @@ export function rewriteBareYjsImportsForServerlessOutput(serverDir) {
2245
2265
  }
2246
2266
  return bareImports;
2247
2267
  }
2268
+ /**
2269
+ * Resolve Yjs's ESM entry for bundling into a worker `_libs/yjs.mjs`.
2270
+ * Templates don't depend on `yjs` directly (it's a core dependency), so when
2271
+ * the project itself can't resolve it, resolve through the installed
2272
+ * `@agent-native/core` package location instead.
2273
+ */
2274
+ export function resolveYjsEsmEntry(projectCwd) {
2275
+ const resolveFrom = (base) => {
2276
+ try {
2277
+ return createRequire(path.join(base, "package.json")).resolve("yjs");
2278
+ }
2279
+ catch {
2280
+ return null;
2281
+ }
2282
+ };
2283
+ let resolved = resolveFrom(projectCwd);
2284
+ if (!resolved) {
2285
+ try {
2286
+ const corePkg = createRequire(path.join(projectCwd, "package.json")).resolve("@agent-native/core/package.json");
2287
+ resolved = resolveFrom(path.dirname(fs.realpathSync(corePkg)));
2288
+ }
2289
+ catch {
2290
+ resolved = null;
2291
+ }
2292
+ }
2293
+ if (!resolved)
2294
+ return null;
2295
+ // require.resolve returns the CJS entry; prefer the sibling ESM build so
2296
+ // `export * from` re-exports Yjs's real named exports statically.
2297
+ const esmSibling = resolved.replace(/\.c?js$/, ".mjs");
2298
+ return esmSibling !== resolved && fs.existsSync(esmSibling)
2299
+ ? esmSibling
2300
+ : resolved;
2301
+ }
2302
+ /**
2303
+ * Emit Yjs as a standalone `_libs/yjs.mjs` in the Cloudflare worker output
2304
+ * and rewrite every bare `yjs` import (left external by the main esbuild
2305
+ * bundle) to it. Keeping Yjs in its own module file is what lets the unified
2306
+ * workspace assembly (`workspace-deploy.ts`) collapse all apps onto ONE
2307
+ * shared copy — wrangler's final re-bundle dedupes modules by file path, so
2308
+ * N inlined copies would otherwise land in a single isolate and trip Yjs's
2309
+ * "Yjs was already imported. This breaks constructor checks" guard.
2310
+ */
2311
+ export function bundleSharedYjsLibForWorkerOutput(opts) {
2312
+ const { workerOutDir, esbuildBin, projectCwd, tmpDir } = opts;
2313
+ // Fail loud on CJS require sites — the import rewrite below cannot fix a
2314
+ // `require("yjs")`, and leaving one would crash at runtime instead.
2315
+ const requireSites = [];
2316
+ let hasBareImport = false;
2317
+ walkServerJavaScriptFiles(workerOutDir, (filePath) => {
2318
+ const source = fs.readFileSync(filePath, "utf-8");
2319
+ if (/\brequire\(\s*["']yjs["']\s*\)/.test(source)) {
2320
+ requireSites.push(filePath);
2321
+ }
2322
+ if (hasBareYjsRuntimeImport(source))
2323
+ hasBareImport = true;
2324
+ });
2325
+ if (requireSites.length > 0) {
2326
+ throw new Error(`[deploy] Cloudflare worker output left CJS require("yjs") sites the Yjs lib rewrite cannot fix: ${requireSites.join(", ")}`);
2327
+ }
2328
+ if (!hasBareImport)
2329
+ return [];
2330
+ const yjsEntry = resolveYjsEsmEntry(projectCwd);
2331
+ if (!yjsEntry) {
2332
+ throw new Error("[deploy] Cloudflare worker output imports yjs but the package could not be resolved for _libs bundling");
2333
+ }
2334
+ const libsDir = path.join(workerOutDir, "_libs");
2335
+ fs.mkdirSync(libsDir, { recursive: true });
2336
+ const entryFile = path.join(tmpDir, "_yjs-lib-entry.js");
2337
+ // Forward slashes: backslashes in an import specifier are escape sequences.
2338
+ fs.writeFileSync(entryFile, `export * from "${yjsEntry.split(path.sep).join("/")}";\n`);
2339
+ const command = esbuildSpawnCommand(esbuildBin, [
2340
+ entryFile,
2341
+ "--bundle",
2342
+ `--outfile=${path.join(libsDir, "yjs.mjs")}`,
2343
+ "--format=esm",
2344
+ "--platform=browser",
2345
+ "--target=es2022",
2346
+ "--minify",
2347
+ "--conditions=workerd,worker,import",
2348
+ ]);
2349
+ execFileSync(command.file, command.args, {
2350
+ stdio: "inherit",
2351
+ cwd: projectCwd,
2352
+ });
2353
+ const rewritten = rewriteBareYjsImportsForServerlessOutput(workerOutDir);
2354
+ console.log(`[deploy] Bundled yjs into _libs/yjs.mjs (${rewritten.length} import site file(s) rewritten)`);
2355
+ return rewritten;
2356
+ }
2248
2357
  export function assertSingleTemplateNetlifyBuildOutput(projectCwd) {
2249
2358
  const failures = [];
2250
2359
  const publishDir = path.join(projectCwd, "dist");