@decocms/tanstack 7.81.2 → 7.81.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decocms/tanstack",
3
- "version": "7.81.2",
3
+ "version": "7.81.4",
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.81.2",
31
- "@decocms/blocks-admin": "7.81.2",
32
- "@decocms/blocks-cli": "7.81.2",
30
+ "@decocms/blocks": "7.81.4",
31
+ "@decocms/blocks-admin": "7.81.4",
32
+ "@decocms/blocks-cli": "7.81.4",
33
33
  "@deco-cx/warp-node": "^0.3.16",
34
34
  "fast-json-patch": "^3.1.0",
35
35
  "ws": "^8.18.0"
@@ -0,0 +1,129 @@
1
+ import { EventEmitter } from "node:events";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6
+
7
+ let schemaGenError = null;
8
+
9
+ vi.mock("node:child_process", () => {
10
+ const exec = (cmd, _opts, cb) => {
11
+ cb(cmd.includes("generate-schema.ts") ? schemaGenError : null, "", "");
12
+ };
13
+ const execFileSync = () => "";
14
+ return { exec, execFileSync, default: { exec, execFileSync } };
15
+ });
16
+
17
+ /**
18
+ * The isolate keeps the composed admin schema on globalThis, which outlives
19
+ * the meta.gen.json module the plugin invalidates after a dev regen. Without a
20
+ * decofile reload (the only caller of invalidateMetaCache), `/live/_meta` kept
21
+ * serving the boot-time schema, so a changed section's props never reached the
22
+ * admin form until the dev server restarted.
23
+ */
24
+ describe("decoVitePlugin — dev admin reads from Studio", () => {
25
+ let tmp;
26
+ let cwdSpy;
27
+ let fetchSpy;
28
+ let plugin;
29
+ let middlewares;
30
+
31
+ beforeEach(async () => {
32
+ vi.resetModules();
33
+ schemaGenError = null;
34
+ middlewares = [];
35
+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "plugin-dev-admin-"));
36
+ // Present, so the synchronous cold-start generation is skipped.
37
+ fs.mkdirSync(path.join(tmp, ".deco"));
38
+ fs.writeFileSync(path.join(tmp, ".deco", "meta.gen.json"), "{}");
39
+ cwdSpy = vi.spyOn(process, "cwd").mockReturnValue(tmp);
40
+ fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}", { status: 200 }));
41
+ vi.useFakeTimers();
42
+ ({ decoVitePlugin: plugin } = await import("./plugin.js"));
43
+ });
44
+
45
+ afterEach(() => {
46
+ vi.useRealTimers();
47
+ cwdSpy.mockRestore();
48
+ fs.rmSync(tmp, { recursive: true, force: true });
49
+ vi.restoreAllMocks();
50
+ });
51
+
52
+ function startServer({ stack = middlewares } = {}) {
53
+ const p = Array.isArray(plugin()) ? plugin()[0] : plugin();
54
+ const server = {
55
+ watcher: new EventEmitter(),
56
+ middlewares: { stack },
57
+ config: { define: {} },
58
+ environments: undefined,
59
+ httpServer: { once: () => {}, address: () => ({ port: 4321 }) },
60
+ };
61
+ p.configureServer(server);
62
+ return server;
63
+ }
64
+
65
+ const decofilePosts = () =>
66
+ fetchSpy.mock.calls.filter(([url]) => String(url).endsWith("/.decofile"));
67
+
68
+ it("posts an empty decofile delta after meta.gen.json is regenerated", async () => {
69
+ const server = startServer();
70
+ server.watcher.emit("change", path.join(tmp, "src", "sections", "Foo.tsx"));
71
+ await vi.advanceTimersByTimeAsync(600);
72
+
73
+ const posts = decofilePosts();
74
+ expect(posts).toHaveLength(1);
75
+ const [url, init] = posts[0];
76
+ expect(url).toBe("http://localhost:4321/.decofile");
77
+ expect(init.method).toBe("POST");
78
+ expect(JSON.parse(init.body)).toEqual({ blocks: {} });
79
+ });
80
+
81
+ it("does not post when schema generation fails", async () => {
82
+ schemaGenError = new Error("ts-morph exploded");
83
+ const server = startServer();
84
+ server.watcher.emit("change", path.join(tmp, "src", "sections", "Foo.tsx"));
85
+ await vi.advanceTimersByTimeAsync(600);
86
+
87
+ expect(decofilePosts()).toHaveLength(0);
88
+ });
89
+
90
+ /** Runs a request through the front of the stack, ahead of Vite's CORS. */
91
+ function preflight(method, url, origin) {
92
+ startServer();
93
+ const res = {
94
+ statusCode: 200,
95
+ headers: {},
96
+ ended: false,
97
+ setHeader(name, value) {
98
+ this.headers[name] = value;
99
+ },
100
+ end() {
101
+ this.ended = true;
102
+ },
103
+ };
104
+ let passed = false;
105
+ middlewares[0].handle({ method, url, headers: { origin } }, res, () => {
106
+ passed = true;
107
+ });
108
+ return { res, passed };
109
+ }
110
+
111
+ it("answers an admin preflight from Studio before Vite's CORS ends it", () => {
112
+ const { res, passed } = preflight("OPTIONS", "/live/_meta?x=1", "https://studio.decocms.com");
113
+ expect(passed).toBe(false);
114
+ expect(res.ended).toBe(true);
115
+ expect(res.statusCode).toBe(204);
116
+ expect(res.headers["Access-Control-Allow-Origin"]).toBe("https://studio.decocms.com");
117
+ expect(res.headers["Access-Control-Allow-Headers"]).toContain("If-None-Match");
118
+ });
119
+
120
+ it("leaves other requests to Vite", () => {
121
+ expect(preflight("GET", "/live/_meta", "https://studio.decocms.com").passed).toBe(true);
122
+ expect(preflight("OPTIONS", "/src/main.tsx", "https://studio.decocms.com").passed).toBe(true);
123
+ expect(preflight("OPTIONS", "/live/previews/", "https://studio.decocms.com").passed).toBe(true);
124
+ });
125
+
126
+ it("still starts when the middleware stack isn't connect's array", () => {
127
+ expect(() => startServer({ stack: undefined })).not.toThrow();
128
+ });
129
+ });
@@ -85,6 +85,33 @@ function resolveBuildHash() {
85
85
  return Date.now().toString(36);
86
86
  }
