@decocms/tanstack 8.1.0-next.0 → 8.4.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/README.md +79 -0
- package/dist/draft.d.ts +33 -0
- package/dist/draft.d.ts.map +1 -0
- package/dist/draft.js +41 -0
- package/dist/draft.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/react/DecoDocument.d.ts +61 -0
- package/dist/react/DecoDocument.d.ts.map +1 -0
- package/dist/react/DecoDocument.js +96 -0
- package/dist/react/DecoDocument.js.map +1 -0
- package/dist/react/Image.d.ts +96 -0
- package/dist/react/Image.d.ts.map +1 -0
- package/dist/react/Image.js +79 -0
- package/dist/react/Image.js.map +1 -0
- package/dist/react/index.d.ts +7 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +7 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/pageValues.d.ts +10 -0
- package/dist/react/pageValues.d.ts.map +1 -0
- package/dist/react/pageValues.js +29 -0
- package/dist/react/pageValues.js.map +1 -0
- package/dist/react/scripts.d.ts +14 -0
- package/dist/react/scripts.d.ts.map +1 -0
- package/dist/react/scripts.js +96 -0
- package/dist/react/scripts.js.map +1 -0
- package/dist/router/index.d.ts +38 -0
- package/dist/router/index.d.ts.map +1 -0
- package/dist/router/index.js +60 -0
- package/dist/router/index.js.map +1 -0
- package/dist/scope/browser.d.ts +11 -0
- package/dist/scope/browser.d.ts.map +1 -0
- package/dist/scope/browser.js +8 -0
- package/dist/scope/browser.js.map +1 -0
- package/dist/scope/server.d.ts +13 -0
- package/dist/scope/server.d.ts.map +1 -0
- package/dist/scope/server.js +26 -0
- package/dist/scope/server.js.map +1 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +31 -0
- package/dist/server/index.js.map +1 -0
- package/dist/shared.d.ts +26 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +26 -0
- package/dist/shared.js.map +1 -0
- package/dist/start/index.d.ts +9 -0
- package/dist/start/index.d.ts.map +1 -0
- package/dist/start/index.js +33 -0
- package/dist/start/index.js.map +1 -0
- package/dist/studio.d.ts +28 -0
- package/dist/studio.d.ts.map +1 -0
- package/dist/studio.js +53 -0
- package/dist/studio.js.map +1 -0
- package/dist/vite/index.d.ts +15 -0
- package/dist/vite/index.d.ts.map +1 -0
- package/dist/vite/index.js +95 -0
- package/dist/vite/index.js.map +1 -0
- package/dist/worker/cacheProfiles.d.ts +43 -0
- package/dist/worker/cacheProfiles.d.ts.map +1 -0
- package/dist/worker/cacheProfiles.js +162 -0
- package/dist/worker/cacheProfiles.js.map +1 -0
- package/dist/worker/cookies.d.ts +20 -0
- package/dist/worker/cookies.d.ts.map +1 -0
- package/dist/worker/cookies.js +69 -0
- package/dist/worker/cookies.js.map +1 -0
- package/dist/worker/drafts.d.ts +59 -0
- package/dist/worker/drafts.d.ts.map +1 -0
- package/dist/worker/drafts.js +140 -0
- package/dist/worker/drafts.js.map +1 -0
- package/dist/worker/index.d.ts +107 -0
- package/dist/worker/index.d.ts.map +1 -0
- package/dist/worker/index.js +511 -0
- package/dist/worker/index.js.map +1 -0
- package/dist/worker/security.d.ts +14 -0
- package/dist/worker/security.d.ts.map +1 -0
- package/dist/worker/security.js +48 -0
- package/dist/worker/security.js.map +1 -0
- package/dist/worker/segment.d.ts +21 -0
- package/dist/worker/segment.d.ts.map +1 -0
- package/dist/worker/segment.js +43 -0
- package/dist/worker/segment.js.map +1 -0
- package/package.json +85 -37
- package/src/draft.ts +43 -0
- package/src/index.ts +8 -61
- package/src/react/DecoDocument.tsx +234 -0
- package/src/react/Image.tsx +213 -0
- package/src/react/index.ts +24 -0
- package/src/react/pageValues.ts +35 -0
- package/src/react/scripts.ts +98 -0
- package/src/router/index.ts +80 -0
- package/src/scope/browser.ts +18 -0
- package/src/scope/server.ts +37 -0
- package/src/server/index.ts +43 -0
- package/src/shared.ts +29 -0
- package/src/start/index.ts +31 -0
- package/src/studio.ts +52 -0
- package/src/vite/index.ts +105 -0
- package/src/worker/cacheProfiles.ts +180 -0
- package/src/worker/cookies.ts +65 -0
- package/src/worker/drafts.ts +157 -0
- package/src/worker/index.ts +648 -0
- package/src/worker/security.ts +63 -0
- package/src/worker/segment.ts +49 -0
- package/src/__conformance__/observability.test.ts +0 -221
- package/src/cms/kvBlockSource.test.ts +0 -82
- package/src/cms/kvBlockSource.ts +0 -68
- package/src/daemon/auth.ts +0 -204
- package/src/daemon/fs.ts +0 -238
- package/src/daemon/index.ts +0 -8
- package/src/daemon/middleware.ts +0 -156
- package/src/daemon/tunnel.ts +0 -129
- package/src/daemon/volumes.ts +0 -366
- package/src/daemon/watch.ts +0 -272
- package/src/hooks/CdnSegmentMarker.tsx +0 -38
- package/src/hooks/DecoPageRenderer.tsx +0 -750
- package/src/hooks/DecoRootLayout.tsx +0 -192
- package/src/hooks/DraftPreviewIndicator.test.tsx +0 -60
- package/src/hooks/DraftPreviewIndicator.tsx +0 -64
- package/src/hooks/NavigationProgress.test.tsx +0 -58
- package/src/hooks/NavigationProgress.tsx +0 -63
- package/src/hooks/PreviewProviders.test.tsx +0 -42
- package/src/hooks/PreviewProviders.tsx +0 -45
- package/src/hooks/StableOutlet.tsx +0 -30
- package/src/hooks/deferredObserverTiming.test.tsx +0 -91
- package/src/hooks/index.ts +0 -10
- package/src/routes/adminRoutes.test.ts +0 -99
- package/src/routes/adminRoutes.ts +0 -153
- package/src/routes/cmsRoute.test.ts +0 -267
- package/src/routes/cmsRoute.ts +0 -1053
- package/src/routes/components.tsx +0 -57
- package/src/routes/index.ts +0 -24
- package/src/routes/pageUrl.test.ts +0 -70
- package/src/routes/pageUrl.ts +0 -55
- package/src/routes/withSiteGlobals.test.ts +0 -243
- package/src/routes/withSiteGlobals.ts +0 -243
- package/src/sdk/backgroundTasks.test.ts +0 -68
- package/src/sdk/backgroundTasks.ts +0 -38
- package/src/sdk/cdnSegment.test.ts +0 -67
- package/src/sdk/cdnSegment.ts +0 -71
- package/src/sdk/cookiePassthrough.ts +0 -58
- package/src/sdk/createInvoke.ts +0 -77
- package/src/sdk/deferredSectionLoader.test.ts +0 -94
- package/src/sdk/deferredSectionLoader.ts +0 -46
- package/src/sdk/draft.test.ts +0 -341
- package/src/sdk/draft.ts +0 -277
- package/src/sdk/draftShared.ts +0 -16
- package/src/sdk/kvHydration.test.ts +0 -371
- package/src/sdk/kvHydration.ts +0 -263
- package/src/sdk/kvRedirects.test.ts +0 -132
- package/src/sdk/kvRedirects.ts +0 -125
- package/src/sdk/outboundHeaders.test.ts +0 -113
- package/src/sdk/outboundHeaders.ts +0 -81
- package/src/sdk/router.ts +0 -101
- package/src/sdk/serverFnFetch.ts +0 -59
- package/src/sdk/speculationRules.test.ts +0 -82
- package/src/sdk/speculationRules.ts +0 -136
- package/src/sdk/startEntry.ts +0 -31
- package/src/sdk/useHydrated.ts +0 -19
- package/src/sdk/workerEntry.cacheStorage.test.ts +0 -147
- package/src/sdk/workerEntry.test.ts +0 -1033
- package/src/sdk/workerEntry.trackingCache.test.ts +0 -328
- package/src/sdk/workerEntry.ts +0 -3154
- package/src/setupFastDeploy.ts +0 -13
- package/src/v8/__conformance__/delivery.test.ts +0 -100
- package/src/v8/binding.ts +0 -70
- package/src/v8/kvLoader.bundle.test.ts +0 -42
- package/src/v8/kvLoader.test.ts +0 -74
- package/src/v8/kvLoader.ts +0 -43
- package/src/vite/plugin-scaffold-gen.test.js +0 -106
- package/src/vite/plugin.js +0 -1022
- package/src/vite/plugin.test.js +0 -238
- package/src/vite/plugin.test.ts +0 -176
- package/tsconfig.json +0 -7
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@decocms/tanstack/vite`: the Vite plugins a Deco TanStack site adds next to
|
|
3
|
+
* `cloudflare()`, `tanstackStart()` and `react()`.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* plugins: [
|
|
7
|
+
* cloudflare({ viteEnvironment: { name: "ssr" } }),
|
|
8
|
+
* tanstackStart(),
|
|
9
|
+
* react(),
|
|
10
|
+
* decoTanstack({ buildHash: process.env.WORKERS_CI_COMMIT_SHA }),
|
|
11
|
+
* ]
|
|
12
|
+
* ```
|
|
13
|
+
*
|
|
14
|
+
* - `decoContent()` from `@decocms/blocks/vite` (a block saved in the site
|
|
15
|
+
* editor reloads open pages in `vite dev`);
|
|
16
|
+
* - `__BUILD_HASH__`, the build's id the worker keys its cache on: the commit
|
|
17
|
+
* (the CI's sha when given, else `git`, else the time), `"dev"` in `vite dev`;
|
|
18
|
+
* - a browser stub for `node:async_hooks`, so server state never breaks the client build;
|
|
19
|
+
* - one copy of React and the TanStack packages (`resolve.dedupe`).
|
|
20
|
+
*/
|
|
21
|
+
import { execFileSync } from "node:child_process";
|
|
22
|
+
import { decoContent } from "@decocms/blocks/vite";
|
|
23
|
+
import type { Plugin } from "vite";
|
|
24
|
+
|
|
25
|
+
const SHA_LENGTH = 12;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The commit this build is made from (`git rev-parse --short=12 HEAD`), or the
|
|
29
|
+
* time when git can't say (no git, not a repository), so two builds never share
|
|
30
|
+
* a key by accident.
|
|
31
|
+
*/
|
|
32
|
+
export function gitBuildHash(cwd?: string): string {
|
|
33
|
+
try {
|
|
34
|
+
const sha = execFileSync("git", ["rev-parse", `--short=${SHA_LENGTH}`, "HEAD"], {
|
|
35
|
+
cwd,
|
|
36
|
+
encoding: "utf8",
|
|
37
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
38
|
+
}).trim();
|
|
39
|
+
if (sha) return sha;
|
|
40
|
+
} catch {
|
|
41
|
+
// no git here
|
|
42
|
+
}
|
|
43
|
+
return Date.now().toString(36);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The build hash for `vite build`: the CI's sha (shortened), else {@link gitBuildHash}. */
|
|
47
|
+
export function resolveBuildHash(ciSha: string | undefined, cwd?: string): string {
|
|
48
|
+
const fromCi = ciSha?.trim();
|
|
49
|
+
return fromCi ? fromCi.slice(0, SHA_LENGTH) : gitBuildHash(cwd);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const DEDUPE = [
|
|
53
|
+
"@tanstack/react-start",
|
|
54
|
+
"@tanstack/react-router",
|
|
55
|
+
"@tanstack/react-start-server",
|
|
56
|
+
"@tanstack/start-server-core",
|
|
57
|
+
"@tanstack/start-client-core",
|
|
58
|
+
"@tanstack/start-storage-context",
|
|
59
|
+
"@decocms/blocks",
|
|
60
|
+
"react",
|
|
61
|
+
"react-dom",
|
|
62
|
+
];
|
|
63
|
+
|
|
64
|
+
const ASYNC_HOOKS_STUB = "\0decocms:async-hooks-stub";
|
|
65
|
+
|
|
66
|
+
/** `node:async_hooks` in the browser: the same shape, holding nothing. */
|
|
67
|
+
const ASYNC_HOOKS_STUB_SOURCE = `export class AsyncLocalStorage {
|
|
68
|
+
run(_store, fn, ...args) { return fn(...args); }
|
|
69
|
+
getStore() { return undefined; }
|
|
70
|
+
enterWith() {}
|
|
71
|
+
disable() {}
|
|
72
|
+
exit(fn, ...args) { return fn(...args); }
|
|
73
|
+
}
|
|
74
|
+
export default { AsyncLocalStorage };
|
|
75
|
+
`;
|
|
76
|
+
|
|
77
|
+
export interface DecoTanstackOptions {
|
|
78
|
+
/** The CI's commit sha (e.g. `process.env.WORKERS_CI_COMMIT_SHA`); without it, git's. */
|
|
79
|
+
buildHash?: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function decoTanstack(options: DecoTanstackOptions = {}): Plugin[] {
|
|
83
|
+
const settings: Plugin = {
|
|
84
|
+
name: "decocms:tanstack",
|
|
85
|
+
config(_config, { command }) {
|
|
86
|
+
const buildHash = command === "build" ? resolveBuildHash(options.buildHash) : "dev";
|
|
87
|
+
return {
|
|
88
|
+
define: { __BUILD_HASH__: JSON.stringify(buildHash) },
|
|
89
|
+
resolve: { dedupe: DEDUPE },
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
const asyncHooksStub: Plugin = {
|
|
94
|
+
name: "decocms:tanstack-async-hooks-stub",
|
|
95
|
+
enforce: "pre",
|
|
96
|
+
applyToEnvironment: (environment) => environment.config.consumer === "client",
|
|
97
|
+
resolveId(id) {
|
|
98
|
+
return id === "node:async_hooks" || id === "async_hooks" ? ASYNC_HOOKS_STUB : undefined;
|
|
99
|
+
},
|
|
100
|
+
load(id) {
|
|
101
|
+
return id === ASYNC_HOOKS_STUB ? ASYNC_HOOKS_STUB_SOURCE : undefined;
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
return [settings, asyncHooksStub, decoContent()];
|
|
105
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page cache profiles: how long a response may be served from the edge cache
|
|
3
|
+
* and from the browser, picked per URL. The values and URL rules are v7's
|
|
4
|
+
* (`@decocms/blocks/sdk/cacheHeaders`), which the TanStack storefronts copied
|
|
5
|
+
* unchanged; a site that needs other values passes `cacheProfiles` to
|
|
6
|
+
* `createDecoWorker`.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export type CacheProfileName =
|
|
10
|
+
| "static"
|
|
11
|
+
| "product"
|
|
12
|
+
| "listing"
|
|
13
|
+
| "search"
|
|
14
|
+
| "cart"
|
|
15
|
+
| "private"
|
|
16
|
+
| "none";
|
|
17
|
+
|
|
18
|
+
/** Seconds: `fresh` = served as is; `swr` = served stale while revalidating; `sie` = served stale when the origin fails. */
|
|
19
|
+
export interface CacheWindow {
|
|
20
|
+
fresh: number;
|
|
21
|
+
swr: number;
|
|
22
|
+
sie: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface CacheProfile {
|
|
26
|
+
edge: CacheWindow;
|
|
27
|
+
browser: CacheWindow;
|
|
28
|
+
isPublic: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A site's changes to the default profiles: only the values that differ. */
|
|
32
|
+
export type CacheProfileOverrides = Partial<
|
|
33
|
+
Record<CacheProfileName, { edge?: Partial<CacheWindow>; browser?: Partial<CacheWindow> }>
|
|
34
|
+
>;
|
|
35
|
+
|
|
36
|
+
const NEVER: CacheWindow = { fresh: 0, swr: 0, sie: 0 };
|
|
37
|
+
const NO_CACHE: CacheProfile = { edge: NEVER, browser: NEVER, isPublic: false };
|
|
38
|
+
|
|
39
|
+
export const DEFAULT_CACHE_PROFILES: Readonly<Record<CacheProfileName, CacheProfile>> = {
|
|
40
|
+
static: {
|
|
41
|
+
edge: { fresh: 900, swr: 7200, sie: 21600 },
|
|
42
|
+
browser: { fresh: 120, swr: 1800, sie: 7200 },
|
|
43
|
+
isPublic: true,
|
|
44
|
+
},
|
|
45
|
+
product: {
|
|
46
|
+
edge: { fresh: 300, swr: 1800, sie: 7200 },
|
|
47
|
+
browser: { fresh: 60, swr: 600, sie: 3600 },
|
|
48
|
+
isPublic: true,
|
|
49
|
+
},
|
|
50
|
+
listing: {
|
|
51
|
+
edge: { fresh: 120, swr: 900, sie: 3600 },
|
|
52
|
+
browser: { fresh: 30, swr: 300, sie: 1800 },
|
|
53
|
+
isPublic: true,
|
|
54
|
+
},
|
|
55
|
+
search: {
|
|
56
|
+
edge: { fresh: 60, swr: 300, sie: 1800 },
|
|
57
|
+
browser: { fresh: 0, swr: 120, sie: 600 },
|
|
58
|
+
isPublic: true,
|
|
59
|
+
},
|
|
60
|
+
cart: NO_CACHE,
|
|
61
|
+
private: NO_CACHE,
|
|
62
|
+
none: NO_CACHE,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** The defaults with a site's overrides applied. The private profiles stay private. */
|
|
66
|
+
export function resolveProfiles(
|
|
67
|
+
overrides: CacheProfileOverrides | undefined,
|
|
68
|
+
): Record<CacheProfileName, CacheProfile> {
|
|
69
|
+
const out = { ...DEFAULT_CACHE_PROFILES };
|
|
70
|
+
for (const [name, change] of Object.entries(overrides ?? {}) as [
|
|
71
|
+
CacheProfileName,
|
|
72
|
+
CacheProfileOverrides[CacheProfileName],
|
|
73
|
+
][]) {
|
|
74
|
+
const base = DEFAULT_CACHE_PROFILES[name];
|
|
75
|
+
if (!base || !change || !base.isPublic) continue;
|
|
76
|
+
out[name] = {
|
|
77
|
+
isPublic: true,
|
|
78
|
+
edge: { ...base.edge, ...change.edge },
|
|
79
|
+
browser: { ...base.browser, ...change.browser },
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export const PRIVATE_NO_CACHE = "private, no-cache, no-store, must-revalidate";
|
|
86
|
+
|
|
87
|
+
/** The browser's `Cache-Control` for a profile. */
|
|
88
|
+
export function cacheControl(profile: CacheProfile): string {
|
|
89
|
+
if (!profile.isPublic || (profile.edge.fresh === 0 && profile.browser.fresh === 0)) {
|
|
90
|
+
return PRIVATE_NO_CACHE;
|
|
91
|
+
}
|
|
92
|
+
const { browser, edge } = profile;
|
|
93
|
+
const parts = ["public", browser.fresh > 0 ? `max-age=${browser.fresh}` : "max-age=0"];
|
|
94
|
+
if (edge.fresh > 0) parts.push(`s-maxage=${edge.fresh}`);
|
|
95
|
+
if (browser.swr > 0) parts.push(`stale-while-revalidate=${browser.swr}`);
|
|
96
|
+
if (browser.sie > 0) parts.push(`stale-if-error=${browser.sie}`);
|
|
97
|
+
return parts.join(", ");
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const PRIVATE_PREFIX_RE = /^\/(cart|checkout|account|login|my-account)(\/|$)/;
|
|
101
|
+
|
|
102
|
+
/** The profile of a page URL. The first rule that matches wins. */
|
|
103
|
+
export function detectCacheProfile(url: URL): CacheProfileName {
|
|
104
|
+
const p = url.pathname;
|
|
105
|
+
if (PRIVATE_PREFIX_RE.test(p)) return "private";
|
|
106
|
+
if (p.startsWith("/api/") || p.startsWith("/deco/") || p.startsWith("/_build")) return "none";
|
|
107
|
+
if (p === "/sitemap.xml") return "static";
|
|
108
|
+
if (p === "/s" || p.startsWith("/s/") || url.searchParams.has("q")) return "search";
|
|
109
|
+
if (p.endsWith("/p")) return "product";
|
|
110
|
+
if (p === "/" || p === "") return "static";
|
|
111
|
+
return "listing";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function isServerFnPath(pathname: string): boolean {
|
|
115
|
+
return pathname.startsWith("/_serverFn/") || pathname.startsWith("/_server/");
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The page a GET server-function request loads, from its `payload`: the first
|
|
120
|
+
* string in it that is a local path. `null` for any other server function.
|
|
121
|
+
*/
|
|
122
|
+
export function serverFnPagePath(url: URL): string | null {
|
|
123
|
+
if (!isServerFnPath(url.pathname)) return null;
|
|
124
|
+
const payload = url.searchParams.get("payload");
|
|
125
|
+
if (!payload) return null;
|
|
126
|
+
let found: string | null = null;
|
|
127
|
+
const visit = (v: unknown): void => {
|
|
128
|
+
if (found !== null) return;
|
|
129
|
+
if (typeof v === "string") {
|
|
130
|
+
if (v.startsWith("/") && !v.startsWith("//")) found = v;
|
|
131
|
+
} else if (Array.isArray(v)) {
|
|
132
|
+
for (const x of v) visit(x);
|
|
133
|
+
} else if (v && typeof v === "object") {
|
|
134
|
+
for (const x of Object.values(v)) visit(x);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
try {
|
|
138
|
+
visit(JSON.parse(payload));
|
|
139
|
+
} catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
return found;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Variant params a page loader ignores, left out of a server function's cache key. */
|
|
146
|
+
const SERVER_FN_IGNORED_PARAMS = ["skuId", "idsku"];
|
|
147
|
+
|
|
148
|
+
/** A server function's payload for its cache key: page paths without the variant params. */
|
|
149
|
+
export function canonicalizeServerFnPayload(payload: string): string {
|
|
150
|
+
const stripQuery = (s: string): string => {
|
|
151
|
+
if (!s.startsWith("/") || s.startsWith("//")) return s;
|
|
152
|
+
const q = s.indexOf("?");
|
|
153
|
+
if (q < 0) return s;
|
|
154
|
+
const sp = new URLSearchParams(s.slice(q + 1));
|
|
155
|
+
for (const p of SERVER_FN_IGNORED_PARAMS) sp.delete(p);
|
|
156
|
+
const rest = sp.toString();
|
|
157
|
+
return rest ? `${s.slice(0, q)}?${rest}` : s.slice(0, q);
|
|
158
|
+
};
|
|
159
|
+
const visit = (v: unknown): unknown => {
|
|
160
|
+
if (typeof v === "string") return stripQuery(v);
|
|
161
|
+
if (Array.isArray(v)) return v.map(visit);
|
|
162
|
+
if (v && typeof v === "object")
|
|
163
|
+
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, visit(x)]));
|
|
164
|
+
return v;
|
|
165
|
+
};
|
|
166
|
+
try {
|
|
167
|
+
return JSON.stringify(visit(JSON.parse(payload)));
|
|
168
|
+
} catch {
|
|
169
|
+
return payload;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The profile of a request: a GET server function takes its page's, any other one is private. */
|
|
174
|
+
export function profileOf(url: URL): CacheProfileName {
|
|
175
|
+
if (isServerFnPath(url.pathname)) {
|
|
176
|
+
const page = serverFnPagePath(url);
|
|
177
|
+
return page ? detectCacheProfile(new URL(page, url.origin)) : "private";
|
|
178
|
+
}
|
|
179
|
+
return detectCacheProfile(url);
|
|
180
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Set-Cookie handling: which cookies a cached response may carry, and one header per cookie. */
|
|
2
|
+
|
|
3
|
+
function cookieName(setCookie: string): string {
|
|
4
|
+
const eq = setCookie.indexOf("=");
|
|
5
|
+
return eq > 0 ? setCookie.slice(0, eq).trim() : "";
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** Whether every cookie the response sets is one a shared (cached) response may set. */
|
|
9
|
+
export function hasOnlySafeCookies(response: Response, safe: ReadonlySet<string>): boolean {
|
|
10
|
+
return response.headers.getSetCookie().every((c) => {
|
|
11
|
+
const name = cookieName(c);
|
|
12
|
+
return name === "" || safe.has(name);
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A copy for the cache without the safe cookies; the visitor still gets them. */
|
|
17
|
+
export function withoutSafeCookies(response: Response, safe: ReadonlySet<string>): Response {
|
|
18
|
+
const copy = response.clone();
|
|
19
|
+
const cookies = response.headers.getSetCookie();
|
|
20
|
+
if (cookies.length === 0) return copy;
|
|
21
|
+
copy.headers.delete("set-cookie");
|
|
22
|
+
for (const c of cookies) {
|
|
23
|
+
const name = cookieName(c);
|
|
24
|
+
if (name && !safe.has(name)) copy.headers.append("set-cookie", c);
|
|
25
|
+
}
|
|
26
|
+
return copy;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A Set-Cookie's identity: name + Domain + Path, the way the browser keys its
|
|
31
|
+
* cookie jar (RFC 6265 §5.3), so two headers that differ in scope address two
|
|
32
|
+
* cookies. The domain is case-insensitive and a leading dot is ignored; the
|
|
33
|
+
* path is compared as sent. v7's #642.
|
|
34
|
+
*/
|
|
35
|
+
export function setCookieIdentity(setCookie: string): string {
|
|
36
|
+
const [nameValue = "", ...attrs] = setCookie.split(";");
|
|
37
|
+
const eq = nameValue.indexOf("=");
|
|
38
|
+
const name = eq > 0 ? nameValue.slice(0, eq).trim() : nameValue.trim();
|
|
39
|
+
let domain = "";
|
|
40
|
+
let path = "";
|
|
41
|
+
for (const attr of attrs) {
|
|
42
|
+
const sep = attr.indexOf("=");
|
|
43
|
+
const key = (sep >= 0 ? attr.slice(0, sep) : attr).trim().toLowerCase();
|
|
44
|
+
const value = sep >= 0 ? attr.slice(sep + 1).trim() : "";
|
|
45
|
+
if (key === "domain") domain = value.replace(/^\./, "").toLowerCase();
|
|
46
|
+
else if (key === "path") path = value;
|
|
47
|
+
}
|
|
48
|
+
return `${name}\u0000${domain}\u0000${path}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Keeps the last Set-Cookie of each cookie (name + Domain + Path): several
|
|
53
|
+
* layers may set the same cookie. Keying on the name alone would collapse a
|
|
54
|
+
* sign-out that clears one cookie under several scopes into a single clear,
|
|
55
|
+
* leaving the others signed in. The response's headers must be mutable.
|
|
56
|
+
*/
|
|
57
|
+
export function dedupeSetCookies(response: Response): void {
|
|
58
|
+
const cookies = response.headers.getSetCookie();
|
|
59
|
+
if (cookies.length <= 1) return;
|
|
60
|
+
const last = new Map<string, string>();
|
|
61
|
+
for (const c of cookies) last.set(setCookieIdentity(c), c);
|
|
62
|
+
if (last.size === cookies.length) return;
|
|
63
|
+
response.headers.delete("set-cookie");
|
|
64
|
+
for (const c of last.values()) response.headers.append("set-cookie", c);
|
|
65
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which hosts may render drafts: v7's allowlist (`@decocms/blocks` 7.x
|
|
3
|
+
* `cms/draftSource.ts`: `readAllowedHosts`, `isDraftHostAllowed`,
|
|
4
|
+
* `isDraftPreviewEnabled`), ported as is. v7 read its override from the
|
|
5
|
+
* `DECO_ALLOWED_PREVIEW_HOSTS` variable; here it is the `previewHosts` option.
|
|
6
|
+
*
|
|
7
|
+
* - The site's own preview hosts: the ones it declares, in the `CMS` block or
|
|
8
|
+
* as `createCMS({ preview: { hosts } })` (matched as `cms.draftPointer`
|
|
9
|
+
* matches them). A site that declares none has none, as in v7: blocks'
|
|
10
|
+
* own default (every host) doesn't count as a declaration.
|
|
11
|
+
* - The hosts Deco runs the site on, named after the site and always added:
|
|
12
|
+
* `<site>.deco.site` and `<site>.deco-cx.workers.dev`, exact.
|
|
13
|
+
* - `previewHosts: [...]` replaces the site's own list (the inferred hosts are
|
|
14
|
+
* still added); `previewHosts: "none"` turns previews off on every host.
|
|
15
|
+
*
|
|
16
|
+
* Hosts compare exactly, lowercased, port included (`localhost:5173`).
|
|
17
|
+
*
|
|
18
|
+
* The draft itself is the capability: a host check only bounds where a draft
|
|
19
|
+
* link works. A request the check refuses gets the release, never an error.
|
|
20
|
+
*/
|
|
21
|
+
import { type CMS, parseDraftPointer } from "@decocms/blocks";
|
|
22
|
+
import { DRAFT_COOKIE, DRAFT_PARAM } from "../draft.ts";
|
|
23
|
+
|
|
24
|
+
export interface PreviewPolicy {
|
|
25
|
+
/** The site's name: `<site>.deco.site` and `<site>.deco-cx.workers.dev` may preview. */
|
|
26
|
+
site?: string;
|
|
27
|
+
/** Replaces the `CMS` block's preview hosts; `"none"` turns previews off everywhere. */
|
|
28
|
+
previewHosts?: readonly string[] | "none";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The hosts Deco runs `site` on, which may always preview (unless previews are off). */
|
|
32
|
+
export function inferredPreviewHosts(site: string | undefined): string[] {
|
|
33
|
+
const s = (site ?? "").trim().toLowerCase();
|
|
34
|
+
return s ? [`${s}.deco.site`, `${s}.deco-cx.workers.dev`] : [];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Whether `host` may preview without asking the CMS: `true` (an override or
|
|
39
|
+
* inferred host), `false` (previews off, or the override leaves it out), or
|
|
40
|
+
* `"cms"` when only the site's declared preview hosts can say (none declared:
|
|
41
|
+
* `false`, see {@link declaresPreviewHosts}).
|
|
42
|
+
*/
|
|
43
|
+
export function previewHostDecision(host: string, policy: PreviewPolicy): boolean | "cms" {
|
|
44
|
+
const override =
|
|
45
|
+
policy.previewHosts === "none"
|
|
46
|
+
? ["none"]
|
|
47
|
+
: (policy.previewHosts ?? []).map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
48
|
+
if (override.includes("none")) return false;
|
|
49
|
+
const h = host.trim().toLowerCase();
|
|
50
|
+
if (h === "") return false;
|
|
51
|
+
if (inferredPreviewHosts(policy.site).includes(h)) return true;
|
|
52
|
+
if (policy.previewHosts !== undefined) return override.includes(h);
|
|
53
|
+
return "cms";
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Whether the site declares its own preview hosts: in the `CMS` block, or as
|
|
58
|
+
* `createCMS`'s `preview.hosts`. When it declares none, `cms.settings()`
|
|
59
|
+
* reports blocks' default, every host (`["*"]`), which v7 never had: there,
|
|
60
|
+
* a site without a list previewed only on its Deco hosts. The saved `CMS`
|
|
61
|
+
* block tells an explicit `["*"]` from that default.
|
|
62
|
+
*/
|
|
63
|
+
export async function declaresPreviewHosts(
|
|
64
|
+
cms: Pick<CMS, "settings" | "forRelease">,
|
|
65
|
+
): Promise<boolean> {
|
|
66
|
+
const { hosts } = (await cms.settings()).preview;
|
|
67
|
+
if (hosts.length !== 1 || hosts[0] !== "*") return true;
|
|
68
|
+
try {
|
|
69
|
+
const [block] = await cms.forRelease().resolve<unknown>("CMS", { run: false });
|
|
70
|
+
const preview = isRecord(block) ? block.preview : undefined;
|
|
71
|
+
return isRecord(preview) && ("hosts" in preview || "__resolveType" in preview);
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
78
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const DRAFT_OFF = "off";
|
|
82
|
+
|
|
83
|
+
function draftParam(url: URL): string | null {
|
|
84
|
+
return url.searchParams.get(DRAFT_PARAM);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readCookie(header: string | null, name: string): string | null {
|
|
88
|
+
if (!header) return null;
|
|
89
|
+
for (const part of header.split(";")) {
|
|
90
|
+
const eq = part.indexOf("=");
|
|
91
|
+
if (eq === -1 || part.slice(0, eq).trim() !== name) continue;
|
|
92
|
+
try {
|
|
93
|
+
return decodeURIComponent(part.slice(eq + 1).trim());
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The pointer a request carries, as `@decocms/blocks` reads it: `?__draft=`
|
|
103
|
+
* first, then the draft cookie; `null` for `?__draft=off` and for a value
|
|
104
|
+
* that doesn't parse.
|
|
105
|
+
*/
|
|
106
|
+
export function readDraftPointer(request: Request): string | null {
|
|
107
|
+
const param = draftParam(new URL(request.url));
|
|
108
|
+
if (param === DRAFT_OFF) return null;
|
|
109
|
+
if (param && parseDraftPointer(param) !== null) return param;
|
|
110
|
+
const cookie = readCookie(request.headers.get("cookie"), DRAFT_COOKIE);
|
|
111
|
+
return cookie && parseDraftPointer(cookie) !== null ? cookie : null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function serializeCookie(value: string, extra: string[]): string {
|
|
115
|
+
// The same cookie `cms.draftCookie` writes (a test holds the two together).
|
|
116
|
+
return [
|
|
117
|
+
`${DRAFT_COOKIE}=${value}`,
|
|
118
|
+
"Path=/",
|
|
119
|
+
...extra,
|
|
120
|
+
"HttpOnly",
|
|
121
|
+
"Secure",
|
|
122
|
+
"SameSite=None",
|
|
123
|
+
"Partitioned",
|
|
124
|
+
].join("; ");
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface DraftDecision {
|
|
128
|
+
/** The draft this request renders, after the host check; `null` for the release. */
|
|
129
|
+
pointer: string | null;
|
|
130
|
+
/** The `Set-Cookie` the response carries: storing a draft link's pointer, or ending a preview. */
|
|
131
|
+
setCookie: string | null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The draft a request renders, and the cookie its response sets, under `policy`. */
|
|
135
|
+
export async function decideDraft(
|
|
136
|
+
cms: Pick<CMS, "draftPointer" | "settings" | "forRelease">,
|
|
137
|
+
request: Request,
|
|
138
|
+
policy: PreviewPolicy,
|
|
139
|
+
): Promise<DraftDecision> {
|
|
140
|
+
const url = new URL(request.url);
|
|
141
|
+
const param = draftParam(url);
|
|
142
|
+
// Ending a preview is allowed on any host, so a cookie set earlier always goes.
|
|
143
|
+
if (param === DRAFT_OFF) return { pointer: null, setCookie: serializeCookie("", ["Max-Age=0"]) };
|
|
144
|
+
const pointer = readDraftPointer(request);
|
|
145
|
+
if (pointer === null) return { pointer: null, setCookie: null };
|
|
146
|
+
const decision = previewHostDecision(url.host, policy);
|
|
147
|
+
const allowed =
|
|
148
|
+
decision === "cms"
|
|
149
|
+
? (await declaresPreviewHosts(cms)) && (await cms.draftPointer(request)) !== null
|
|
150
|
+
: decision;
|
|
151
|
+
if (!allowed) return { pointer: null, setCookie: null };
|
|
152
|
+
const fromLink = param !== null && param === pointer;
|
|
153
|
+
return {
|
|
154
|
+
pointer,
|
|
155
|
+
setCookie: fromLink ? serializeCookie(encodeURIComponent(pointer), []) : null,
|
|
156
|
+
};
|
|
157
|
+
}
|