@decocms/blocks 8.1.0-next.0 → 8.1.0-next.1
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 +6 -92
- package/src/index.ts +2 -12
- package/src/protocol/storage/memory.ts +1 -1
- package/src/v8/background.ts +3 -3
- package/src/v8/builtins/legacy.ts +1 -1
- package/src/v8/cli/index.ts +1 -1
- package/src/v8/fetch.ts +8 -27
- package/src/v8/remoteLoader.ts +1 -1
- package/src/v8/telemetry.ts +1 -1
- package/src/cms/applySectionConventions.ts +0 -148
- package/src/cms/blockSource.ts +0 -228
- package/src/cms/client.ts +0 -85
- package/src/cms/deferredTrigger.ts +0 -58
- package/src/cms/draftSource.ts +0 -476
- package/src/cms/index.ts +0 -180
- package/src/cms/loadDecofileDirectory.ts +0 -89
- package/src/cms/loader.ts +0 -563
- package/src/cms/registry.ts +0 -264
- package/src/cms/renderJson.ts +0 -179
- package/src/cms/resolve.ts +0 -2583
- package/src/cms/schema.ts +0 -1219
- package/src/cms/sectionLoaderContext.ts +0 -113
- package/src/cms/sectionLoaders.ts +0 -686
- package/src/cms/sectionMixins.ts +0 -153
- package/src/flags/audience.ts +0 -56
- package/src/flags/everyone.ts +0 -29
- package/src/flags/flag.ts +0 -15
- package/src/flags/multivariate/image.ts +0 -11
- package/src/flags/multivariate/message.ts +0 -11
- package/src/flags/multivariate/page.ts +0 -16
- package/src/flags/multivariate/section.ts +0 -16
- package/src/flags/multivariate.ts +0 -1
- package/src/flags/types.ts +0 -59
- package/src/flags/utils/multivariate.ts +0 -20
- package/src/hooks/Image.tsx +0 -314
- package/src/hooks/JsonLd.tsx +0 -353
- package/src/hooks/LazySection.tsx +0 -121
- package/src/hooks/LiveControls.tsx +0 -144
- package/src/hooks/Picture.tsx +0 -127
- package/src/hooks/RenderSection.tsx +0 -91
- package/src/hooks/SectionErrorFallback.tsx +0 -97
- package/src/hooks/Stats.tsx +0 -134
- package/src/hooks/index.ts +0 -35
- package/src/hooks/useLoadMore.ts +0 -100
- package/src/matchers/builtins.ts +0 -459
- package/src/matchers/countryNames.ts +0 -104
- package/src/matchers/override.ts +0 -136
- package/src/matchers/posthog.ts +0 -154
- package/src/middleware/decoState.ts +0 -55
- package/src/middleware/healthMetrics.ts +0 -133
- package/src/middleware/hydrationContext.ts +0 -79
- package/src/middleware/index.ts +0 -88
- package/src/middleware/liveness.ts +0 -21
- package/src/middleware/observability.ts +0 -800
- package/src/middleware/validateSection.ts +0 -100
- package/src/preview/DraftPreviewBadge.tsx +0 -306
- package/src/preview/decoMark.ts +0 -11
- package/src/preview/index.ts +0 -8
- package/src/sdk/abTesting.ts +0 -556
- package/src/sdk/analytics.ts +0 -147
- package/src/sdk/cacheHeaders.ts +0 -633
- package/src/sdk/cacheStorage.ts +0 -287
- package/src/sdk/cachedLoader.ts +0 -556
- package/src/sdk/clx.ts +0 -5
- package/src/sdk/cn.ts +0 -28
- package/src/sdk/composite.ts +0 -114
- package/src/sdk/cookie.ts +0 -129
- package/src/sdk/crypto.ts +0 -199
- package/src/sdk/csp.ts +0 -59
- package/src/sdk/deepOmit.ts +0 -52
- package/src/sdk/detectDevice.ts +0 -45
- package/src/sdk/djb2.ts +0 -20
- package/src/sdk/encoding.ts +0 -44
- package/src/sdk/env.ts +0 -54
- package/src/sdk/experiments.ts +0 -314
- package/src/sdk/fetchCache.ts +0 -269
- package/src/sdk/fetchTimeout.ts +0 -58
- package/src/sdk/flags.ts +0 -138
- package/src/sdk/http.ts +0 -124
- package/src/sdk/index.ts +0 -97
- package/src/sdk/inflightTimeout.ts +0 -53
- package/src/sdk/instrumentedFetch.ts +0 -362
- package/src/sdk/invoke.ts +0 -298
- package/src/sdk/logger.ts +0 -304
- package/src/sdk/mergeCacheControl.ts +0 -150
- package/src/sdk/nonce.ts +0 -46
- package/src/sdk/normalizeUrls.ts +0 -91
- package/src/sdk/observability.ts +0 -116
- package/src/sdk/otel.ts +0 -1118
- package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
- package/src/sdk/otelAdapters.ts +0 -144
- package/src/sdk/otelHttpLog.ts +0 -419
- package/src/sdk/otelHttpMeter.ts +0 -532
- package/src/sdk/otelHttpTracer.ts +0 -543
- package/src/sdk/redirects.ts +0 -336
- package/src/sdk/requestContext.ts +0 -281
- package/src/sdk/requestContextStorage.browser.ts +0 -43
- package/src/sdk/requestContextStorage.ts +0 -35
- package/src/sdk/responseCache.ts +0 -82
- package/src/sdk/retry.ts +0 -45
- package/src/sdk/serverTimings.ts +0 -68
- package/src/sdk/signal.ts +0 -42
- package/src/sdk/sitemap.ts +0 -160
- package/src/sdk/urlRedaction.ts +0 -82
- package/src/sdk/urlUtils.ts +0 -183
- package/src/sdk/useDevice.ts +0 -89
- package/src/sdk/useDeviceContext.tsx +0 -108
- package/src/sdk/useId.ts +0 -7
- package/src/sdk/useScript.ts +0 -210
- package/src/sdk/useSuggestions.ts +0 -188
- package/src/sdk/wrapCaughtErrors.ts +0 -107
- package/src/setup.ts +0 -120
- package/src/types/index.ts +0 -53
- package/src/types/widgets.ts +0 -14
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import * as fs from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Derive a block id (decofile map key) from a `.deco/blocks` filename.
|
|
6
|
-
*
|
|
7
|
-
* Classic deco stores each block as `encodeURIComponent(<block id>).json`
|
|
8
|
-
* and derives the id back with exactly one decodeURIComponent — this is
|
|
9
|
-
* upstream `parseBlockId` (deco-cx/deco, engine/decofile/fsFolder). Block
|
|
10
|
-
* CONTENT references saved blocks by the DECODED id (`"__resolveType":
|
|
11
|
-
* "Cores dos preços"`), and the Studio editor derives the write-back
|
|
12
|
-
* filename as `encodeURIComponent(<key>)`, so keying the map by the raw
|
|
13
|
-
* stem breaks both: references dangle at resolve time and editor saves
|
|
14
|
-
* land in a freshly-created double-encoded file.
|
|
15
|
-
*
|
|
16
|
-
* A stem that is not valid percent-encoding (e.g. a page literally named
|
|
17
|
-
* "50% off") throws in decodeURIComponent — such a stem IS the id already
|
|
18
|
-
* (classic deco would have stored it encoded), so it is kept verbatim,
|
|
19
|
-
* matching upstream behavior for pre-encoding-era files.
|
|
20
|
-
*/
|
|
21
|
-
export function parseBlockId(filename: string): string {
|
|
22
|
-
const stem = filename.endsWith(".json") ? filename.slice(0, -".json".length) : filename;
|
|
23
|
-
try {
|
|
24
|
-
return decodeURIComponent(stem);
|
|
25
|
-
} catch {
|
|
26
|
-
return stem;
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Loads a directory of legacy per-block JSON snapshot files (the format
|
|
32
|
-
* produced by the pre-v2 Deco admin, e.g. `.deco/blocks/<name>.json`) into
|
|
33
|
-
* a single blocks map suitable for setBlocks(). Each file becomes one
|
|
34
|
-
* entry keyed by `parseBlockId(<filename>)` — the filename stem URL-decoded
|
|
35
|
-
* once, matching the classic deco runtime's key convention.
|
|
36
|
-
*
|
|
37
|
-
* Beyond that single decode the key is not renamed or normalized: whatever
|
|
38
|
-
* prefix convention a block's filename already carries (e.g. real page
|
|
39
|
-
* block snapshots are named `pages-<slug>-<id>.json`) is preserved, because
|
|
40
|
-
* getAllPages() in loader.ts filters blocks by `key.startsWith("pages-")`
|
|
41
|
-
* before findPageByPath() matches on each page's own `.path` field. So the
|
|
42
|
-
* key format IS load-bearing for page blocks — decoding never touches the
|
|
43
|
-
* `pages-` prefix itself, only the percent-escapes after it.
|
|
44
|
-
*
|
|
45
|
-
* Two filenames can decode to the same id (`A B.json` + `A%20B.json`).
|
|
46
|
-
* Files are processed in sorted filename order and the last one wins, so
|
|
47
|
-
* the outcome is deterministic; a console.warn names the shadowed file.
|
|
48
|
-
*
|
|
49
|
-
* Replaces the abandoned @decocms/start/node tier's loadAllDecofileBlocks,
|
|
50
|
-
* which no longer exists on any reachable blocks version — ported
|
|
51
|
-
* fresh rather than resurrected. Namespace-imported node:fs/promises to
|
|
52
|
-
* match this codebase's existing pattern for Node-only code that must not
|
|
53
|
-
* break Vite/webpack client bundle analysis (see cms/loader.ts's
|
|
54
|
-
* AsyncLocalStorage import for the established precedent).
|
|
55
|
-
*/
|
|
56
|
-
export async function loadDecofileDirectory(dir: string): Promise<Record<string, unknown>> {
|
|
57
|
-
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
58
|
-
const blocks: Record<string, unknown> = {};
|
|
59
|
-
|
|
60
|
-
const files = entries
|
|
61
|
-
.filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
|
|
62
|
-
.map((entry) => entry.name)
|
|
63
|
-
.sort();
|
|
64
|
-
|
|
65
|
-
const parsed = await Promise.all(
|
|
66
|
-
files.map(async (name) => {
|
|
67
|
-
const content = await fs.readFile(join(dir, name), "utf8");
|
|
68
|
-
try {
|
|
69
|
-
return { name, value: JSON.parse(content) as unknown };
|
|
70
|
-
} catch (error) {
|
|
71
|
-
throw new Error(
|
|
72
|
-
`loadDecofileDirectory: failed to parse ${name}: ${(error as Error).message}`,
|
|
73
|
-
);
|
|
74
|
-
}
|
|
75
|
-
}),
|
|
76
|
-
);
|
|
77
|
-
|
|
78
|
-
for (const { name, value } of parsed) {
|
|
79
|
-
const key = parseBlockId(name);
|
|
80
|
-
if (key in blocks) {
|
|
81
|
-
console.warn(
|
|
82
|
-
`loadDecofileDirectory: block id ${JSON.stringify(key)} maps to multiple files; ${JSON.stringify(name)} wins`,
|
|
83
|
-
);
|
|
84
|
-
}
|
|
85
|
-
blocks[key] = value;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
return blocks;
|
|
89
|
-
}
|
package/src/cms/loader.ts
DELETED
|
@@ -1,563 +0,0 @@
|
|
|
1
|
-
import * as asyncHooks from "node:async_hooks";
|
|
2
|
-
import { djb2Hex } from "../sdk/djb2";
|
|
3
|
-
import { getRequestDraftOverride } from "./draftSource";
|
|
4
|
-
|
|
5
|
-
export type Resolvable = {
|
|
6
|
-
__resolveType?: string;
|
|
7
|
-
[key: string]: unknown;
|
|
8
|
-
};
|
|
9
|
-
|
|
10
|
-
export type DecoPage = {
|
|
11
|
-
name: string;
|
|
12
|
-
path?: string;
|
|
13
|
-
sections: Resolvable[] | Resolvable;
|
|
14
|
-
seo?: Record<string, unknown>;
|
|
15
|
-
};
|
|
16
|
-
|
|
17
|
-
// globalThis-backed storage: TanStack Start server function split modules
|
|
18
|
-
// may get isolated module instances. globalThis ensures shared state.
|
|
19
|
-
const G = globalThis as any;
|
|
20
|
-
if (!G.__deco) G.__deco = {};
|
|
21
|
-
|
|
22
|
-
let blockData: Record<string, unknown> = G.__deco.blockData ?? {};
|
|
23
|
-
let revision: string | null = G.__deco.revision ?? null;
|
|
24
|
-
|
|
25
|
-
interface ALSLike<T> {
|
|
26
|
-
getStore(): T | undefined;
|
|
27
|
-
run<R>(store: T, fn: () => R): R;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// AsyncLocalStorage might not be available in client builds (Vite replaces
|
|
31
|
-
// node:async_hooks with an empty shim). The namespace import avoids Rollup's
|
|
32
|
-
// named-export validation, and the runtime check prevents construction errors.
|
|
33
|
-
const ALS = (asyncHooks as any).AsyncLocalStorage;
|
|
34
|
-
|
|
35
|
-
/**
|
|
36
|
-
* A scoped blocks override, tagged with how it composes over the base:
|
|
37
|
-
* - `merge`: a PARTIAL decofile (admin preview payloads) — entries replace or
|
|
38
|
-
* delete their base twins, everything else survives (see mergeOverride).
|
|
39
|
-
* - `snapshot`: a COMPLETE decofile (draft preview) — it replaces the
|
|
40
|
-
* file-backed base entirely; only synthetic base blocks survive (see
|
|
41
|
-
* applyDraftSnapshot).
|
|
42
|
-
*/
|
|
43
|
-
interface BlocksOverride {
|
|
44
|
-
mode: "merge" | "snapshot";
|
|
45
|
-
blocks: Record<string, unknown>;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const blocksOverrideStorage: ALSLike<BlocksOverride> = ALS
|
|
49
|
-
? new ALS()
|
|
50
|
-
: { getStore: () => undefined, run: (_s: any, fn: any) => fn() };
|
|
51
|
-
|
|
52
|
-
// ---------------------------------------------------------------------------
|
|
53
|
-
// Change listeners
|
|
54
|
-
// ---------------------------------------------------------------------------
|
|
55
|
-
|
|
56
|
-
type ChangeListener = (
|
|
57
|
-
blocks: Record<string, unknown>,
|
|
58
|
-
revision: string,
|
|
59
|
-
) => void;
|
|
60
|
-
const changeListeners: ChangeListener[] = [];
|
|
61
|
-
|
|
62
|
-
/** Register a callback invoked whenever setBlocks() changes the decofile. */
|
|
63
|
-
export function onChange(listener: ChangeListener) {
|
|
64
|
-
changeListeners.push(listener);
|
|
65
|
-
return () => {
|
|
66
|
-
const idx = changeListeners.indexOf(listener);
|
|
67
|
-
if (idx >= 0) changeListeners.splice(idx, 1);
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// ---------------------------------------------------------------------------
|
|
72
|
-
// Revision hashing
|
|
73
|
-
// ---------------------------------------------------------------------------
|
|
74
|
-
|
|
75
|
-
function computeRevision(blocks: Record<string, unknown>): string {
|
|
76
|
-
return djb2Hex(JSON.stringify(blocks));
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
// ---------------------------------------------------------------------------
|
|
80
|
-
// Block management
|
|
81
|
-
// ---------------------------------------------------------------------------
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Set the blocks data. Called at startup with generated blocks,
|
|
85
|
-
* and by the admin on hot-reload.
|
|
86
|
-
* Notifies all onChange listeners and updates the revision.
|
|
87
|
-
*/
|
|
88
|
-
export function setBlocks(blocks: Record<string, unknown>) {
|
|
89
|
-
// A caller may hand back the same object after mutating it in place.
|
|
90
|
-
pageIndexCache.delete(blocks);
|
|
91
|
-
blockData = blocks;
|
|
92
|
-
revision = computeRevision(blocks);
|
|
93
|
-
|
|
94
|
-
// Persist to globalThis so other module instances see them
|
|
95
|
-
G.__deco.blockData = blockData;
|
|
96
|
-
G.__deco.revision = revision;
|
|
97
|
-
|
|
98
|
-
for (const listener of [...changeListeners]) {
|
|
99
|
-
try {
|
|
100
|
-
listener(blocks, revision);
|
|
101
|
-
} catch (e) {
|
|
102
|
-
console.error("[CMS] onChange listener error:", e);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Canonicalise a block key so an override block matches its base twin even when
|
|
109
|
-
* the two decofiles disagree on percent-encoding of the key.
|
|
110
|
-
*
|
|
111
|
-
* The site's published decofile encodes special characters in block keys
|
|
112
|
-
* (`pages-Home%20(principal)-287364`); the Studio draft-preview sandbox emits
|
|
113
|
-
* them raw (`pages-Home (principal)-287364`). Decoding collapses both spellings
|
|
114
|
-
* to the same canonical form. Defensive: a malformed `%` sequence makes
|
|
115
|
-
* `decodeURIComponent` throw, so fall back to the raw key rather than 500 the
|
|
116
|
-
* merge.
|
|
117
|
-
*/
|
|
118
|
-
function canonicalBlockKey(key: string): string {
|
|
119
|
-
try {
|
|
120
|
-
return decodeURIComponent(key);
|
|
121
|
-
} catch {
|
|
122
|
-
return key;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/**
|
|
127
|
-
* Merge an override decofile on top of the base blocks.
|
|
128
|
-
*
|
|
129
|
-
* An override entry REPLACES the base block of the same logical key — including
|
|
130
|
-
* a base twin spelled with different percent-encoding. A naive key-merge would
|
|
131
|
-
* instead ADD the differently-encoded override block, leaving two `pages-`
|
|
132
|
-
* blocks with the same `.path`; `findPageByPath` returns the first (base) one,
|
|
133
|
-
* so a draft-preview edit would silently never render. Canonicalising the base
|
|
134
|
-
* keys lets the override find and displace its twin.
|
|
135
|
-
*
|
|
136
|
-
* A `null`/`undefined` override value deletes the block (its twin too), so a
|
|
137
|
-
* draft that removes a block is honoured.
|
|
138
|
-
*/
|
|
139
|
-
function mergeOverride(
|
|
140
|
-
base: Record<string, unknown>,
|
|
141
|
-
override: Record<string, unknown>,
|
|
142
|
-
): Record<string, unknown> {
|
|
143
|
-
const merged = { ...base };
|
|
144
|
-
const baseByCanonical = new Map<string, string>();
|
|
145
|
-
for (const baseKey of Object.keys(merged)) {
|
|
146
|
-
baseByCanonical.set(canonicalBlockKey(baseKey), baseKey);
|
|
147
|
-
}
|
|
148
|
-
for (const [key, value] of Object.entries(override)) {
|
|
149
|
-
const twin = baseByCanonical.get(canonicalBlockKey(key));
|
|
150
|
-
if (twin !== undefined && twin !== key) delete merged[twin];
|
|
151
|
-
if (value === null || value === undefined) {
|
|
152
|
-
delete merged[key];
|
|
153
|
-
} else {
|
|
154
|
-
merged[key] = value;
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
return merged;
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
/**
|
|
161
|
-
* Base blocks that are NOT file-backed: synthesized by the generator (CSV
|
|
162
|
-
* redirect loaders, keyed `__csv_redirects__<file>`). A draft snapshot is the
|
|
163
|
-
* complete truth of `.deco/blocks/` but knows nothing about these, so they
|
|
164
|
-
* survive the snapshot instead of vanishing from the preview.
|
|
165
|
-
*/
|
|
166
|
-
const SYNTHETIC_BLOCK_KEY_PREFIX = "__csv_redirects__";
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Compose a draft SNAPSHOT over the base blocks: the draft is the complete
|
|
170
|
-
* decofile at the branch head, so it REPLACES every file-backed base block —
|
|
171
|
-
* a block absent from the draft was deleted and must not render. Only
|
|
172
|
-
* synthetic base blocks (see SYNTHETIC_BLOCK_KEY_PREFIX) survive. `null`
|
|
173
|
-
* draft values are tolerated as deletions for defensiveness.
|
|
174
|
-
*/
|
|
175
|
-
function applyDraftSnapshot(
|
|
176
|
-
base: Record<string, unknown>,
|
|
177
|
-
draft: Record<string, unknown>,
|
|
178
|
-
): Record<string, unknown> {
|
|
179
|
-
const out: Record<string, unknown> = {};
|
|
180
|
-
for (const [key, value] of Object.entries(base)) {
|
|
181
|
-
if (key.startsWith(SYNTHETIC_BLOCK_KEY_PREFIX)) out[key] = value;
|
|
182
|
-
}
|
|
183
|
-
for (const [key, value] of Object.entries(draft)) {
|
|
184
|
-
if (value === null || value === undefined) continue;
|
|
185
|
-
out[key] = value;
|
|
186
|
-
}
|
|
187
|
-
return out;
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Load the current blocks. If running inside a `withBlocksOverride` /
|
|
192
|
-
* `withDraftBlocks` scope (admin preview / draft endpoints) or a request
|
|
193
|
-
* carrying an ambient draft, that override composes over the base blocks
|
|
194
|
-
* according to its mode.
|
|
195
|
-
*/
|
|
196
|
-
export function loadBlocks(): Record<string, unknown> {
|
|
197
|
-
// Re-sync from globalThis in case setBlocks was called in another module instance
|
|
198
|
-
if (G.__deco.blockData && G.__deco.blockData !== blockData) {
|
|
199
|
-
blockData = G.__deco.blockData;
|
|
200
|
-
revision = G.__deco.revision ?? null;
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// An explicit scope (the caller named the exact blocks to render) wins over
|
|
204
|
-
// an ambient draft: a draft pointer on the same request must not silently
|
|
205
|
-
// replace it.
|
|
206
|
-
const scoped = blocksOverrideStorage.getStore();
|
|
207
|
-
if (scoped) {
|
|
208
|
-
return scoped.mode === "merge"
|
|
209
|
-
? mergeOverride(blockData, scoped.blocks)
|
|
210
|
-
: applyDraftSnapshot(blockData, scoped.blocks);
|
|
211
|
-
}
|
|
212
|
-
const draft = getRequestDraftOverride();
|
|
213
|
-
if (draft) return applyDraftSnapshot(blockData, draft);
|
|
214
|
-
return blockData;
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/** Get the current decofile revision hash. Changes on each setBlocks(). */
|
|
218
|
-
export function getRevision(): string | null {
|
|
219
|
-
return revision;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* Run a function with a temporary blocks overlay.
|
|
224
|
-
*
|
|
225
|
-
* Used by admin preview: the admin sends a partial decofile (only the
|
|
226
|
-
* blocks that changed), and `loadBlocks()` returns the merged result
|
|
227
|
-
* for the duration of the render. Other concurrent requests are not
|
|
228
|
-
* affected (AsyncLocalStorage is per-request scoped).
|
|
229
|
-
*/
|
|
230
|
-
export function withBlocksOverride<T>(
|
|
231
|
-
override: Record<string, unknown>,
|
|
232
|
-
fn: () => T,
|
|
233
|
-
): T {
|
|
234
|
-
return blocksOverrideStorage.run({ mode: "merge", blocks: override }, fn);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/**
|
|
238
|
-
* Run a function with a COMPLETE draft decofile (snapshot semantics — see
|
|
239
|
-
* applyDraftSnapshot). Used by secondary endpoints (`/deco/invoke`) that
|
|
240
|
-
* re-resolve the page's draft from the raw request: the draft must compose
|
|
241
|
-
* exactly like the page render, deletions included, or a lazy section could
|
|
242
|
-
* render a block the page no longer has.
|
|
243
|
-
*/
|
|
244
|
-
export function withDraftBlocks<T>(
|
|
245
|
-
draft: Record<string, unknown>,
|
|
246
|
-
fn: () => T,
|
|
247
|
-
): T {
|
|
248
|
-
return blocksOverrideStorage.run({ mode: "snapshot", blocks: draft }, fn);
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Higher key wins. Compared lexicographically:
|
|
252
|
-
// [hasNoWildcard, literalSegments, paramSegments]
|
|
253
|
-
//
|
|
254
|
-
// `hasNoWildcard` is the top key so a literal-only path always beats any
|
|
255
|
-
// pattern that contains `*` or `{group}?` — including the empty-parts case
|
|
256
|
-
// `/` (literals=0) vs the catch-all `/{prefix/}?*` (literals=0, params=1).
|
|
257
|
-
// Without this, the URLPattern fix (#213/#214) inadvertently lets a
|
|
258
|
-
// `/{group/}?*` catch-all out-rank an exact `/` home page because the
|
|
259
|
-
// `{group` segment counted as a param. See a production storefront
|
|
260
|
-
// where `/` was being routed to a brand-prefixed PDP/PLP block's NotFound
|
|
261
|
-
// fallback.
|
|
262
|
-
//
|
|
263
|
-
// Order produced:
|
|
264
|
-
// /foo/bar (no wildcard, literals=2) > /foo/:x (no wildcard, lit=1, param=1)
|
|
265
|
-
// /foo (no wildcard) > /{acme/}?* (has wildcard) > /*
|
|
266
|
-
function pathSpecificityKey(path: string): [number, number, number] {
|
|
267
|
-
const parts = path.split("/").filter(Boolean);
|
|
268
|
-
let literals = 0;
|
|
269
|
-
let params = 0;
|
|
270
|
-
let hasWildcard = false;
|
|
271
|
-
for (const part of parts) {
|
|
272
|
-
// A wildcard is any `*`, optional group `{...}?`, or any segment
|
|
273
|
-
// bearing `?` — these all make the pattern match strictly more URLs
|
|
274
|
-
// than a plain literal/`:param`/`:slug([\w-]+)` segment, so they
|
|
275
|
-
// are demoted to "least specific" together regardless of count.
|
|
276
|
-
if (part.includes("*") || /[{}?]/.test(part)) {
|
|
277
|
-
hasWildcard = true;
|
|
278
|
-
} else if (part.startsWith(":") || part.startsWith("$")) {
|
|
279
|
-
params++;
|
|
280
|
-
} else {
|
|
281
|
-
literals++;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return [hasWildcard ? 0 : 1, literals, params];
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
// Literal rather than WELL_KNOWN_TYPES.PAGE: resolve.ts already imports from
|
|
288
|
-
// this module, so importing back would close a cycle.
|
|
289
|
-
const PAGE_RESOLVE_TYPE = "website/pages/Page.tsx";
|
|
290
|
-
|
|
291
|
-
/**
|
|
292
|
-
* Is this block a page?
|
|
293
|
-
*
|
|
294
|
-
* The `pages-` prefix is kept as a fast path because it is what the admin
|
|
295
|
-
* emits and it short-circuits the vast majority of blocks without a property
|
|
296
|
-
* read. But it cannot be the *only* test: a decofile carried over from Deco on
|
|
297
|
-
* Fresh can hold page blocks under any key — renaming one in the CMS renames
|
|
298
|
-
* its snapshot file, and `loadDecofileDirectory` preserves whatever key the
|
|
299
|
-
* filename already had.
|
|
300
|
-
*
|
|
301
|
-
* Those blocks are pages in every way that matters (`website/pages/Page.tsx`,
|
|
302
|
-
* a `path`, `sections`), and on Fresh they routed fine: `website/loaders/pages.ts`
|
|
303
|
-
* enumerated by `__resolveType`, not by key. Filtering on the prefix alone makes
|
|
304
|
-
* them invisible, so every one of their URLs falls through to whatever catch-all
|
|
305
|
-
* the site has — usually a 404 — and they disappear from the CMS sitemap too.
|
|
306
|
-
* One storefront in this state has 205 such blocks against 107 prefixed ones.
|
|
307
|
-
*/
|
|
308
|
-
function isPageBlock(key: string, block: unknown): boolean {
|
|
309
|
-
if (key.startsWith("pages-")) return true;
|
|
310
|
-
return (
|
|
311
|
-
typeof block === "object" &&
|
|
312
|
-
block !== null &&
|
|
313
|
-
(block as Resolvable).__resolveType === PAGE_RESOLVE_TYPE
|
|
314
|
-
);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
type PageIndexEntry = {
|
|
318
|
-
key: string;
|
|
319
|
-
page: DecoPage;
|
|
320
|
-
path: string;
|
|
321
|
-
/** `path` has no URLPattern syntax, so it only matches its own spelling. */
|
|
322
|
-
literal: boolean;
|
|
323
|
-
/** Compiled on first use; `null` when the pattern is malformed. */
|
|
324
|
-
matcher?: CompiledPattern | null;
|
|
325
|
-
};
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* Page list per blocks object, ranked by path specificity.
|
|
329
|
-
*
|
|
330
|
-
* `findPageByPath` runs on every CMS resolve — twice per request on a site
|
|
331
|
-
* that retries a lowercase path, and once more per template it resolves — and
|
|
332
|
-
* a request that ends on no CMS page (a catalog PLP/PDP, a search, a 404) walks
|
|
333
|
-
* the whole list. Rebuilding and sorting the list and compiling a URLPattern
|
|
334
|
-
* per page on each call made that walk the hottest frame of an uncached render
|
|
335
|
-
* on a 1.2k-page decofile. Keyed by the blocks object: `setBlocks()` and every
|
|
336
|
-
* draft/override composition produce a new one, so a published change can
|
|
337
|
-
* never be served from a stale index. Kept on `globalThis`, like the blocks
|
|
338
|
-
* themselves, so every module instance drops the same entry on `setBlocks()`.
|
|
339
|
-
* The compiled matchers live on the entries and go away with them.
|
|
340
|
-
*/
|
|
341
|
-
const pageIndexCache: WeakMap<Record<string, unknown>, PageIndexEntry[]> =
|
|
342
|
-
G.__deco.pageIndexCache ?? (G.__deco.pageIndexCache = new WeakMap());
|
|
343
|
-
|
|
344
|
-
function buildPageIndex(blocks: Record<string, unknown>): PageIndexEntry[] {
|
|
345
|
-
const pages: Array<PageIndexEntry & { key2: [number, number, number] }> = [];
|
|
346
|
-
|
|
347
|
-
for (const [key, block] of Object.entries(blocks)) {
|
|
348
|
-
if (!isPageBlock(key, block)) continue;
|
|
349
|
-
const page = block as DecoPage;
|
|
350
|
-
if (!page.sections) continue;
|
|
351
|
-
if (!page.path) continue;
|
|
352
|
-
|
|
353
|
-
pages.push({
|
|
354
|
-
key,
|
|
355
|
-
page,
|
|
356
|
-
path: page.path,
|
|
357
|
-
literal: isPlainPath(page.path),
|
|
358
|
-
key2: pathSpecificityKey(page.path),
|
|
359
|
-
});
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
return pages
|
|
363
|
-
.sort((a, b) => {
|
|
364
|
-
for (let i = 0; i < a.key2.length; i++) {
|
|
365
|
-
if (a.key2[i] !== b.key2[i]) return b.key2[i] - a.key2[i];
|
|
366
|
-
}
|
|
367
|
-
return 0;
|
|
368
|
-
})
|
|
369
|
-
.map(({ key, page, path, literal }) => ({ key, page, path, literal }));
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
function getPageIndex(): PageIndexEntry[] {
|
|
373
|
-
const blocks = loadBlocks();
|
|
374
|
-
let index = pageIndexCache.get(blocks);
|
|
375
|
-
if (!index) {
|
|
376
|
-
index = buildPageIndex(blocks);
|
|
377
|
-
pageIndexCache.set(blocks, index);
|
|
378
|
-
}
|
|
379
|
-
return index;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
export function getAllPages(): Array<{ key: string; page: DecoPage }> {
|
|
383
|
-
return getPageIndex().map(({ key, page }) => ({ key, page }));
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
// Module-scoped (NOT `declare global`) ambient declaration for the
|
|
387
|
-
// `URLPattern` Web API. It's natively available at runtime in browsers,
|
|
388
|
-
// Cloudflare Workers, Deno, and Node 24+, but its type declarations aren't
|
|
389
|
-
// consistently present: TypeScript's bundled lib.dom.d.ts doesn't ship it
|
|
390
|
-
// yet, and @types/node only started shipping a global augmentation for it
|
|
391
|
-
// in newer major versions (via `node/web-globals/url.d.ts`).
|
|
392
|
-
//
|
|
393
|
-
// A `declare global` shim here would merge with @types/node's own global
|
|
394
|
-
// `URLPattern`/`URLPatternResult` augmentation whenever a new-enough
|
|
395
|
-
// @types/node wins the workspace's package hoist — and merging two
|
|
396
|
-
// independently-authored global interfaces under the same name throws
|
|
397
|
-
// TS2430 ("incorrectly extends") the moment their shapes don't line up
|
|
398
|
-
// structurally. Declaring `URLPattern` and its result shape as file-local
|
|
399
|
-
// bindings instead (no `declare global`) means this file typechecks the
|
|
400
|
-
// same regardless of whether @types/node has its own `URLPattern` global or
|
|
401
|
-
// not — there's nothing for a local declaration to collide with.
|
|
402
|
-
type MatchPatternResult = {
|
|
403
|
-
pathname: { groups: Record<string, string | undefined> };
|
|
404
|
-
};
|
|
405
|
-
declare const URLPattern: {
|
|
406
|
-
new (init: {
|
|
407
|
-
pathname: string;
|
|
408
|
-
}): {
|
|
409
|
-
exec(input: { pathname: string }): MatchPatternResult | null;
|
|
410
|
-
};
|
|
411
|
-
};
|
|
412
|
-
|
|
413
|
-
type CompiledPattern = {
|
|
414
|
-
exec(input: { pathname: string }): MatchPatternResult | null;
|
|
415
|
-
};
|
|
416
|
-
|
|
417
|
-
function compilePattern(pattern: string): CompiledPattern | null {
|
|
418
|
-
try {
|
|
419
|
-
return new URLPattern({ pathname: pattern });
|
|
420
|
-
} catch {
|
|
421
|
-
return null;
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
/**
|
|
426
|
-
* Compiled patterns for direct `matchPath()` callers, bounded: unlike the page
|
|
427
|
-
* index, its patterns can come from anywhere. Oldest entry evicted first.
|
|
428
|
-
*/
|
|
429
|
-
const MATCH_PATH_CACHE_MAX = 256;
|
|
430
|
-
const matchPathCache = new Map<string, CompiledPattern | null>();
|
|
431
|
-
|
|
432
|
-
function cachedPattern(pattern: string): CompiledPattern | null {
|
|
433
|
-
const hit = matchPathCache.get(pattern);
|
|
434
|
-
if (hit !== undefined) return hit;
|
|
435
|
-
const compiled = compilePattern(pattern);
|
|
436
|
-
if (matchPathCache.size >= MATCH_PATH_CACHE_MAX) {
|
|
437
|
-
matchPathCache.delete(matchPathCache.keys().next().value as string);
|
|
438
|
-
}
|
|
439
|
-
matchPathCache.set(pattern, compiled);
|
|
440
|
-
return compiled;
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
function execPattern(
|
|
444
|
-
compiled: CompiledPattern | null,
|
|
445
|
-
urlPath: string,
|
|
446
|
-
): Record<string, string> | null {
|
|
447
|
-
if (!compiled) return null;
|
|
448
|
-
let result: MatchPatternResult | null;
|
|
449
|
-
try {
|
|
450
|
-
result = compiled.exec({ pathname: urlPath });
|
|
451
|
-
} catch {
|
|
452
|
-
return null;
|
|
453
|
-
}
|
|
454
|
-
if (!result) return null;
|
|
455
|
-
|
|
456
|
-
const groups = result.pathname.groups as Record<string, string | undefined>;
|
|
457
|
-
const out: Record<string, string> = {};
|
|
458
|
-
for (const [k, v] of Object.entries(groups)) {
|
|
459
|
-
if (v !== undefined) out[k] = v;
|
|
460
|
-
}
|
|
461
|
-
return out;
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
/**
|
|
465
|
-
* Characters that are literal both in URLPattern syntax and in URL path
|
|
466
|
-
* canonicalization. A pattern made only of them matches exactly its own
|
|
467
|
-
* spelling, and an input made only of them is already canonical — so for that
|
|
468
|
-
* pair a string comparison gives the same answer as `URLPattern.exec`. Anything
|
|
469
|
-
* else (`:param`, groups, `*`, `%`-escapes, non-ASCII, dot segments) takes the
|
|
470
|
-
* URLPattern path.
|
|
471
|
-
*/
|
|
472
|
-
const PLAIN_PATH = /^[A-Za-z0-9\-._~/]*$/;
|
|
473
|
-
const DOT_SEGMENT = /(^|\/)\.{1,2}(\/|$)/;
|
|
474
|
-
|
|
475
|
-
function isPlainPath(path: string): boolean {
|
|
476
|
-
return PLAIN_PATH.test(path) && !DOT_SEGMENT.test(path);
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
function assertURLPattern() {
|
|
480
|
-
if (typeof URLPattern === "undefined") {
|
|
481
|
-
throw new Error(
|
|
482
|
-
"@decocms/blocks: this runtime has no URLPattern Web API, so CMS page " +
|
|
483
|
-
"paths cannot be matched. URLPattern is native in browsers, " +
|
|
484
|
-
"Cloudflare workerd, Deno, and Node.js >= 24 — you are most likely " +
|
|
485
|
-
"running Node <= 22. Upgrade the runtime to Node 24+ (see this " +
|
|
486
|
-
'package\'s "engines" field).',
|
|
487
|
-
);
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* Match a CMS page path pattern against a URL path.
|
|
493
|
-
*
|
|
494
|
-
* Mirrors the original deco-cx/deco Fresh framework
|
|
495
|
-
* (`runtime/features/render.tsx`) by delegating to the platform's native
|
|
496
|
-
* `URLPattern`. Supports the full URLPattern syntax that the admin emits:
|
|
497
|
-
* `:slug`, `:slug([\w-]+)`, optional groups `{...}?`, and trailing `*`
|
|
498
|
-
* splats. Splats are exposed as the standard numbered groups (`"0"`, `"1"`,
|
|
499
|
-
* …), matching the Fresh shape.
|
|
500
|
-
*
|
|
501
|
-
* Malformed patterns return `null` instead of throwing — bad CMS data must
|
|
502
|
-
* never take down the worker.
|
|
503
|
-
*
|
|
504
|
-
* A MISSING `URLPattern` API, however, throws loudly and immediately: the
|
|
505
|
-
* try/catch below exists to absorb bad *patterns*, and letting it also
|
|
506
|
-
* swallow a `ReferenceError` from an old runtime turns "wrong Node version"
|
|
507
|
-
* into "every CMS page silently 404s" — the worst possible failure mode.
|
|
508
|
-
* `URLPattern` is native in browsers, workerd, Deno, and Node >= 24 (this
|
|
509
|
-
* package's `engines` floor). Node 22 and older lack it.
|
|
510
|
-
*/
|
|
511
|
-
export function matchPath(
|
|
512
|
-
pattern: string,
|
|
513
|
-
urlPath: string,
|
|
514
|
-
): Record<string, string> | null {
|
|
515
|
-
assertURLPattern();
|
|
516
|
-
return execPattern(cachedPattern(pattern), urlPath);
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
/**
|
|
520
|
-
* Extract the site-wide SEO config from the "Site" app block.
|
|
521
|
-
*
|
|
522
|
-
* In the original deco-cx/deco framework this is `ctx.seo` — the app-level
|
|
523
|
-
* SEO configuration that provides fallback title, description, and templates
|
|
524
|
-
* when page-level seo blocks don't supply them.
|
|
525
|
-
*/
|
|
526
|
-
export function getSiteSeo(): {
|
|
527
|
-
title?: string;
|
|
528
|
-
description?: string;
|
|
529
|
-
titleTemplate?: string;
|
|
530
|
-
descriptionTemplate?: string;
|
|
531
|
-
image?: string;
|
|
532
|
-
favicon?: string;
|
|
533
|
-
themeColor?: string;
|
|
534
|
-
noIndexing?: boolean;
|
|
535
|
-
} {
|
|
536
|
-
const blocks = loadBlocks();
|
|
537
|
-
const site = (blocks["Site"] ?? blocks["site"]) as Record<string, unknown> | undefined;
|
|
538
|
-
if (!site) return {};
|
|
539
|
-
const seo = site.seo as Record<string, unknown> | undefined;
|
|
540
|
-
if (!seo) return {};
|
|
541
|
-
return seo as ReturnType<typeof getSiteSeo>;
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
export function findPageByPath(
|
|
545
|
-
targetPath: string,
|
|
546
|
-
): { page: DecoPage; params: Record<string, string>; blockKey: string } | null {
|
|
547
|
-
// Same loud failure as matchPath, even when every page is literal.
|
|
548
|
-
assertURLPattern();
|
|
549
|
-
const plainTarget = isPlainPath(targetPath);
|
|
550
|
-
|
|
551
|
-
for (const entry of getPageIndex()) {
|
|
552
|
-
const { key, page, path, literal } = entry;
|
|
553
|
-
if (literal && plainTarget) {
|
|
554
|
-
if (path === targetPath) return { page, params: {}, blockKey: key };
|
|
555
|
-
continue;
|
|
556
|
-
}
|
|
557
|
-
if (entry.matcher === undefined) entry.matcher = compilePattern(path);
|
|
558
|
-
const params = execPattern(entry.matcher, targetPath);
|
|
559
|
-
if (params !== null) return { page, params, blockKey: key };
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
return null;
|
|
563
|
-
}
|