@decocms/blocks 7.72.0 → 8.0.0-next.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/bin/deco.js +13 -0
- package/package.json +32 -3
- package/src/cms/schema.ts +1 -1
- package/src/hooks/LiveControls.tsx +2 -0
- package/src/hooks/useLoadMore.ts +2 -0
- package/src/index.ts +37 -0
- package/src/protocol/assets.ts +124 -0
- package/src/protocol/canonical.ts +7 -0
- package/src/protocol/ciphertext.ts +6 -0
- package/src/protocol/client.ts +170 -0
- package/src/protocol/conformance/cases/assets.ts +81 -0
- package/src/protocol/conformance/cases/guards.ts +314 -0
- package/src/protocol/conformance/cases/reads.ts +168 -0
- package/src/protocol/conformance/cases/types.ts +9 -0
- package/src/protocol/conformance/cases/wire.ts +138 -0
- package/src/protocol/conformance/cases/writes.ts +345 -0
- package/src/protocol/conformance/contentHashFixtures.ts +79 -0
- package/src/protocol/conformance/context.ts +222 -0
- package/src/protocol/conformance/index.ts +140 -0
- package/src/protocol/errors.ts +142 -0
- package/src/protocol/index.ts +39 -0
- package/src/protocol/keys.ts +279 -0
- package/src/protocol/params.ts +67 -0
- package/src/protocol/secrets.ts +231 -0
- package/src/protocol/server/assets.ts +119 -0
- package/src/protocol/server/auth.ts +49 -0
- package/src/protocol/server/bodyCache.ts +84 -0
- package/src/protocol/server/content.ts +175 -0
- package/src/protocol/server/core.ts +112 -0
- package/src/protocol/server/handler.ts +102 -0
- package/src/protocol/server/http.ts +139 -0
- package/src/protocol/server/index.ts +11 -0
- package/src/protocol/server/methods/apply.ts +341 -0
- package/src/protocol/server/methods/read.ts +156 -0
- package/src/protocol/server/rpc.ts +136 -0
- package/src/protocol/storage/fs/hash.ts +21 -0
- package/src/protocol/storage/fs/index.ts +338 -0
- package/src/protocol/storage/fs/lock.ts +68 -0
- package/src/protocol/storage/fs/transaction.ts +183 -0
- package/src/protocol/storage/fs/unsupported.ts +15 -0
- package/src/protocol/storage/memory.ts +238 -0
- package/src/protocol/storage.ts +182 -0
- package/src/protocol/types.ts +172 -0
- package/src/v8/analytics.ts +50 -0
- package/src/v8/background.ts +107 -0
- package/src/v8/builtins/data.ts +23 -0
- package/src/v8/builtins/index.ts +26 -0
- package/src/v8/builtins/lazy.ts +23 -0
- package/src/v8/builtins/legacy.ts +65 -0
- package/src/v8/builtins/matchers.ts +31 -0
- package/src/v8/builtins/multivariate.ts +25 -0
- package/src/v8/builtins/secret.ts +82 -0
- package/src/v8/canonical.ts +117 -0
- package/src/v8/ciphertext.ts +158 -0
- package/src/v8/cli/builtins.ts +20 -0
- package/src/v8/cli/check/index.ts +774 -0
- package/src/v8/cli/check/messages.ts +168 -0
- package/src/v8/cli/content.ts +287 -0
- package/src/v8/cli/index.ts +17 -0
- package/src/v8/cli/log.ts +18 -0
- package/src/v8/cli/main.ts +12 -0
- package/src/v8/cli/root.ts +66 -0
- package/src/v8/cli/run.ts +236 -0
- package/src/v8/cli/schema/builtinSchemas.ts +236 -0
- package/src/v8/cli/schema/generate.ts +507 -0
- package/src/v8/cli/schema/index.ts +63 -0
- package/src/v8/cli/schema/tsProgram.ts +497 -0
- package/src/v8/cli/schema/typeToSchema.ts +689 -0
- package/src/v8/cli/serve/server.ts +303 -0
- package/src/v8/cli/watch.ts +86 -0
- package/src/v8/client.ts +147 -0
- package/src/v8/cms.ts +237 -0
- package/src/v8/content.ts +195 -0
- package/src/v8/draft.ts +136 -0
- package/src/v8/errors.ts +59 -0
- package/src/v8/fetch.ts +152 -0
- package/src/v8/identity.ts +65 -0
- package/src/v8/index.ts +39 -0
- package/src/v8/json.ts +74 -0
- package/src/v8/matchRoute.ts +204 -0
- package/src/v8/remoteLoader.ts +282 -0
- package/src/v8/resolver.ts +278 -0
- package/src/v8/secrets.ts +17 -0
- package/src/v8/telemetry.ts +533 -0
- package/src/v8/types.ts +240 -0
- package/src/cms/blockSource.test.ts +0 -76
- package/src/cms/client.browserBundle.test.ts +0 -44
- package/src/cms/deferredTrigger.test.ts +0 -32
- package/src/cms/draftSource.test.ts +0 -519
- package/src/cms/layoutCacheRace.test.ts +0 -181
- package/src/cms/loadDecofileDirectory.test.ts +0 -109
- package/src/cms/loader.test.ts +0 -557
- package/src/cms/registry.test.ts +0 -110
- package/src/cms/renderJson.test.ts +0 -167
- package/src/cms/resolve.test.ts +0 -1492
- package/src/cms/schema.test.ts +0 -356
- package/src/cms/sectionLoaderContext.test.ts +0 -111
- package/src/cms/sectionLoaders.test.ts +0 -625
- package/src/cms/sectionMixins.test.ts +0 -167
- package/src/cms/stickyFlags.test.ts +0 -117
- package/src/flags/flags.test.ts +0 -148
- package/src/hooks/Image.test.ts +0 -239
- package/src/hooks/RenderSection.test.tsx +0 -81
- package/src/hooks/Stats.test.ts +0 -112
- package/src/hooks/useLoadMore.test.ts +0 -205
- package/src/matchers/builtins.test.ts +0 -318
- package/src/matchers/override.test.ts +0 -205
- package/src/middleware/hydrationContext.test.ts +0 -61
- package/src/middleware/observability.test.ts +0 -335
- package/src/middleware/validateSection.test.ts +0 -147
- package/src/preview/DraftPreviewBadge.render.test.tsx +0 -67
- package/src/preview/DraftPreviewBadge.test.ts +0 -55
- package/src/sdk/abTesting.test.ts +0 -381
- package/src/sdk/cacheHeaders.test.ts +0 -258
- package/src/sdk/cacheStorage.test.ts +0 -242
- package/src/sdk/cachedLoader.test.ts +0 -122
- package/src/sdk/cachedLoaderMaxBytes.test.ts +0 -23
- package/src/sdk/cachedLoaderModule.test.ts +0 -209
- package/src/sdk/cachedLoaderSizeMetric.test.ts +0 -93
- package/src/sdk/cn.test.ts +0 -34
- package/src/sdk/composite.test.ts +0 -121
- package/src/sdk/cookie.test.ts +0 -108
- package/src/sdk/crypto.test.ts +0 -65
- package/src/sdk/deepOmit.test.ts +0 -45
- package/src/sdk/encoding.test.ts +0 -71
- package/src/sdk/env.test.ts +0 -33
- package/src/sdk/experiments.test.ts +0 -328
- package/src/sdk/fetchCache.test.ts +0 -164
- package/src/sdk/flags.test.ts +0 -91
- package/src/sdk/http.test.ts +0 -71
- package/src/sdk/inflightTimeout.test.ts +0 -35
- package/src/sdk/instrumentedFetch.test.ts +0 -559
- package/src/sdk/invoke.test.ts +0 -115
- package/src/sdk/logger.test.ts +0 -432
- package/src/sdk/otel.test.ts +0 -691
- package/src/sdk/otelAdapters.test.ts +0 -89
- package/src/sdk/otelHttpLog.test.ts +0 -457
- package/src/sdk/otelHttpMeter.test.ts +0 -395
- package/src/sdk/otelHttpTracer.test.ts +0 -474
- package/src/sdk/replaceStream.test.ts +0 -117
- package/src/sdk/requestContextStorage.browser.test.ts +0 -29
- package/src/sdk/splitExactRedirects.test.ts +0 -154
- package/src/sdk/urlRedaction.test.ts +0 -73
- package/src/sdk/urlUtils.test.ts +0 -34
- package/src/sdk/useDevice.test.ts +0 -130
- package/src/sdk/useScript.test.ts +0 -128
- package/src/sdk/useSuggestions.test.ts +0 -230
- package/tsconfig.json +0 -7
package/src/v8/fetch.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@decocms/blocks/fetch`: the instrumented fetch every upstream client uses.
|
|
3
|
+
* See /next/upstream-clients and /next/api-reference#createinstrumentedfetch-options.
|
|
4
|
+
*
|
|
5
|
+
* Each request is timed until its response headers arrive and measured once
|
|
6
|
+
* (`http.client.request.duration`), with `provider`, `operation`,
|
|
7
|
+
* `status_class`, `cached` and `retries` labels, however many retries it
|
|
8
|
+
* took. Measurements go to the CMS in the same process, and nowhere when it
|
|
9
|
+
* has no telemetry destination. Nothing about a request's body, headers or
|
|
10
|
+
* query string is recorded.
|
|
11
|
+
*/
|
|
12
|
+
import { currentTelemetry, describe, newTraceId } from "./telemetry";
|
|
13
|
+
|
|
14
|
+
interface InstrumentedFetchOptions {
|
|
15
|
+
/** The provider label, e.g. "vtex", "acme-search". */
|
|
16
|
+
provider: string;
|
|
17
|
+
/** The fetch underneath; defaults to `globalThis.fetch`. */
|
|
18
|
+
fetch?: typeof fetch;
|
|
19
|
+
/** Off unless set. `attempts` is how many times a failed request is retried; a retried request is measured once. */
|
|
20
|
+
retry?: { attempts: number; backoffMs?: number };
|
|
21
|
+
/** Off unless set: after `failures` consecutive failures, fail fast for `cooldownMs`. */
|
|
22
|
+
circuitBreaker?: { failures: number; cooldownMs: number };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
type InstrumentedFetch = (
|
|
26
|
+
input: string | URL | Request,
|
|
27
|
+
init?: RequestInit & { operation?: string },
|
|
28
|
+
) => Promise<Response>;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Where a framework binding installs its upstream cache (on Workers,
|
|
32
|
+
* `@decocms/tanstack` installs one over the Cache API). GETs go through it,
|
|
33
|
+
* and it reports whether the response came from the cache.
|
|
34
|
+
*/
|
|
35
|
+
const UPSTREAM_CACHE = Symbol.for("decocms.blocks.upstreamCache");
|
|
36
|
+
|
|
37
|
+
type UpstreamCache = (
|
|
38
|
+
input: string | URL | Request,
|
|
39
|
+
init: RequestInit,
|
|
40
|
+
fetch: typeof globalThis.fetch,
|
|
41
|
+
) => Promise<{ response: Response; cached: boolean }>;
|
|
42
|
+
|
|
43
|
+
/** Statuses worth retrying: rate limits and gateway errors. */
|
|
44
|
+
const RETRY_STATUSES = new Set([429, 502, 503, 504]);
|
|
45
|
+
/** Only requests that are safe to repeat are retried. */
|
|
46
|
+
const IDEMPOTENT = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
|
|
47
|
+
|
|
48
|
+
export function createInstrumentedFetch(options: InstrumentedFetchOptions): InstrumentedFetch {
|
|
49
|
+
const { provider, retry, circuitBreaker } = options;
|
|
50
|
+
let failures = 0;
|
|
51
|
+
let openUntil = 0;
|
|
52
|
+
|
|
53
|
+
return async (input, init = {}) => {
|
|
54
|
+
const { operation = "unknown", ...requestInit } = init;
|
|
55
|
+
const method = (
|
|
56
|
+
requestInit.method ?? (input instanceof Request ? input.method : "GET")
|
|
57
|
+
).toUpperCase();
|
|
58
|
+
const origin = options.fetch ?? globalThis.fetch;
|
|
59
|
+
const cache = (globalThis as Record<symbol, UpstreamCache | undefined>)[UPSTREAM_CACHE];
|
|
60
|
+
let cached = false;
|
|
61
|
+
const doFetch: typeof globalThis.fetch =
|
|
62
|
+
typeof cache === "function" && method === "GET"
|
|
63
|
+
? async (request, requestInit = {}) => {
|
|
64
|
+
const hit = await cache(request as string | URL | Request, requestInit, origin);
|
|
65
|
+
cached = hit.cached;
|
|
66
|
+
return hit.response;
|
|
67
|
+
}
|
|
68
|
+
: origin;
|
|
69
|
+
const maxRetries =
|
|
70
|
+
retry && IDEMPOTENT.has(method) ? Math.max(0, Math.floor(retry.attempts)) : 0;
|
|
71
|
+
const startedAt = Date.now();
|
|
72
|
+
const started = performance.now();
|
|
73
|
+
let retries = 0;
|
|
74
|
+
let response: Response | undefined;
|
|
75
|
+
let failure: unknown;
|
|
76
|
+
|
|
77
|
+
if (circuitBreaker && failures >= circuitBreaker.failures && Date.now() < openUntil) {
|
|
78
|
+
failure = new Error(`${provider} ${operation}: circuit open after ${failures} failures`);
|
|
79
|
+
} else {
|
|
80
|
+
for (;;) {
|
|
81
|
+
try {
|
|
82
|
+
response = await doFetch(
|
|
83
|
+
maxRetries > 0 && input instanceof Request ? input.clone() : input,
|
|
84
|
+
requestInit,
|
|
85
|
+
);
|
|
86
|
+
failure = undefined;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
response = undefined;
|
|
89
|
+
failure = error;
|
|
90
|
+
}
|
|
91
|
+
const retryable =
|
|
92
|
+
response !== undefined ? RETRY_STATUSES.has(response.status) : !isAbort(failure);
|
|
93
|
+
if (!retryable || retries >= maxRetries) break;
|
|
94
|
+
void response?.body?.cancel().catch(() => {});
|
|
95
|
+
await new Promise((resolve) =>
|
|
96
|
+
setTimeout(resolve, (retry?.backoffMs ?? 100) * 2 ** retries),
|
|
97
|
+
);
|
|
98
|
+
retries++;
|
|
99
|
+
}
|
|
100
|
+
if (circuitBreaker) {
|
|
101
|
+
const failed = response === undefined || response.status >= 500;
|
|
102
|
+
failures = failed ? failures + 1 : 0;
|
|
103
|
+
if (failed && failures >= circuitBreaker.failures) {
|
|
104
|
+
openUntil = Date.now() + circuitBreaker.cooldownMs;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const telemetry = currentTelemetry();
|
|
110
|
+
if (telemetry !== undefined) {
|
|
111
|
+
const labels = {
|
|
112
|
+
provider,
|
|
113
|
+
operation,
|
|
114
|
+
status_class: response ? `${Math.floor(response.status / 100)}xx` : "error",
|
|
115
|
+
// Upstream caching lives in the binding, under this fetch.
|
|
116
|
+
cached,
|
|
117
|
+
retries,
|
|
118
|
+
};
|
|
119
|
+
telemetry.histogram(
|
|
120
|
+
"http.client.request.duration",
|
|
121
|
+
labels,
|
|
122
|
+
(performance.now() - started) / 1000,
|
|
123
|
+
);
|
|
124
|
+
if (response === undefined) {
|
|
125
|
+
telemetry.error(`${provider} ${operation} failed: ${describe(failure)}`, {
|
|
126
|
+
"error.code": "FETCH_FAILED",
|
|
127
|
+
provider,
|
|
128
|
+
operation,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
if (telemetry.sampleTrace()) {
|
|
132
|
+
telemetry.span({
|
|
133
|
+
name: `${provider} ${operation}`,
|
|
134
|
+
kind: "client",
|
|
135
|
+
traceId: newTraceId(),
|
|
136
|
+
start: startedAt,
|
|
137
|
+
end: Date.now(),
|
|
138
|
+
attributes: { ...labels, "http.response.status_code": response?.status },
|
|
139
|
+
error: response === undefined || response.status >= 500,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (response === undefined) throw failure;
|
|
145
|
+
return response;
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function isAbort(error: unknown): boolean {
|
|
150
|
+
const name = (error as { name?: unknown } | null)?.name;
|
|
151
|
+
return name === "AbortError" || name === "TimeoutError";
|
|
152
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Identity helpers for process-wide singletons (`createCMS`, `remoteLoader`):
|
|
3
|
+
* keys go into the global symbol registry, so they're derived from the
|
|
4
|
+
* configuration and never carry a secret.
|
|
5
|
+
*/
|
|
6
|
+
import type { Loader, Snapshot } from "./types";
|
|
7
|
+
|
|
8
|
+
const OBJECT_IDS = Symbol.for("decocms.blocks.cms-loader-ids");
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `module:<root>` for a content module, which names the `.deco` folder it was
|
|
12
|
+
* generated from in a `root` field `deco content` writes (not part of the
|
|
13
|
+
* documented `Snapshot`); `loader#<id>`/`module#<id>` otherwise.
|
|
14
|
+
*/
|
|
15
|
+
export function contentIdentity(content: Snapshot | Loader): string {
|
|
16
|
+
if (typeof (content as Loader).load === "function") return `loader#${objectId(content)}`;
|
|
17
|
+
const root: unknown = (content as { root?: unknown }).root;
|
|
18
|
+
return typeof root === "string" && root.length > 0
|
|
19
|
+
? `module:${root}`
|
|
20
|
+
: `module#${objectId(content)}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A process-wide id per object (a loader, a root-less module), shared by every copy of this module. */
|
|
24
|
+
function objectId(object: object): number {
|
|
25
|
+
const store = globalThis as unknown as Record<
|
|
26
|
+
symbol,
|
|
27
|
+
{ ids: WeakMap<object, number>; next: number }
|
|
28
|
+
>;
|
|
29
|
+
store[OBJECT_IDS] ??= { ids: new WeakMap(), next: 1 };
|
|
30
|
+
const registry = store[OBJECT_IDS];
|
|
31
|
+
let id = registry.ids.get(object);
|
|
32
|
+
if (id === undefined) {
|
|
33
|
+
id = registry.next++;
|
|
34
|
+
registry.ids.set(object, id);
|
|
35
|
+
}
|
|
36
|
+
return id;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** FNV-1a, 32-bit: a non-cryptographic fingerprint that keeps secrets out of keys and logs. */
|
|
40
|
+
export function fnv1a(input: string): string {
|
|
41
|
+
let hash = 0x811c9dc5;
|
|
42
|
+
for (let i = 0; i < input.length; i++) {
|
|
43
|
+
hash ^= input.charCodeAt(i);
|
|
44
|
+
hash = Math.imul(hash, 0x01000193);
|
|
45
|
+
}
|
|
46
|
+
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Reads an environment variable where there is one (Node, Bun, Workers with nodejs_compat). */
|
|
50
|
+
export function readEnv(name: string): string | undefined {
|
|
51
|
+
try {
|
|
52
|
+
return (globalThis as { process?: { env?: Record<string, string | undefined> } }).process
|
|
53
|
+
?.env?.[name];
|
|
54
|
+
} catch {
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Clears every global instance whose registry key starts with `prefix`. */
|
|
60
|
+
export function clearGlobals(prefix: string): void {
|
|
61
|
+
const store = globalThis as unknown as Record<symbol, unknown>;
|
|
62
|
+
for (const symbol of Object.getOwnPropertySymbols(globalThis)) {
|
|
63
|
+
if (Symbol.keyFor(symbol)?.startsWith(prefix)) delete store[symbol];
|
|
64
|
+
}
|
|
65
|
+
}
|
package/src/v8/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The next-major (v8) core SDK: `createCMS`, the clients, the built-in blocks,
|
|
3
|
+
* `matchRoute` and the draft helpers. Re-exported from the package root, where
|
|
4
|
+
* these names are the documented ones; see /next/api-reference.
|
|
5
|
+
*/
|
|
6
|
+
export { createCMS, resetForTests } from "./cms";
|
|
7
|
+
export {
|
|
8
|
+
DRAFT_COOKIE,
|
|
9
|
+
draftCookie,
|
|
10
|
+
draftPointer,
|
|
11
|
+
formatDraftPointer,
|
|
12
|
+
parseDraftPointer,
|
|
13
|
+
} from "./draft";
|
|
14
|
+
export { matchRoute } from "./matchRoute";
|
|
15
|
+
export { remoteLoader } from "./remoteLoader";
|
|
16
|
+
export type {
|
|
17
|
+
Analytics,
|
|
18
|
+
Block,
|
|
19
|
+
BlockFunction,
|
|
20
|
+
Blocks,
|
|
21
|
+
Client,
|
|
22
|
+
CMS,
|
|
23
|
+
CMSError,
|
|
24
|
+
DraftPointer,
|
|
25
|
+
Lazy,
|
|
26
|
+
ListOptions,
|
|
27
|
+
Loader,
|
|
28
|
+
Match,
|
|
29
|
+
Page,
|
|
30
|
+
Redirect,
|
|
31
|
+
Result,
|
|
32
|
+
Route,
|
|
33
|
+
Secret,
|
|
34
|
+
Seo,
|
|
35
|
+
Snapshot,
|
|
36
|
+
Telemetry,
|
|
37
|
+
TelemetryConfig,
|
|
38
|
+
Variant,
|
|
39
|
+
} from "./types";
|
package/src/v8/json.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Small JSON-shape helpers shared by the resolver and the CMS. */
|
|
2
|
+
|
|
3
|
+
export type JsonObject = Record<string, unknown>;
|
|
4
|
+
|
|
5
|
+
/** A plain `{}` object (JSON-like), not an array, a class instance, a Date… */
|
|
6
|
+
export function isPlainObject(value: unknown): value is JsonObject {
|
|
7
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
8
|
+
const proto = Object.getPrototypeOf(value);
|
|
9
|
+
return proto === Object.prototype || proto === null;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** A stored block: a plain object whose `__resolveType` is a string. */
|
|
13
|
+
export function isBlock(value: unknown): value is JsonObject & { __resolveType: string } {
|
|
14
|
+
return isPlainObject(value) && typeof value.__resolveType === "string";
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Own-property lookup that ignores the prototype chain (`"constructor"`, `"__proto__"`…). */
|
|
18
|
+
export function own<T>(record: Record<string, T> | undefined, key: string): T | undefined {
|
|
19
|
+
return record !== undefined && Object.hasOwn(record, key) ? record[key] : undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* A canonical string for a JSON-like value: object keys sorted, so two equal
|
|
24
|
+
* blocks written in a different key order share a key. Returns `null` for
|
|
25
|
+
* anything that isn't JSON-like (functions, Dates, class instances…), which
|
|
26
|
+
* callers treat as "don't memoize". Object results are cached per object, so a
|
|
27
|
+
* subtree's key is computed once even when its parents are keyed too.
|
|
28
|
+
*/
|
|
29
|
+
export function canonicalKey(value: unknown, cache: WeakMap<object, string | null>): string | null {
|
|
30
|
+
switch (typeof value) {
|
|
31
|
+
case "string":
|
|
32
|
+
case "boolean":
|
|
33
|
+
return JSON.stringify(value);
|
|
34
|
+
case "number":
|
|
35
|
+
return Number.isFinite(value) ? String(value) : "null";
|
|
36
|
+
case "undefined":
|
|
37
|
+
return "~";
|
|
38
|
+
case "object":
|
|
39
|
+
break;
|
|
40
|
+
default:
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
if (value === null) return "null";
|
|
44
|
+
const cached = cache.get(value);
|
|
45
|
+
if (cached !== undefined) return cached;
|
|
46
|
+
|
|
47
|
+
let key: string | null;
|
|
48
|
+
if (Array.isArray(value)) {
|
|
49
|
+
key = joinKeys(
|
|
50
|
+
value.map((item) => canonicalKey(item, cache)),
|
|
51
|
+
"[",
|
|
52
|
+
"]",
|
|
53
|
+
);
|
|
54
|
+
} else if (isPlainObject(value)) {
|
|
55
|
+
const names = Object.keys(value).sort();
|
|
56
|
+
key = joinKeys(
|
|
57
|
+
names.map((name) => {
|
|
58
|
+
const child = canonicalKey(value[name], cache);
|
|
59
|
+
return child === null ? null : `${JSON.stringify(name)}:${child}`;
|
|
60
|
+
}),
|
|
61
|
+
"{",
|
|
62
|
+
"}",
|
|
63
|
+
);
|
|
64
|
+
} else {
|
|
65
|
+
key = null;
|
|
66
|
+
}
|
|
67
|
+
cache.set(value, key);
|
|
68
|
+
return key;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function joinKeys(parts: (string | null)[], open: string, close: string): string | null {
|
|
72
|
+
if (parts.some((part) => part === null)) return null;
|
|
73
|
+
return `${open}${parts.join(",")}${close}`;
|
|
74
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `matchRoute(url, items)`: finds the entry for a URL (see /next/routing and
|
|
3
|
+
* /next/router-internals).
|
|
4
|
+
*
|
|
5
|
+
* Paths compile into a segment trie, cached per array object: a lookup costs
|
|
6
|
+
* the URL's depth, not the number of routes. At every node the walk tries the
|
|
7
|
+
* literal child, then the parameter child, then a trailing `*` (a splat: one
|
|
8
|
+
* or more remaining segments), so exact paths win over parameters and
|
|
9
|
+
* parameters over a splat, per segment. Redirects are a second trie, checked
|
|
10
|
+
* first. Two entries that
|
|
11
|
+
* reach the same leaf are a conflict `deco check` reports; here the earlier
|
|
12
|
+
* one keeps it, so a lookup never throws. No regex, no sorting.
|
|
13
|
+
*/
|
|
14
|
+
import type { LegacyRedirect, Match, Redirect, RedirectStatus, Route } from "./types";
|
|
15
|
+
|
|
16
|
+
/** A leaf holds the entry and its parameter names, in path order; `splat` is a trailing `*`'s leaf. */
|
|
17
|
+
type Leaf<T> = { value: T; names: string[] };
|
|
18
|
+
type TrieNode<T> = {
|
|
19
|
+
literals: Map<string, TrieNode<T>>;
|
|
20
|
+
param?: TrieNode<T>;
|
|
21
|
+
leaf?: Leaf<T>;
|
|
22
|
+
splat?: Leaf<T>;
|
|
23
|
+
};
|
|
24
|
+
type Hit<T> = { value: T; params: Record<string, string>; rest: string[] };
|
|
25
|
+
type NormalizedRedirect = Redirect & { status: RedirectStatus };
|
|
26
|
+
|
|
27
|
+
const routeTries = new WeakMap<object, TrieNode<Route>>();
|
|
28
|
+
const redirectTries = new WeakMap<object, TrieNode<NormalizedRedirect>>();
|
|
29
|
+
const STATUSES = new Set<number>([301, 302, 307, 308]);
|
|
30
|
+
|
|
31
|
+
export function matchRoute<T extends Route>(
|
|
32
|
+
url: string | URL | Request,
|
|
33
|
+
items: { routes: T[]; redirects?: Redirect[] },
|
|
34
|
+
): Match<T> {
|
|
35
|
+
const target = parseTarget(url);
|
|
36
|
+
if (target === null) return { kind: "not-found" };
|
|
37
|
+
|
|
38
|
+
const redirects: unknown[] = Array.isArray(items?.redirects) ? items.redirects : [];
|
|
39
|
+
const redirectTrie = cached(redirectTries, redirects, () =>
|
|
40
|
+
redirects.flatMap((input) => {
|
|
41
|
+
const r = normalizeRedirect(input);
|
|
42
|
+
return r ? [[r.from, r] as [string, NormalizedRedirect]] : [];
|
|
43
|
+
}),
|
|
44
|
+
);
|
|
45
|
+
const redirect = lookup(redirectTrie, target.segments);
|
|
46
|
+
if (redirect !== null) {
|
|
47
|
+
const location = buildLocation(redirect, target.search);
|
|
48
|
+
return { kind: "redirect", location, status: redirect.value.status };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const routes = Array.isArray(items?.routes) ? items.routes : [];
|
|
52
|
+
const trie = cached(routeTries, routes, () =>
|
|
53
|
+
routes.filter((r) => typeof r?.path === "string").map((r) => [r.path, r as Route]),
|
|
54
|
+
);
|
|
55
|
+
const found = lookup(trie, target.segments);
|
|
56
|
+
if (found === null) return { kind: "not-found" };
|
|
57
|
+
return { kind: "match", entry: found.value as T, params: found.params };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The URL's path segments (percent-decoded) and its query string, with its `?`, or `""`. */
|
|
61
|
+
function parseTarget(url: string | URL | Request): { segments: string[]; search: string } | null {
|
|
62
|
+
try {
|
|
63
|
+
const raw = typeof url === "string" ? url : url instanceof URL ? url.href : url.url;
|
|
64
|
+
// A bare path stays a path: `//summer` is not a host named "summer".
|
|
65
|
+
const parsed = raw.startsWith("/") ? new URL(raw, "http://path.invalid") : new URL(raw);
|
|
66
|
+
const pathname = raw.startsWith("/") ? raw : parsed.pathname;
|
|
67
|
+
return { segments: splitPath(pathname).map(safeDecode), search: parsed.search };
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `/a/b/`, `/a//b` and `/a/b?x` all name `["a", "b"]`; `/` names `[]`. */
|
|
74
|
+
function splitPath(path: string): string[] {
|
|
75
|
+
const query = path.indexOf("?");
|
|
76
|
+
const hash = path.indexOf("#");
|
|
77
|
+
const end = Math.min(query === -1 ? path.length : query, hash === -1 ? path.length : hash);
|
|
78
|
+
return path
|
|
79
|
+
.slice(0, end)
|
|
80
|
+
.split("/")
|
|
81
|
+
.filter((segment) => segment.length > 0);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function safeDecode(segment: string): string {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(segment);
|
|
87
|
+
} catch {
|
|
88
|
+
return segment;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The trie for an array, built once per array object. */
|
|
93
|
+
function cached<T>(cache: WeakMap<object, TrieNode<T>>, key: object, entries: () => [string, T][]) {
|
|
94
|
+
const hit = cache.get(key);
|
|
95
|
+
if (hit) return hit;
|
|
96
|
+
const root: TrieNode<T> = { literals: new Map() };
|
|
97
|
+
for (const [path, value] of entries()) insert(root, path, value);
|
|
98
|
+
cache.set(key, root);
|
|
99
|
+
return root;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Adds `path`; returns the value already holding its leaf (a conflict: the earlier keeps it). */
|
|
103
|
+
function insert<T>(root: TrieNode<T>, path: string, value: T): T | undefined {
|
|
104
|
+
const names: string[] = [];
|
|
105
|
+
const segments = splitPath(path);
|
|
106
|
+
let node = root;
|
|
107
|
+
for (const [i, segment] of segments.entries()) {
|
|
108
|
+
if (segment === "*" && i === segments.length - 1) {
|
|
109
|
+
if (node.splat) return node.splat.value;
|
|
110
|
+
node.splat = { value, names };
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
if (segment.startsWith(":") && segment.length > 1) {
|
|
114
|
+
names.push(segment.slice(1));
|
|
115
|
+
node = node.param ??= { literals: new Map() };
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const literal = safeDecode(segment);
|
|
119
|
+
const child = node.literals.get(literal) ?? { literals: new Map() };
|
|
120
|
+
node.literals.set(literal, child);
|
|
121
|
+
node = child;
|
|
122
|
+
}
|
|
123
|
+
if (node.leaf) return node.leaf.value;
|
|
124
|
+
node.leaf = { value, names };
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The entries that reach a leaf an earlier entry already holds: two equal
|
|
130
|
+
* paths, or two templates of one shape (`/:slug/p` and `/:id/p`). `matchRoute`
|
|
131
|
+
* serves the earlier one; `deco check` reports each pair.
|
|
132
|
+
*/
|
|
133
|
+
export function findRouteConflicts<T extends { path: string }>(entries: readonly T[]) {
|
|
134
|
+
const root: TrieNode<T> = { literals: new Map() };
|
|
135
|
+
const conflicts: { entry: T; other: T }[] = [];
|
|
136
|
+
for (const entry of entries) {
|
|
137
|
+
const other = insert(root, entry.path, entry);
|
|
138
|
+
if (other !== undefined) conflicts.push({ entry, other });
|
|
139
|
+
}
|
|
140
|
+
return conflicts;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Walks the URL's segments: the literal child first, then the parameter child, then the splat. */
|
|
144
|
+
function lookup<T>(node: TrieNode<T>, segs: string[], i = 0, vals: string[] = []): Hit<T> | null {
|
|
145
|
+
if (i === segs.length) return node.leaf ? hit(node.leaf, vals, []) : null;
|
|
146
|
+
const literal = node.literals.get(segs[i]!);
|
|
147
|
+
let found = literal ? lookup(literal, segs, i + 1, vals) : null;
|
|
148
|
+
// A parameter is one segment and never contains a slash, even an encoded one.
|
|
149
|
+
if (!found && node.param && !segs[i]!.includes("/")) {
|
|
150
|
+
found = lookup(node.param, segs, i + 1, [...vals, segs[i]!]);
|
|
151
|
+
}
|
|
152
|
+
// A splat takes the rest (at least one segment, as there is one here).
|
|
153
|
+
return found ?? (node.splat ? hit(node.splat, vals, segs.slice(i)) : null);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function hit<T>({ value, names }: Leaf<T>, values: string[], rest: string[]): Hit<T> {
|
|
157
|
+
const params: Record<string, string> = Object.fromEntries(names.map((n, i) => [n, values[i]!]));
|
|
158
|
+
if (rest.length > 0) params["*"] = rest.join("/");
|
|
159
|
+
return { value, params, rest };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Both redirect shapes: the flat built-in `{ from, to, permanent, status?,
|
|
164
|
+
* discardQueryParameters? }` and the site editor's legacy nested
|
|
165
|
+
* `{ redirect: { from, to, type } }` (see /next/studio-compatibility), where
|
|
166
|
+
* `permanent` is a 301 and anything else a 307.
|
|
167
|
+
*/
|
|
168
|
+
function normalizeRedirect(input: unknown): NormalizedRedirect | null {
|
|
169
|
+
if (typeof input !== "object" || input === null) return null;
|
|
170
|
+
const nested = (input as Partial<LegacyRedirect>).redirect;
|
|
171
|
+
const flat = (nested ?? input) as Partial<Redirect & LegacyRedirect["redirect"]>;
|
|
172
|
+
if (typeof flat.from !== "string" || typeof flat.to !== "string") return null;
|
|
173
|
+
let status: RedirectStatus = flat.permanent === true ? 301 : 302;
|
|
174
|
+
if (nested) status = flat.type === "permanent" ? 301 : 307;
|
|
175
|
+
else if (STATUSES.has(flat.status as number)) status = flat.status as RedirectStatus;
|
|
176
|
+
const { from, to, discardQueryParameters } = flat;
|
|
177
|
+
return { from, to, permanent: status === 301 || status === 308, status, discardQueryParameters };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Fills the redirect's `:name` segments with the parameters `from` captured,
|
|
182
|
+
* and a `*` segment with the splat's segments, then carries the request's
|
|
183
|
+
* query string over unless the redirect discards it. Each captured segment is
|
|
184
|
+
* re-encoded on its own and none is empty, so a `to` on this site can't turn
|
|
185
|
+
* into `//other.host` (or `/\other.host`).
|
|
186
|
+
*/
|
|
187
|
+
function buildLocation({ value: redirect, params, rest }: Hit<NormalizedRedirect>, search: string) {
|
|
188
|
+
const { to } = redirect;
|
|
189
|
+
const hashAt = to.indexOf("#") === -1 ? to.length : to.indexOf("#");
|
|
190
|
+
const queryAt = to.indexOf("?") === -1 || to.indexOf("?") > hashAt ? hashAt : to.indexOf("?");
|
|
191
|
+
const filled = to
|
|
192
|
+
.slice(0, queryAt)
|
|
193
|
+
.split("/")
|
|
194
|
+
.map((s) => {
|
|
195
|
+
if (s === "*" && rest.length > 0) return rest.map(encodeURIComponent).join("/");
|
|
196
|
+
return Object.hasOwn(params, s.slice(1)) && s[0] === ":"
|
|
197
|
+
? encodeURIComponent(params[s.slice(1)]!)
|
|
198
|
+
: s;
|
|
199
|
+
})
|
|
200
|
+
.join("/");
|
|
201
|
+
const carried = redirect.discardQueryParameters ? "" : search.slice(1);
|
|
202
|
+
const query = [to.slice(queryAt + 1, hashAt), carried].filter(Boolean).join("&");
|
|
203
|
+
return `${filled}${query ? `?${query}` : ""}${to.slice(hashAt)}`;
|
|
204
|
+
}
|