@decocms/tanstack 7.64.1 → 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.1",
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.1",
31
- "@decocms/blocks-admin": "7.64.1",
32
- "@decocms/blocks-cli": "7.64.1",
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"
@@ -213,3 +213,150 @@ describe("maybePollRevision", () => {
213
213
  expect(getCalls()).toBe(callsAfterHydrate + 1);
214
214
  });
215
215
  });
216
+
217
+ // ---------------------------------------------------------------------------
218
+ // Bundles that ship no decofile (`decoVitePlugin({ fastDeploy: true })`)
219
+ //
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.
228
+ // ---------------------------------------------------------------------------
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
+ });
243
+
244
+ it("throws when the snapshot is missing instead of serving an empty site", async () => {
245
+ withStubbedBundle();
246
+ setBlocks({});
247
+ const { kv } = makeKV(); // no decofile:<id> seeded
248
+ const env = { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID };
249
+
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/);
263
+ });
264
+
265
+ it("throws when KV itself fails", async () => {
266
+ withStubbedBundle();
267
+ setBlocks({});
268
+ const kv = {
269
+ get: () => Promise.reject(new Error("KV unreachable")),
270
+ put: () => Promise.resolve(),
271
+ delete: () => Promise.resolve(),
272
+ } as unknown as KVNamespace;
273
+
274
+ await expect(
275
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
276
+ ).rejects.toThrow(/KV unreachable/);
277
+ });
278
+
279
+ it("throws when no deployment id resolves", async () => {
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" } });
295
+ const { kv } = makeKV();
296
+
297
+ await expect(
298
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
299
+ ).rejects.toThrow(/not found and this bundle ships no/);
300
+ });
301
+
302
+ it("does not latch hydration on the fatal path, so the next request retries", async () => {
303
+ withStubbedBundle();
304
+ setBlocks({});
305
+ const blocks = { Site: { name: "from-kv" } };
306
+ const store = new Map<string, string>();
307
+ const kv: KVNamespace = {
308
+ get: (k) => Promise.resolve(store.get(k) ?? null),
309
+ put: (k, v) => {
310
+ store.set(k, v);
311
+ return Promise.resolve();
312
+ },
313
+ delete: (k) => {
314
+ store.delete(k);
315
+ return Promise.resolve();
316
+ },
317
+ };
318
+ const env = { DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID };
319
+
320
+ // First request: snapshot absent → fatal.
321
+ await expect(ensureBlocksHydrated(env)).rejects.toThrow();
322
+
323
+ // Operator seeds it; the isolate must pick it up rather than stay empty.
324
+ store.set(SNAP, JSON.stringify(blocks));
325
+ store.set(REV, computeRevision(blocks));
326
+
327
+ await expect(ensureBlocksHydrated(env)).resolves.toBeUndefined();
328
+ expect(loadBlocks()).toEqual(blocks);
329
+ });
330
+ });
331
+
332
+ describe("ensureBlocksHydrated when the bundle DOES ship a decofile (default)", () => {
333
+ beforeEach(() => {
334
+ globalThis.__DECO_BLOCKS_STUBBED__ = undefined;
335
+ });
336
+
337
+ it("warns and serves bundled when KV fails", async () => {
338
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
339
+ const kv = {
340
+ get: () => Promise.reject(new Error("KV unreachable")),
341
+ put: () => Promise.resolve(),
342
+ delete: () => Promise.resolve(),
343
+ } as unknown as KVNamespace;
344
+
345
+ await expect(
346
+ ensureBlocksHydrated({ DECO_KV: kv, DECO_FAST_DEPLOY: "1", DECO_DEPLOYMENT_ID: ID }),
347
+ ).resolves.toBeUndefined();
348
+ expect(loadBlocks()).toEqual(BUNDLED);
349
+ expect(warn).toHaveBeenCalled();
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
+ });
362
+ });
@@ -24,7 +24,7 @@
24
24
  * `DecofileProvider` pattern from the deco-cx/deco Fresh runtime.
25
25
  */
26
26
 
27
- import { getDeploymentId, getRevision, setBlocks } from "@decocms/blocks/cms";
27
+ import { DEPLOYMENT_ID_ENV, getDeploymentId, getRevision, setBlocks } from "@decocms/blocks/cms";
28
28
  import { KVBlockSource } from "../cms/kvBlockSource";
29
29
  import type { KVNamespace } from "@decocms/blocks/cms";