87
87
 
88
+ /**
89
+ * Admin routes whose preflight the worker answers (`tryAdminRoute` in
90
+ * `sdk/workerEntry.ts`).
91
+ * @param {string | undefined} url
92
+ */
93
+ function isAdminPreflightPath(url) {
94
+ const pathname = new URL(url ?? "/", "http://localhost").pathname;
95
+ return (
96
+ pathname === "/live/_meta" ||
97
+ pathname === "/.decofile" ||
98
+ (pathname.startsWith("/live/previews/") && pathname !== "/live/previews/")
99
+ );
100
+ }
101
+
102
+ /**
103
+ * The worker's preflight answer (`corsHeaders` in `@decocms/blocks-admin`).
104
+ * @param {string | undefined} origin
105
+ */
106
+ function adminPreflightHeaders(origin) {
107
+ return {
108
+ "Access-Control-Allow-Origin": origin || "*",
109
+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
110
+ "Access-Control-Allow-Headers": "Content-Type, Authorization, If-None-Match",
111
+ "Access-Control-Allow-Credentials": "true",
112
+ };
113
+ }
114
+
88
115
  // Virtual id for meta.gen.json on the server: the real path wrapped so the id
89
116
  // does NOT end in `.json` (Vite's `vite:json` would re-parse our JS output).
90
117
  const META_GEN_PREFIX = "\0deco-meta:";
@@ -474,6 +501,27 @@ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {})
474
501
  // Generator is loaded lazily via tsImport (same pattern as the daemon
