@decocms/tanstack 7.79.7 → 7.80.0

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.79.7",
3
+ "version": "7.80.0",
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.79.7",
31
- "@decocms/blocks-admin": "7.79.7",
32
- "@decocms/blocks-cli": "7.79.7",
30
+ "@decocms/blocks": "7.80.0",
31
+ "@decocms/blocks-admin": "7.80.0",
32
+ "@decocms/blocks-cli": "7.80.0",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -75,7 +75,7 @@ import {
75
75
  instrumentWorker,
76
76
  type OtelOptions,
77
77
  } from "@decocms/blocks/sdk/otel";
78
- import { setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
78
+ import { getRuntimeEnv, setRuntimeEnv } from "@decocms/blocks/sdk/otelAdapters";
79
79
  import { parseTraceparent } from "@decocms/blocks/sdk/otelHttpTracer";
80
80
  import {
81
81
  getRedirectSemantics,
@@ -91,7 +91,7 @@ import { RequestContext } from "@decocms/blocks/sdk/requestContext";
91
91
  import { createResponseCache } from "@decocms/blocks/sdk/responseCache";
92
92
  import { cleanPathForCacheKey, hasTrackingParams } from "@decocms/blocks/sdk/urlUtils";
93
93
  import { type Device, isMobileUA } from "@decocms/blocks/sdk/useDevice";
94
- import { getRenderShellConfig } from "@decocms/blocks-admin/admin/setup";
94
+ import { getRenderShellConfig, setMetaAssetFetcher } from "@decocms/blocks-admin/admin/setup";
95
95
  import { reconfigureAppsOnce } from "@decocms/blocks-admin/apps/autoconfig";
96
96
  import { buildHtmlShell } from "@decocms/blocks-admin/sdk/htmlShell";
97
97
  import { getAppMiddleware } from "@decocms/blocks-admin/sdk/setupApps";
@@ -1200,6 +1200,18 @@ export function createDecoWorkerEntry(
1200
1200
  ctx: WorkerExecutionContext,
1201
1201
  ): Promise<Response>;
1202
1202
  } {
1203
+ // `/live/_meta` reads the admin schema from the `ASSETS` binding when the
1204
+ // build published it as a static asset (`decoVitePlugin({ metaAsset: true })`).
1205
+ // Registered here so no site has to remember a setup call; inert for builds
1206
+ // that keep the schema in the bundle, since they never ask for the asset.
1207
+ setMetaAssetFetcher((assetPath) => {
1208
+ const assets = getRuntimeEnv()?.ASSETS as
1209
+ | { fetch(req: Request): Promise<Response> }
1210
+ | undefined;
1211
+ // Only the path matters to the binding; the host is a placeholder.
1212
+ return assets ? assets.fetch(new Request(new URL(assetPath, "https://assets.invalid"))) : null;
1213
+ });
1214
+
1203
1215
  const {
1204
1216
  admin,
1205
1217
  detectProfile: customDetect,
@@ -41,7 +41,8 @@
41
41
  * ```
42
42
  */
43
43
  import { exec, execFileSync } from "node:child_process";
44
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
44
+ import { createHash } from "node:crypto";
45
+ import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
45
46
  import path from "node:path";
46
47
 
47
48
  /**
@@ -90,6 +91,39 @@ const META_GEN_PREFIX = "\0deco-meta:";
90
91
  const META_GEN_SUFFIX = ".deco-meta.js";
91
92
  const metaGenSsrId = (file) => META_GEN_PREFIX + file + META_GEN_SUFFIX;
92
93
 
94
+ /**
95
+ * Turn the raw `meta.gen.json` into the static asset `/live/_meta` serves when
96
+ * `metaAsset` is on: the exact bytes the admin receives today
97
+ * (`{...schema, etag}`), plus the ETag the server bundle keeps.
98
+ *
99
+ * Only a pre-composed schema qualifies (`framework` set — what generate-schema
100
+ * writes). A raw one still needs `composeMeta` at runtime, so serving its bytes
101
+ * verbatim would change what the admin sees; return null and the caller keeps
102
+ * the in-bundle path.
103
+ *
104
+ * The ETag is merged textually rather than via parse+stringify so the asset is
105
+ * byte-for-byte the file plus one field.
106
+ *
107
+ * @param {string} raw
108
+ * @returns {{ fileName: string, etag: string, payload: string } | null}
109
+ */
110
+ export function buildMetaAsset(raw) {
111
+ let parsed;
112
+ try {
113
+ parsed = JSON.parse(raw);
114
+ } catch {
115
+ return null;
116
+ }
117
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || !parsed.framework) {
118
+ return null;
119
+ }
120
+ const hash = createHash("sha256").update(raw).digest("hex").slice(0, 16);
121
+ const etag = `"meta-${hash}"`;
122
+ const trimmed = raw.trimEnd();
123
+ const payload = `${trimmed.slice(0, -1)},"etag":${JSON.stringify(etag)}}`;
124
+ return { fileName: `_deco/meta-${hash}.json`, etag, payload };
125
+ }
126
+
93
127
  // Bare-specifier stubs resolved by ID before Vite touches them.
94
128
  /** @type {Record<string, string>} */
95
129
  const CLIENT_STUBS = {
@@ -193,6 +227,27 @@ function isSeededDeployPipeline() {
193
227
  return v === "1" || v === "true";
194
228
  }
195
229
 
230
+ /**
231
+ * `deco.sectionPackages` from the site's package.json → the realpath of each
232
+ * package's src/ (Vite reports realpaths for symlinked `file:` deps). Mirrors
233
+ * blocks-cli's readSectionPackages, which owns the "package missing" error.
234
+ * ponytail: only the site's own node_modules, no hoisted-workspace lookup.
235
+ */
236
+ function readSectionPackageSrcDirs(cwd) {
237
+ try {
238
+ const { deco } = JSON.parse(readFileSync(path.join(cwd, "package.json"), "utf8"));
239
+ return Object.entries(deco?.sectionPackages ?? {}).flatMap(([namespace, name]) => {
240
+ try {
241
+ return [{ namespace, srcDir: realpathSync(path.join(cwd, "node_modules", name, "src")) }];
242
+ } catch {
243
+ return [];
244
+ }
245
+ });
246
+ } catch {
247
+ return [];
248
+ }
249
+ }
250
+
196
251
  /**
197
252
  * @param {object} [opts]
198
253
  * @param {boolean | "auto"} [opts.fastDeploy="auto"] Stub `blocks.gen` out of
@@ -220,9 +275,29 @@ function isSeededDeployPipeline() {
220
275
  * it. `true` forces the stub, `false` disables it. A stubbed bundle also
221
276
  * needs `DECO_FAST_DEPLOY=1` and a `DECO_KV` binding at runtime — without
222
277
  * them `ensureBlocksHydrated` fails every request rather than serve `{}`.
278
+ * @param {boolean} [opts.metaAsset=false] Serve the admin schema (`meta.gen`)
279
+ * as a static asset instead of carrying it in the SERVER bundle.
280
+ *
281
+ * The schema is only read by `GET /live/_meta`, yet in the bundle it costs
282
+ * roughly four times its size in every isolate: V8 keeps the module source
283
+ * and materialises the `JSON.parse` string literal separately, both two-byte
284
+ * as soon as the text holds one character above U+00FF. Measured on a
285
+ * 6 MB schema: 27.9 MB of a 54 MB cold heap.
286
+ *
287
+ * With this on, a production build writes the schema to
288
+ * `<client outDir>/_deco/meta-<hash>.json` and the server module becomes a
289
+ * tiny `{ __decoMetaAsset: { path, etag } }` marker; `handleMeta` answers
290
+ * `If-None-Match` from the ETag and streams the body from the `ASSETS`
291
+ * binding. The asset ships in the same upload as the code, so there is no
292
+ * seed step and no window where code and schema disagree.
293
+ *
294
+ * Requires an `ASSETS` binding (`"assets": { "binding": "ASSETS", ... }` in
295
+ * wrangler.jsonc). Without it `/live/_meta` answers 503 — only the admin is
296
+ * affected, the site keeps serving. Dev (`vite dev`) is unchanged.
223
297
  * @returns {import("vite").PluginOption}
224
298
  */
225
- export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
299
+ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {}) {
300
+ const sectionPackages = readSectionPackageSrcDirs(process.cwd());
226
301
  // Resolved once: the pipeline's answer cannot change mid-build.
227
302
  const stubBlocks = fastDeploy === "auto" ? isSeededDeployPipeline() : fastDeploy === true;
228
303
  // Set from the `config` hook (which Vite always runs before `load`). The
@@ -231,6 +306,12 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
231
306
  // the `.json` sibling that the stub bypasses — stubbing there blanks the
232
307
  // local site.
233
308
  let isBuild = false;
309
+ // `metaAsset`: the schema asset captured while loading meta.gen on the
310
+ // server, and where the client build writes its output.
311
+ /** @type {{ fileName: string, etag: string, payload: string } | null} */
312
+ let metaAssetFile = null;
313
+ /** @type {string | null} */
314
+ let clientOutDir = null;
234
315
 
235
316
  /** @type {import("vite").Plugin} */
236
317
  const plugin = {
@@ -334,7 +415,21 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
334
415
  // byte of that whitespace is paid twice in the isolate (module source +
335
416
  // the string literal), at two-byte width since the schema has accented
336
417
  // text. On a real site: 7.3 MB chunk / +15 MB heap, vs 3.3 MB compact.
418
+ // The static asset uses the compact form too, so `/live/_meta` serves
419
+ // the same bytes either way.
337
420
  const compact = JSON.stringify(JSON.parse(readFileSync(file, "utf-8")));
421
+ if (metaAsset && isBuild) {
422
+ const asset = buildMetaAsset(compact);
423
+ if (asset) {
424
+ metaAssetFile = asset;
425
+ const ref = { __decoMetaAsset: { path: `/${asset.fileName}`, etag: asset.etag } };
426
+ return `export default ${JSON.stringify(ref)};`;
427
+ }
428
+ this.warn?.(
429
+ `metaAsset: ${file} is not a pre-composed schema (no \`framework\` field) — ` +
430
+ "keeping it in the server bundle. Regenerate it with generate-schema.",
431
+ );
432
+ }
338
433
  return `export default JSON.parse(${JSON.stringify(compact)});`;
339
434
  }
