@decocms/tanstack 7.64.2 → 7.64.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.64.2",
3
+ "version": "7.64.3",
4
4
  "type": "module",
5
5
  "description": "Deco framework binding for TanStack Start + Cloudflare Workers",
6
6
  "repository": {
@@ -27,9 +27,9 @@
27
27
  "lint:unused": "knip"
28
28
  },
29
29
  "dependencies": {
30
- "@decocms/blocks": "7.64.2",
31
- "@decocms/blocks-admin": "7.64.2",
32
- "@decocms/blocks-cli": "7.64.2",
30
+ "@decocms/blocks": "7.64.3",
31
+ "@decocms/blocks-admin": "7.64.3",
32
+ "@decocms/blocks-cli": "7.64.3",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -215,28 +215,56 @@ describe("maybePollRevision", () => {
215
215
  });
216
216
 
217
217
  // ---------------------------------------------------------------------------
218
- // No-bundled-fallback semantics (`decoVitePlugin({ fastDeploy: true })`)
218
+ // Bundles that ship no decofile (`decoVitePlugin({ fastDeploy: true })`)
219
219
  //
220
- // When the server bundle is stubbed, KV is the ONLY source of content. The
221
- // "warn and serve bundled" recovery would serve an EMPTY site — 200s with no
222
- // pages, which get edge-cached and outlive the KV failure. These assert it
223
- // fails loudly instead, and that the default (bundled present) is unchanged.
220
+ // With the decofile stubbed out of the server bundle, KV is the ONLY source of
221
+ // content. The "warn and serve bundled" recovery would serve an EMPTY site —
222
+ // 200s with no pages, which get edge-cached and outlive the KV failure that
223
+ // caused them. These assert it fails loudly instead.
224
+ //
225
+ // The signal is the build-time `__DECO_BLOCKS_STUBBED__` define, NOT an empty
226
+ // in-memory map: draft overrides can make a stubbed bundle look populated, and
227
+ // a legitimately-empty decofile would look stubbed. Both are covered below.
224
228
  // ---------------------------------------------------------------------------
225
- describe("ensureBlocksHydrated without a bundled fallback", () => {
226
- /** Simulates the stubbed server bundle: `export const blocks = {}`. */
227
- const stubBundle = () => setBlocks({});
229
+ declare global {
230
+ // eslint-disable-next-line no-var
231
+ var __DECO_BLOCKS_STUBBED__: boolean | undefined;
232
+ }
233
+
234
+ /** Simulates a build made with `fastDeploy: true`. */
235
+ function withStubbedBundle() {
236
+ globalThis.__DECO_BLOCKS_STUBBED__ = true;
237
+ }
238
+
239
+ describe("ensureBlocksHydrated when the bundle ships no decofile", () => {
240
+ beforeEach(() => {
241
+ globalThis.__DECO_BLOCKS_STUBBED__ = undefined;
242
+ });
228
243
 
229
244
  it("throws when the snapshot is missing instead of serving an empty site", async () => {
230
- stubBundle();
245
+ withStubbedBundle();
246
+ setBlocks({});
231
247
  const { kv } = makeKV(); // no decofile:<id> seeded
232
248
  const env = { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID };
233
249
 
234
- await expect(ensureBlocksHydrated(env)).rejects.toThrow(/not found and no bundled snapshot/);
235
- expect(loadBlocks()).toEqual({});
250
+ await expect(ensureBlocksHydrated(env)).rejects.toThrow(/not found and this bundle ships no/);
251
+ });
252
+
253
+ it("throws when the snapshot exists but is empty", async () => {
254
+ // A seed that wrote `{}` would otherwise take the success branch, latch,
255
+ // and serve the empty edge-cached site this guard exists to prevent.
256
+ withStubbedBundle();
257
+ setBlocks({});
258
+ const { kv } = makeKV({ [SNAP]: "{}", [REV]: computeRevision({}) });
259
+
260
+ await expect(
261
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
262
+ ).rejects.toThrow(/is empty and this bundle ships no/);
236
263
  });
237
264
 
238
265
  it("throws when KV itself fails", async () => {
239
- stubBundle();
266
+ withStubbedBundle();
267
+ setBlocks({});
240
268
  const kv = {
241
269
  get: () => Promise.reject(new Error("KV unreachable")),
242
270
  put: () => Promise.resolve(),
@@ -249,16 +277,31 @@ describe("ensureBlocksHydrated without a bundled fallback", () => {
249
277
  });
250
278
 
251
279
  it("throws when no deployment id resolves", async () => {
252
- stubBundle();
280
+ withStubbedBundle();
281
+ setBlocks({});
282
+ const { kv } = makeKV();
283
+
284
+ await expect(ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1" })).rejects.toThrow(
285
+ /no deployment id/,
286
+ );
287
+ });
288
+
289
+ it("is not rescued by a populated in-memory map (draft-preview overrides)", async () => {
290
+ // `bindRequestDraft` composes overrides into loadBlocks() BEFORE hydration.
291
+ // Inferring "has a fallback" from the map would latch here and then serve
292
+ // the empty base decofile for the isolate's life.
293
+ withStubbedBundle();
294
+ setBlocks({ "pages-Draft": { name: "override" } });
253
295
  const { kv } = makeKV();
254
296
 
255
297
  await expect(
256
- ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1" }),
257
- ).rejects.toThrow(/no deployment id/);
298
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
299
+ ).rejects.toThrow(/not found and this bundle ships no/);
258
300
  });
259
301
 
260
302
  it("does not latch hydration on the fatal path, so the next request retries", async () => {
261
- stubBundle();
303
+ withStubbedBundle();
304
+ setBlocks({});
262
305
  const blocks = { Site: { name: "from-kv" } };
263
306
  const store = new Map<string, string>();
264
307
  const kv: KVNamespace = {
@@ -284,9 +327,14 @@ describe("ensureBlocksHydrated without a bundled fallback", () => {
284
327
  await expect(ensureBlocksHydrated(env)).resolves.toBeUndefined();
285
328
  expect(loadBlocks()).toEqual(blocks);
286
329
  });
330
+ });
331
+
332
+ describe("ensureBlocksHydrated when the bundle DOES ship a decofile (default)", () => {
333
+ beforeEach(() => {
334
+ globalThis.__DECO_BLOCKS_STUBBED__ = undefined;
335
+ });
287
336
 
288
- it("still warns and serves bundled when a bundled snapshot IS present", async () => {
289
- // Default configuration — must behave exactly as before this change.
337
+ it("warns and serves bundled when KV fails", async () => {
290
338
  const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
291
339
  const kv = {
292
340
  get: () => Promise.reject(new Error("KV unreachable")),
@@ -300,4 +348,15 @@ describe("ensureBlocksHydrated without a bundled fallback", () => {
300
348
  expect(loadBlocks()).toEqual(BUNDLED);
301
349
  expect(warn).toHaveBeenCalled();
302
350
  });
351
+
352
+ it("does not 5xx a site whose bundled decofile is legitimately empty", async () => {
353
+ // New site / missing blocks.gen.json. Before the build-time flag this
354
+ // looked identical to a stubbed bundle and started failing requests.
355
+ setBlocks({});
356
+ const { kv } = makeKV(); // no snapshot seeded either
357
+
358
+ await expect(
359
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
360
+ ).resolves.toBeUndefined();
361
+ });
303
362
  });
@@ -24,13 +24,7 @@
24
24
  * `DecofileProvider` pattern from the deco-cx/deco Fresh runtime.
25
25
  */
26
26
 
27
- import {
28
- DEPLOYMENT_ID_ENV,
29
- getDeploymentId,
30
- getRevision,
31
- loadBlocks,
32
- setBlocks,
33
- } from "@decocms/blocks/cms";
27
+ import { DEPLOYMENT_ID_ENV, getDeploymentId, getRevision, setBlocks } from "@decocms/blocks/cms";
34
28
  import { KVBlockSource } from "../cms/kvBlockSource";
35
29
  import type { KVNamespace } from "@decocms/blocks/cms";
36
30
  import { setSpanAttribute } from "@decocms/blocks/sdk/observability";
@@ -101,21 +95,32 @@ export function getFastDeployKV(env: Env): KVNamespace | null {
101
95
  return getKV(env);
102
96
  }
103
97
 
98
+ // Build-time constant injected by `decoVitePlugin({ fastDeploy: true })`: true
99
+ // when `blocks.gen` was stubbed out of THIS server bundle. Declared with a
100
+ // `typeof` guard so it's inert wherever the define isn't applied (this
101
+ // package's own tsc output, the Next.js build, tests).
102
+ declare const __DECO_BLOCKS_STUBBED__: boolean | undefined;
103
+
104
104
  /**
105
- * Is there a bundled snapshot to fall back on?
105
+ * Does this bundle ship no decofile of its own?
106
106
  *
107
- * `decoVitePlugin({ fastDeploy: true })` stubs `blocks.gen` out of the server
108
- * bundle to avoid holding the decofile twice (see the option's docs). That
109
- * makes KV the ONLY source of content, so the "warn and serve bundled"
110
- * recovery below would actually serve an EMPTY site — 200s with no pages,
111
- * which then get edge-cached and outlive the KV failure that caused them.
107
+ * When true, KV is the ONLY source of content, so the "warn and serve bundled"
108
+ * recovery below would serve an EMPTY site — 200s with no pages, which then get
109
+ * edge-cached and outlive the KV failure that caused them. Those cases fail
110
+ * loudly instead.
112
111
  *
113
- * Checking the in-memory map rather than a build-time flag keeps this honest
114
- * in both configurations, and means sites that still bundle their decofile
115
- * (the default) behave exactly as before.
112
+ * This is deliberately a BUILD-time answer rather than "is the in-memory map
113
+ * empty". The runtime check is not equivalent in three ways:
114
+ * - `loadBlocks()` composes request-scoped draft/preview overrides, and
115
+ * `bindRequestDraft` runs before hydration — a draft-preview first request
116
+ * would make a stubbed bundle look populated, latch, and then serve the
117
+ * empty base decofile for the isolate's life.
118
+ * - A legitimately-empty decofile (new site, missing `blocks.gen.json`) would
119
+ * look stubbed, turning a previously-warning default site into 5xx.
120
+ * - An empty snapshot in KV can't be distinguished from a healthy one.
116
121
  */
117
- function hasBundledFallback(): boolean {
118
- return Object.keys(loadBlocks()).length > 0;
122
+ function bundleHasNoDecofile(): boolean {
123
+ return typeof __DECO_BLOCKS_STUBBED__ !== "undefined" && __DECO_BLOCKS_STUBBED__ === true;
119
124
  }
120
125
 
121
126
  /**
@@ -144,10 +149,10 @@ export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Pro
144
149
  // content). Never read another deployment's key.
145
150
  const deploymentId = getDeploymentId(env);
146
151
  if (!deploymentId) {
147
- if (!hasBundledFallback()) {
152
+ if (bundleHasNoDecofile()) {
148
153
  return Promise.reject(
149
154
  new Error(
150
- `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and no bundled snapshot to fall back on`,
155
+ `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and this bundle ships no decofile`,
151
156
  ),
152
157
  );
153
158
  }
@@ -163,19 +168,24 @@ export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Pro
163
168
  let fatal: Error | null = null;
164
169
  try {
165
170
  const snapshot = await new KVBlockSource(kv, deploymentId).loadSnapshot();
166
- if (snapshot) {
167
- setBlocks(snapshot.blocks);
171
+ // An empty snapshot is treated as a failure, not a success: with no
172
+ // bundled decofile it would otherwise latch and serve exactly the empty,
173
+ // edge-cached site this guard exists to prevent. A site legitimately has
174
+ // blocks; `{}` means the seed wrote nothing.
175
+ const empty = !snapshot || Object.keys(snapshot.blocks).length === 0;
176
+ if (!empty) {
177
+ setBlocks(snapshot!.blocks);
168
178
  setSpanAttribute("deco.block.source", "kv");
169
- } else if (hasBundledFallback()) {
179
+ } else if (!bundleHasNoDecofile()) {
170
180
  setSpanAttribute("deco.block.source", "bundled");
171
181
  } else {
172
182
  fatal = new Error(
173
- `[CMS/KV] decofile:${deploymentId} not found and no bundled snapshot to fall back on — ` +
174
- `seed it before activating this version`,
183
+ `[CMS/KV] decofile:${deploymentId} ${snapshot ? "is empty" : "not found"} and this ` +
184
+ `bundle ships no decofile — seed it before activating this version`,
175
185
  );
176
186
  }
177
187
  } catch (e) {
178
- if (hasBundledFallback()) {
188
+ if (!bundleHasNoDecofile()) {
179
189
  // Non-fatal: serve the bundled snapshot. The poll loop recovers later.
180
190
  console.warn("[CMS/KV] cold-start hydration failed, using bundled snapshot:", e);
181
191
  setSpanAttribute("deco.block.source", "bundled");
@@ -1,5 +1,6 @@
1
- import { setBlocks } from "@decocms/blocks/cms";
2
- import { afterEach, describe, expect, it } from "vitest";
1
+ import { computeRevision, revisionKey, setBlocks, snapshotKey } from "@decocms/blocks/cms";
2
+ import { __resetAutoconfigStateForTests, autoconfigApps } from "@decocms/blocks-admin/apps/autoconfig";
3
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
3
4
  import { __resetKvHydrationStateForTests } from "./kvHydration";
4
5
  import { segmentToken } from "./cdnSegment";
5
6
  import {
@@ -939,3 +940,93 @@ describe('cdnCacheControl: "match-profile" guard', () => {
939
940
  expect(res.headers.get("CDN-Cache-Control")).toMatch(/^public, max-age=\d+$/);
940
941
  });
941
942
  });
943
+
944
+ /**
945
+ * Fast-deploy hydration must run BEFORE `reconfigureAppsOnce()`.
946
+ *
947
+ * `reconfigureAppsOnce()` configures apps from the blocks it sees and then
948
+ * latches its promise forever. If it ran first, a `fastDeploy` build — whose
949
+ * bundled decofile is `{}` — would configure ZERO apps, and the only recovery
950
+ * is `setBlocks()`'s onChange listener, whose promise `setBlocks` drops
951
+ * unawaited. The request would proceed with no app loaders registered.
952
+ */
953
+ describe("fast-deploy hydration ordering", () => {
954
+ // Reset BEFORE as well: both flags are module-level and latching, so an
955
+ // earlier test in this file that fired a request leaves `kvHydrated` true
956
+ // and hydration would be skipped entirely here.
957
+ beforeEach(() => {
958
+ __resetKvHydrationStateForTests();
959
+ __resetAutoconfigStateForTests();
960
+ });
961
+
962
+ afterEach(() => {
963
+ __resetKvHydrationStateForTests();
964
+ __resetAutoconfigStateForTests();
965
+ setBlocks({});
966
+ });
967
+
968
+ it("configures apps from the KV snapshot, not the stubbed bundle", async () => {
969
+ const KV_BLOCKS = { "deco-test": { "@type": "test-app", token: "from-kv" } };
970
+ const ID = "sha-ordering";
971
+
972
+ /** Blocks each configure() call observed, in order. */
973
+ const seen: unknown[] = [];
974
+ const registry = [
975
+ {
976
+ blockKey: "deco-test",
977
+ module: () =>
978
+ Promise.resolve({
979
+ configure: (block: unknown) => {
980
+ seen.push(block);
981
+ return Promise.resolve({
982
+ name: "test-app",
983
+ manifest: { name: "test-app", loaders: {}, actions: {} },
984
+ state: {},
985
+ });
986
+ },
987
+ }),
988
+ },
989
+ ];
990
+
991
+ // autoconfigApps and its onChange listener are server-only guarded on
992
+ // `typeof document`. This suite runs under jsdom, so drop `document` for
993
+ // the duration to exercise the worker path.
994
+ const realDocument = globalThis.document;
995
+ delete (globalThis as { document?: unknown }).document;
996
+ try {
997
+ // Simulates the stubbed server bundle: autoconfigApps runs at module init
998
+ // with an empty decofile, exactly as it would in a fastDeploy build.
999
+ setBlocks({});
1000
+ await autoconfigApps({}, registry as never);
1001
+ expect(seen).toEqual([]); // nothing to configure yet — this is the trap
1002
+
1003
+ const store = new Map<string, string>([
1004
+ [snapshotKey(ID), JSON.stringify(KV_BLOCKS)],
1005
+ [revisionKey(ID), computeRevision(KV_BLOCKS)],
1006
+ ]);
1007
+ const env = {
1008
+ DECO_KV: {
1009
+ get: (k: string) => Promise.resolve(store.get(k) ?? null),
1010
+ put: () => Promise.resolve(),
1011
+ delete: () => Promise.resolve(),
1012
+ },
1013
+ DECO_FAST_DEPLOY: "1",
1014
+ DECO_DEPLOYMENT_ID: ID,
1015
+ };
1016
+
1017
+ const worker = createDecoWorkerEntry(MOCK_SERVER_ENTRY, { observability: false });
1018
+ await worker.fetch(new Request("https://example.com/"), env, MOCK_CTX);
1019
+
1020
+ // The app must have been configured with the block that came from KV.
1021
+ // Not asserting a call COUNT: both the onChange listener and the
1022
+ // one-shot reinit legitimately configure, and how many passes happen is
1023
+ // not the contract. The contract is that no pass saw the empty bundle.
1024
+ // Deep equality, not identity: the snapshot arrives via JSON.parse, so
1025
+ // the block is a structurally-equal copy.
1026
+ expect(seen.length).toBeGreaterThan(0);
1027
+ for (const block of seen) expect(block).toEqual(KV_BLOCKS["deco-test"]);
1028
+ } finally {
1029
+ globalThis.document = realDocument;
1030
+ }
1031
+ });
1032
+ });
@@ -1770,6 +1770,24 @@ export function createDecoWorkerEntry(
1770
1770
  // via getRuntimeEnv() in sdk/otelAdapters.ts.
1771
1771
  setRuntimeEnv(env);
1772
1772
 
1773
+ // Fast-deploy: hydrate the in-memory decofile from KV on the first
1774
+ // request per isolate (awaited, ~10-30ms once), then opportunistically
1775
+ // poll for content changes (non-blocking, via ctx.waitUntil). No-op
1776
+ // unless the DECO_KV binding + DECO_FAST_DEPLOY are present —
1777
+ // non-migrated sites are unaffected.
1778
+ //
1779
+ // MUST come before reconfigureAppsOnce() and bindRequestDraft() below.
1780
+ // Both read the decofile, and both are one-shot/latching:
1781
+ // - reconfigureAppsOnce() configures apps from the blocks it sees and
1782
+ // latches `reinitPromise` forever. Running it first means a
1783
+ // fastDeploy build (whose bundled decofile is `{}`) configures ZERO
1784
+ // apps, and the only recovery is setBlocks()'s onChange listener,
1785
+ // whose promise setBlocks drops unawaited — so the request would
1786
+ // proceed with no app loaders registered.
1787
+ // - bindRequestDraft() composes draft overrides into loadBlocks().
1788
+ await ensureBlocksHydrated(env, ctx);
1789
+ maybePollRevision(env, ctx);
1790
+
1773
1791
  // First-request re-configuration of apps. autoconfigApps() runs at
1774
1792
  // module init (setup.ts), before `env` — and thus DECO_CRYPTO_KEY —
1775
1793
  // is available, so encrypted app credentials (VTEX appKey/appToken,
@@ -2000,13 +2018,9 @@ export function createDecoWorkerEntry(
2000
2018
  ): Promise<Response> {
2001
2019
  const url = new URL(request.url);
2002
2020
 
2003
- // Fast-deploy: hydrate the in-memory decofile from KV on the first request
2004
- // per isolate (awaited, ~10-30ms once), then opportunistically poll for
2005
- // content changes (non-blocking, via ctx.waitUntil). No-op unless the
2006
- // DECO_KV binding is present — non-migrated sites are unaffected. Runs
2007
- // before admin routes so /.decofile reads reflect KV too.
2008
- await ensureBlocksHydrated(env, ctx);
2009
- maybePollRevision(env, ctx);
2021
+ // NOTE: fast-deploy hydration does NOT run here. It must happen before
2022
+ // `reconfigureAppsOnce()` and `bindRequestDraft()`, both of which run in
2023
+ // the outer fetch above — see the `ensureBlocksHydrated` call there.
2010
2024
 
2011
2025
  {
2012
2026
  const segment = buildSegment?.(request);
@@ -194,6 +194,13 @@ export function generateSchemaArgs(siteName) {
194
194
  * @returns {import("vite").PluginOption}
195
195
  */
196
196
  export function decoVitePlugin({ fastDeploy = false } = {}) {
197
+ // Set from the `config` hook (which Vite always runs before `load`). The
198
+ // fastDeploy stub must apply to production builds ONLY: `vite dev` has no KV
199
+ // to hydrate from, and the dev bootstrap below deliberately relies on reading
200
+ // the `.json` sibling that the stub bypasses — stubbing there blanks the
201
+ // local site.
202
+ let isBuild = false;
203
+
197
204
  /** @type {import("vite").Plugin} */
198
205
  const plugin = {
199
206
  name: "deco-server-only-stubs",
@@ -231,7 +238,8 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
231
238
  // second, permanently-reachable copy in isolate memory (the site's
232
239
  // `import { blocks }` binding keeps the bundled graph alive for the
233
240
  // isolate's whole life, even after `setBlocks()` swaps in the KV one).
234
- if (fastDeploy) {
241
+ // Build only — see `isBuild` above.
242
+ if (fastDeploy && isBuild) {
235
243
  return "export const blocks = {};";
236
244
  }
237
245
 
@@ -715,6 +723,9 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
715
723
  },
716
724
 
717
725
  config(_cfg, { command }) {
726
+ // Gate the fastDeploy SSR stub in `load()` to production builds.
727
+ isBuild = command === "build";
728
+
718
729
  /** @type {import("vite").UserConfig} */
719
730
  const cfg = {};
720
731
 
@@ -767,6 +778,14 @@ export function decoVitePlugin({ fastDeploy = false } = {}) {
767
778
  cfg.define = {
768
779
  ...cfg.define,
769
780
  __DECO_BUILD_HASH__: JSON.stringify(buildHash),
781
+ // Tells the runtime whether this bundle actually ships a decofile.
782
+ // `ensureBlocksHydrated` needs a build-time answer: with no bundled
783
+ // snapshot, its "warn and serve bundled" recovery would serve an EMPTY
784
+ // site with 200s. Inferring it from an empty in-memory map at runtime
785
+ // is not equivalent — draft-preview overrides can make a stubbed bundle
786
+ // look populated, and a legitimately-empty decofile (new site) would
787
+ // look stubbed.
788
+ __DECO_BLOCKS_STUBBED__: JSON.stringify(fastDeploy && command === "build"),
770
789
  };
771
790
 
772
791
  // Only split chunks for production builds — dev uses unbundled ESM.
@@ -52,45 +52,61 @@ describe("decoVitePlugin — loaders.gen client stub", () => {
52
52
  });
53
53
 
54
54
  /**
55
- * `fastDeploy: true` must stub blocks.gen out of the SERVER bundle too.
55
+ * `fastDeploy: true` must stub blocks.gen out of the SERVER bundle — but only
56
+ * for production builds.
56
57
  *
57
- * Otherwise a fast-deploy site holds the decofile twice: the bundled
58
+ * Without the stub, a fast-deploy site holds the decofile twice: the bundled
58
59
  * JSON.parse(...) graph stays reachable via the site's `import { blocks }`
59
- * binding for the isolate's whole life, and ensureBlocksHydrated adds a
60
- * second graph. Tens of MB of avoidable memory for a 10MB decofile.
60
+ * binding for the isolate's whole life, and ensureBlocksHydrated adds a second
61
+ * graph. Measured at 13.6 MB + 13.4 MB for a 9.2 MB decofile.
62
+ *
63
+ * In `vite dev` there is no KV to hydrate from, and the dev bootstrap relies on
64
+ * reading the `.json` sibling the stub bypasses — so stubbing there would blank
65
+ * the local site.
61
66
  */
62
67
  describe("decoVitePlugin — fastDeploy server stub", () => {
63
68
  const id = "/repo/.deco/blocks.gen.ts";
64
69
  const STUB = "export const blocks = {};";
65
70
 
66
- it("stubs blocks.gen on SSR when fastDeploy is on", () => {
67
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
68
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
69
- };
70
- expect(plugin.load(id, { ssr: true })).toBe(STUB);
71
+ /** @param {{fastDeploy?: boolean}} opts @param {"build"|"serve"} command */
72
+ const make = (opts, command) => {
73
+ const p = /** @type {any} */ (decoVitePlugin(opts));
74
+ p.config({}, { command }); // Vite always runs config() before load()
75
+ return p;
76
+ };
77
+
78
+ it("stubs blocks.gen on SSR for a production build", () => {
79
+ expect(make({ fastDeploy: true }, "build").load(id, { ssr: true })).toBe(STUB);
80
+ });
81
+
82
+ it("does NOT stub on SSR in dev, where there is no KV to hydrate from", () => {
83
+ expect(make({ fastDeploy: true }, "serve").load(id, { ssr: true })).not.toBe(STUB);
71
84
  });
72
85
 
73
- it("keeps stubbing the client bundle when fastDeploy is on", () => {
74
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
75
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
76
- };
77
- expect(plugin.load(id, { ssr: false })).toBe(STUB);
86
+ it("keeps stubbing the client bundle regardless", () => {
87
+ expect(make({ fastDeploy: true }, "build").load(id, { ssr: false })).toBe(STUB);
88
+ expect(make({ fastDeploy: true }, "serve").load(id, { ssr: false })).toBe(STUB);
78
89
  });
79
90
 
80
91
  it("does NOT stub blocks.gen on SSR by default (bundled fallback preserved)", () => {
81
- const plugin = decoVitePlugin() as {
82
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
83
- };
84
92
  // No .json sibling on disk for this synthetic path, so the hook falls
85
- // through to Vite (undefined) rather than returning a stub. The point is
86
- // that it never returns the empty stub for SSR.
87
- expect(plugin.load(id, { ssr: true })).not.toBe(STUB);
93
+ // through to Vite (undefined). The point is it never returns the stub.
94
+ expect(make({}, "build").load(id, { ssr: true })).not.toBe(STUB);
95
+ });
96
+
97
+ it("leaves unrelated modules alone", () => {
98
+ expect(make({ fastDeploy: true }, "build").load("/repo/src/x.tsx", { ssr: true })).toBeUndefined();
88
99
  });
89
100
 
90
- it("leaves unrelated modules alone with fastDeploy on", () => {
91
- const plugin = decoVitePlugin({ fastDeploy: true }) as {
92
- load: (id: string, options?: { ssr?: boolean }) => string | undefined;
93
- };
94
- expect(plugin.load("/repo/src/sections/Hero.tsx", { ssr: true })).toBeUndefined();
101
+ it("defines __DECO_BLOCKS_STUBBED__ so the runtime knows whether it has a fallback", () => {
102
+ const build = /** @type {any} */ (decoVitePlugin({ fastDeploy: true })).config({}, { command: "build" });
103
+ expect(build.define.__DECO_BLOCKS_STUBBED__).toBe("true");
104
+
105
+ // Dev and the default must both report "no, you still have a decofile",
106
+ // otherwise ensureBlocksHydrated would start failing requests.
107
+ const dev = /** @type {any} */ (decoVitePlugin({ fastDeploy: true })).config({}, { command: "serve" });
108
+ expect(dev.define.__DECO_BLOCKS_STUBBED__).toBe("false");
109
+ const def = /** @type {any} */ (decoVitePlugin()).config({}, { command: "build" });
110
+ expect(def.define.__DECO_BLOCKS_STUBBED__).toBe("false");
95
111
  });
96
112
  });