475
502
  // below) so we don't depend on the consumer's TS loader.
476
503
  const cwd = process.cwd();
504
+
505
+ // Vite's CORS middleware ends every preflight itself and, since Vite 6,
506
+ // allows only localhost origins, so a cross-origin admin read that needs
507
+ // one (Studio's conditional `/live/_meta` through the tunnel) never
508
+ // reaches the worker's own answer. Vite installs it before running
509
+ // configureServer, hence the front of the stack rather than `use()`.
510
+ // That stack is connect's, not Vite's API: without it, only this
511
+ // preflight is lost, never the dev server.
512
+ if (Array.isArray(server.middlewares?.stack)) {
513
+ server.middlewares.stack.unshift({
514
+ route: "",
515
+ handle: (req, res, next) => {
516
+ if (req.method !== "OPTIONS" || !isAdminPreflightPath(req.url)) return next();
517
+ res.statusCode = 204;
518
+ for (const [name, value] of Object.entries(adminPreflightHeaders(req.headers.origin))) {
519
+ res.setHeader(name, value);
520
+ }
521
+ res.end();
522
+ },
523
+ });
524
+ }
477
525
  const blocksDir = path.resolve(cwd, ".deco/blocks");
478
526
  const outFile = path.resolve(cwd, ".deco/blocks.gen.ts");
479
527
  const jsonFile = outFile.replace(/\.ts$/, ".json");
@@ -527,6 +575,17 @@ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {})
527
575
  return { merged: mergedBlocks, result };
528
576
  };
529
577
 
578
+ // The workerd SSR runtime's decofile reload (handleDecofileReload).
579
+ const postDecofileDelta = async (blocks) => {
580
+ const addr = server.httpServer?.address();
581
+ const port = typeof addr === "object" && addr ? addr.port : 5173;
582
+ return fetch(`http://localhost:${port}/.decofile`, {
583
+ method: "POST",
584
+ headers: { "Content-Type": "application/json" },
585
+ body: JSON.stringify({ blocks }),
586
+ });
587
+ };
588
+
530
589
  // Live block edits are applied as a DELTA. The Studio daemon (or a manual
531
590
  // edit) writes a single `.deco/blocks/*.json` file; re-reading and
532
591
  // re-merging the whole directory on every write blocks the Node/Vite event
@@ -583,13 +642,7 @@ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {})
583
642
  // POST a delta envelope ({ blocks: {...} }) so handleDecofileReload
584
643
  // merges it over the current snapshot instead of replacing the whole
585
644
  // decofile. setBlocks() runs inside the workerd SSR runtime.
586
- const addr = server.httpServer?.address();
587
- const port = typeof addr === "object" && addr ? addr.port : 5173;
588
- const res = await fetch(`http://localhost:${port}/.decofile`, {
589
- method: "POST",
590
- headers: { "Content-Type": "application/json" },
591
- body: JSON.stringify({ blocks: delta }),
592
- });
645
+ const res = await postDecofileDelta(delta);
593
646
  const ms = Date.now() - start;
594
647
  if (res.ok) {
595
648
  console.log(`[deco] applied ${keys.length}-block delta in ${ms}ms`);
@@ -723,6 +776,16 @@ export function decoVitePlugin({ fastDeploy = "auto", metaAsset = false } = {})
723
776
  if (mod) {
724
777
  server.environments.ssr.moduleGraph.invalidateModule(mod);
725
778
  }
779
+ // The isolate keeps the composed schema on globalThis, which
780
+ // outlives the module above; only the decofile reload clears it
781
+ // (invalidateMetaCache). An empty delta changes no block.
782
+ postDecofileDelta({})
783
+ .then((res) => {
784
+ if (!res.ok) console.warn(`[deco] meta cache invalidation failed: ${res.status}`);
785
+ })
786
+ .catch((err) => {
787
+ console.warn("[deco] meta cache invalidation failed:", err?.message ?? err);
788
+ });
726
789
  }
727
790
  if (schemaQueued) {
728
791
  schemaQueued = false;