340
435
 
@@ -679,7 +774,8 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
679
774
  const isSchemaSource = (file) => {
680
775
  const rel = path.relative(cwd, file);
681
776
  return (
682
- schemaWatchDirs.some((d) => rel.startsWith(d + path.sep)) &&
777
+ (schemaWatchDirs.some((d) => rel.startsWith(d + path.sep)) ||
778
+ sectionPackages.some((p) => file.startsWith(p.srcDir + path.sep))) &&
683
779
  (rel.endsWith(".tsx") || rel.endsWith(".ts"))
684
780
  );
685
781
  };
@@ -1000,13 +1096,47 @@ export function decoVitePlugin({ fastDeploy = "auto" } = {}) {
1000
1096
  }
1001
1097
  },
1002
1098
 
1099
+ configResolved(config) {
1100
+ const outDir = config.environments?.client?.build?.outDir;
1101
+ clientOutDir = outDir ? path.resolve(config.root, outDir) : null;
1102
+ },
1103
+
1104
+ writeBundle() {
1105
+ // The server build runs after the client one, so the schema captured in
1106
+ // `load` is written straight into the client output — the directory
1107
+ // wrangler uploads as static assets. (`generateBundle` below covers the
1108
+ // opposite order.)
1109
+ if (!metaAssetFile || this.environment?.name === "client") return;
1110
+ if (!clientOutDir) {
1111
+ this.error("metaAsset: no client build outDir to write the admin schema to");
1112
+ }
1113
+ const out = path.join(clientOutDir, metaAssetFile.fileName);
1114
+ mkdirSync(path.dirname(out), { recursive: true });
1115
+ writeFileSync(out, metaAssetFile.payload);
1116
+ },
1117
+
1003
1118
  generateBundle(_, bundle) {
1119
+ if (metaAssetFile && this.environment?.name === "client") {
1120
+ this.emitFile({
1121
+ type: "asset",
1122
+ fileName: metaAssetFile.fileName,
1123
+ source: metaAssetFile.payload,
1124
+ });
1125
+ }
1004
1126
  // Build a mapping from section key to chunk filename.
1005
1127
  // Sites use this to emit <link rel="modulepreload"> for eager sections.
1006
1128
  const map = {};
1007
1129
  for (const [fileName, chunk] of Object.entries(bundle)) {
1008
1130
  if (chunk.type === "chunk" && chunk.facadeModuleId) {
1009
- const match = chunk.facadeModuleId.match(/\/(sections\/.+\.tsx)$/);
1131
+ const id = chunk.facadeModuleId;
1132
+ const pkg = sectionPackages.find((p) =>
1133
+ id.startsWith(path.join(p.srcDir, "sections") + path.sep),
1134
+ );
1135
+ if (pkg) {
1136
+ map[`${pkg.namespace}/${path.relative(pkg.srcDir, id)}`] = fileName;
1137
+ continue;
1138
+ }
1139
+ const match = id.match(/\/(sections\/.+\.tsx)$/);
1010
1140
  if (match) {
1011
1141
  map["site/" + match[1]] = fileName;
1012
1142
  }
@@ -1,8 +1,8 @@
1
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import path from "node:path";
4
4
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { decoVitePlugin, generateSchemaArgs } from "./plugin.js";
5
+ import { buildMetaAsset, decoVitePlugin, generateSchemaArgs } from "./plugin.js";
6
6
 
7
7
  /**
8
8
  * The Vite plugin's `resolveId` / `load` hooks are pure functions over their
@@ -251,3 +251,85 @@ describe("decoVitePlugin meta.gen.json on SSR (regression: vite:json double-pars
251
251
  );
252
252
  });
253
253
  });
254
+
255
+ describe("decoVitePlugin({ metaAsset }) — admin schema as a static asset", () => {
256
+ // The schema costs ~4x its size per isolate when bundled (source + JSON.parse
257
+ // literal, two-byte). With metaAsset the server bundle carries only a marker
258
+ // and the bytes ship as a client asset, served through the ASSETS binding.
259
+ const COMPOSED = '{"major":1,"framework":"tanstack","schema":{"definitions":{}}}\n';
260
+ let dir;
261
+
262
+ beforeEach(() => {
263
+ dir = mkdtempSync(path.join(tmpdir(), "deco-meta-asset-"));
264
+ mkdirSync(path.join(dir, ".deco"));
265
+ mkdirSync(path.join(dir, "src"));
266
+ });
267
+
268
+ afterEach(() => {
269
+ rmSync(dir, { recursive: true, force: true });
270
+ });
271
+
272
+ function buildPlugin(opts) {
273
+ const result = decoVitePlugin(opts);
274
+ const p = Array.isArray(result) ? result[0] : result;
275
+ p.config({}, { command: "build" });
276
+ p.configResolved({ root: dir, environments: { client: { build: { outDir: "dist/client" } } } });
277
+ return p;
278
+ }
279
+
280
+ function loadMeta(p, contents, ctx = {}) {
281
+ writeFileSync(path.join(dir, ".deco", "meta.gen.json"), contents);
282
+ const id = p.resolveId.call({}, "../.deco/meta.gen.json", path.join(dir, "src", "setup.ts"), {
283
+ ssr: true,
284
+ });
285
+ return p.load.call(ctx, id, { ssr: true });
286
+ }
287
+
288
+ it("replaces the server module with a tiny marker and writes the asset to the client outDir", () => {
289
+ const p = buildPlugin({ metaAsset: true });
290
+ const code = loadMeta(p, COMPOSED);
291
+ expect(code).not.toContain("JSON.parse");
292
+ const ref = JSON.parse(code.replace(/^export default /, "").replace(/;$/, "")).__decoMetaAsset;
293
+ expect(ref.path).toMatch(/^\/_deco\/meta-[0-9a-f]{16}\.json$/);
294
+
295
+ p.writeBundle.call({ environment: { name: "ssr" } });
296
+ const written = JSON.parse(readFileSync(path.join(dir, "dist/client", ref.path), "utf8"));
297
+ // Same wire format handleMeta always served: the schema plus its ETag.
298
+ expect(written).toEqual({ ...JSON.parse(COMPOSED), etag: ref.etag });
299
+ });
300
+
301
+ it("emits the asset from the client build too, for the reverse build order", () => {
302
+ const p = buildPlugin({ metaAsset: true });
303
+ loadMeta(p, COMPOSED);
304
+ const emitted = [];
305
+ p.generateBundle.call(
306
+ { environment: { name: "client" }, emitFile: (f) => emitted.push(f) },
307
+ {},
308
+ {},
309
+ );
310
+ expect(emitted).toHaveLength(1);
311
+ expect(emitted[0].fileName).toMatch(/^_deco\/meta-[0-9a-f]{16}\.json$/);
312
+ });
313
+
314
+ it("keeps a raw (not pre-composed) schema in the bundle, with a warning", () => {
315
+ const p = buildPlugin({ metaAsset: true });
316
+ const warn = vi.fn();
317
+ const code = loadMeta(p, '{"major":1,"schema":{}}', { warn });
318
+ expect(code).toContain("JSON.parse(");
319
+ expect(warn).toHaveBeenCalledOnce();
320
+ });
321
+
322
+ it("is off by default, and off in dev", () => {
323
+ expect(loadMeta(buildPlugin(), COMPOSED)).toContain("JSON.parse(");
324
+ const dev = buildPlugin({ metaAsset: true });
325
+ dev.config({}, { command: "serve" });
326
+ expect(loadMeta(dev, COMPOSED)).toContain("JSON.parse(");
327
+ });
328
+
329
+ it("buildMetaAsset merges the etag textually and rejects non-objects", () => {
330
+ const asset = buildMetaAsset(COMPOSED);
331
+ expect(JSON.parse(asset.payload).etag).toBe(asset.etag);
332
+ expect(buildMetaAsset("[1]")).toBeNull();
333
+ expect(buildMetaAsset("not json")).toBeNull();
334
+ });
335
+ });