30
30
  import { setSpanAttribute } from "@decocms/blocks/sdk/observability";
@@ -95,12 +95,47 @@ export function getFastDeployKV(env: Env): KVNamespace | null {
95
95
  return getKV(env);
96
96
  }
97
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
+ /**
105
+ * Does this bundle ship no decofile of its own?
106
+ *
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.
111
+ *
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.
121
+ */
122
+ function bundleHasNoDecofile(): boolean {
123
+ return typeof __DECO_BLOCKS_STUBBED__ !== "undefined" && __DECO_BLOCKS_STUBBED__ === true;
124
+ }
125
+
98
126
  /**
99
127
  * Cold-start hydration. Awaits the KV snapshot once per isolate and swaps it
100
128
  * into the in-memory block map. Concurrent first requests share a single
101
- * in-flight load. On any error (KV outage, bad JSON) we keep the bundled
102
- * snapshot and mark hydration done — recovery happens via `maybePollRevision`
103
- * once KV is reachable again (its revision will differ from the bundled one).
129
+ * in-flight load.
130
+ *
131
+ * On failure (KV outage, bad JSON, snapshot not seeded) the behavior depends on
132
+ * whether a bundled snapshot exists:
133
+ *
134
+ * - Bundled present (default): warn, serve bundled, mark hydration done —
135
+ * `maybePollRevision` recovers once KV is reachable again.
136
+ * - Bundled stubbed out (`fastDeploy`): throw. There is no content to serve, so
137
+ * a 5xx is the only honest answer; hydration is left unlatched so the next
138
+ * request retries instead of pinning the isolate to an empty decofile.
104
139
  */
105
140
  export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Promise<void> {
106
141
  if (!isFastDeployEnabled(env)) return Promise.resolve();
@@ -114,28 +149,54 @@ export function ensureBlocksHydrated(env: Env, _ctx?: ExecutionContextLike): Pro
114
149
  // content). Never read another deployment's key.
115
150
  const deploymentId = getDeploymentId(env);
116
151
  if (!deploymentId) {
152
+ if (bundleHasNoDecofile()) {
153
+ return Promise.reject(
154
+ new Error(
155
+ `[CMS/KV] no deployment id (set ${DEPLOYMENT_ID_ENV}) and this bundle ships no decofile`,
156
+ ),
157
+ );
158
+ }
117
159
  setSpanAttribute("deco.block.source", "bundled");
118
160
  G.__deco!.kvHydrated = true;
119
161
  return Promise.resolve();
120
162
  }
121
163
 
122
164
  const load = (async () => {
165
+ // Held rather than rethrown inline so the `finally` below can decide
166
+ // whether to latch — latching on a fatal path would serve an empty
167
+ // decofile for the isolate's entire life.
168
+ let fatal: Error | null = null;
123
169
  try {
124
170
  const snapshot = await new KVBlockSource(kv, deploymentId).loadSnapshot();
125
- if (snapshot) {
126
- 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);
127
178
  setSpanAttribute("deco.block.source", "kv");
128
- } else {
179
+ } else if (!bundleHasNoDecofile()) {
129
180
  setSpanAttribute("deco.block.source", "bundled");
181
+ } else {
182
+ fatal = new Error(
183
+ `[CMS/KV] decofile:${deploymentId} ${snapshot ? "is empty" : "not found"} and this ` +
184
+ `bundle ships no decofile — seed it before activating this version`,
185
+ );
130
186
  }
131
187
  } catch (e) {
132
- // Non-fatal: serve the bundled snapshot. The poll loop recovers later.
133
- console.warn("[CMS/KV] cold-start hydration failed, using bundled snapshot:", e);
134
- setSpanAttribute("deco.block.source", "bundled");
188
+ if (!bundleHasNoDecofile()) {
189
+ // Non-fatal: serve the bundled snapshot. The poll loop recovers later.
190
+ console.warn("[CMS/KV] cold-start hydration failed, using bundled snapshot:", e);
191
+ setSpanAttribute("deco.block.source", "bundled");
192
+ } else {
193
+ fatal = e instanceof Error ? e : new Error(String(e));
194
+ }
135
195
  } finally {
136
- G.__deco!.kvHydrated = true;
196
+ G.__deco!.kvHydrated = !fatal;
137
197
  G.__deco!.kvHydration = null;
138
198
  }
199
+ if (fatal) throw fatal;
139
200
  })();
140
201
 
141
202
  G.__deco!.kvHydration = load;
@@ -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);
@@ -173,8 +173,34 @@ export function generateSchemaArgs(siteName) {
173
173
  return ["--site", siteName];
174
174
  }
175
175
 
176
- /** @returns {import("vite").PluginOption} */
177
- export function decoVitePlugin() {
176
+ /**
177
+ * @param {object} [opts]
178
+ * @param {boolean} [opts.fastDeploy=false] Stub `blocks.gen` out of the SERVER
179
+ * bundle too, so the worker's only copy of the decofile is the one hydrated
180
+ * from KV at cold start.
181
+ *
182
+ * Without this, a fast-deploy site holds the decofile TWICE: the bundled
183
+ * `JSON.parse(...)` graph stays permanently reachable through the site's
184
+ * `import { blocks } from ".deco/blocks.gen"` module binding, and
185
+ * `ensureBlocksHydrated` adds a second graph via `setBlocks()`. For a 10MB
186
+ * decofile that is tens of MB of avoidable isolate memory.
187
+ *
188
+ * Opt-in because it removes the fallback: with no bundled snapshot, a cold
189
+ * start that cannot read KV has no content to serve. `ensureBlocksHydrated`
190
+ * detects that case and fails the request loudly (5xx) instead of serving an
191
+ * empty site — see `kvHydration.ts`. Only enable alongside
192
+ * `DECO_FAST_DEPLOY=1` + a `DECO_KV` binding + a deploy pipeline that seeds
193
+ * `decofile:<deployment-id>` BEFORE the new version activates.
194
+ * @returns {import("vite").PluginOption}
195
+ */
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
+
178
204
  /** @type {import("vite").Plugin} */
179
205
  const plugin = {
180
206
  name: "deco-server-only-stubs",
@@ -207,6 +233,16 @@ export function decoVitePlugin() {
207
233
  return "export const blocks = {};";
208
234
  }
209
235
 
236
+ // Fast-deploy: stub on the SERVER too. The worker hydrates the decofile
237
+ // from KV at cold start, so shipping it in the bundle would just pin a
238
+ // second, permanently-reachable copy in isolate memory (the site's
239
+ // `import { blocks }` binding keeps the bundled graph alive for the
240
+ // isolate's whole life, even after `setBlocks()` swaps in the KV one).
241
+ // Build only — see `isBuild` above.
242
+ if (fastDeploy && isBuild) {
243
+ return "export const blocks = {};";
244
+ }
245
+
210
246
  // SSR: read .json sibling and emit JSON.parse(...) wrapper.
211
247
  // This avoids the Vite SSR module runner hanging on large dynamic
212
248
  // imports and lets V8 use its fast JSON parser (~2-10x vs object literal).
@@ -687,6 +723,9 @@ export function decoVitePlugin() {
687
723
  },
688
724
 
689
725
  config(_cfg, { command }) {
726
+ // Gate the fastDeploy SSR stub in `load()` to production builds.
727
+ isBuild = command === "build";
728
+
690
729
  /** @type {import("vite").UserConfig} */
691
730
  const cfg = {};
692
731
 
@@ -739,6 +778,14 @@ export function decoVitePlugin() {
739
778
  cfg.define = {
740
779
  ...cfg.define,
741
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"),
742
789
  };
743
790
 
744
791
  // Only split chunks for production builds — dev uses unbundled ESM.
@@ -50,3 +50,63 @@ describe("decoVitePlugin — loaders.gen client stub", () => {
50
50
  expect(plugin.load("/repo/src/actions/foo.ts", { ssr: false })).toBeUndefined();
51
51
  });
52
52
  });
53
+
54
+ /**
55
+ * `fastDeploy: true` must stub blocks.gen out of the SERVER bundle — but only
56
+ * for production builds.
57
+ *
58
+ * Without the stub, a fast-deploy site holds the decofile twice: the bundled
59
+ * JSON.parse(...) graph stays reachable via the site's `import { blocks }`
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.
66
+ */
67
+ describe("decoVitePlugin — fastDeploy server stub", () => {
68
+ const id = "/repo/.deco/blocks.gen.ts";
69
+ const STUB = "export const blocks = {};";
70
+
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);
84
+ });
85
+
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);
89
+ });
90
+
91
+ it("does NOT stub blocks.gen on SSR by default (bundled fallback preserved)", () => {
92
+ // No .json sibling on disk for this synthetic path, so the hook falls
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();
99
+ });
100
+
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");
111
+ });
112
+ });