@decocms/blocks 8.0.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.
Files changed (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -0,0 +1,133 @@
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
+ /**
18
+ * The fetch underneath; defaults to `globalThis.fetch`. An upstream cache
19
+ * goes here (see /next/caching#upstream-data); a response it serves from
20
+ * the cache carries `x-cache: HIT` and is measured with `cached=true`.
21
+ */
22
+ fetch?: typeof fetch;
23
+ /** Off unless set. `attempts` is how many times a failed request is retried; a retried request is measured once. */
24
+ retry?: { attempts: number; backoffMs?: number };
25
+ /** Off unless set: after `failures` consecutive failures, fail fast for `cooldownMs`. */
26
+ circuitBreaker?: { failures: number; cooldownMs: number };
27
+ }
28
+
29
+ type InstrumentedFetch = (
30
+ input: string | URL | Request,
31
+ init?: RequestInit & { operation?: string },
32
+ ) => Promise<Response>;
33
+
34
+ /** Statuses worth retrying: rate limits and gateway errors. */
35
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
36
+ /** Only requests that are safe to repeat are retried. */
37
+ const IDEMPOTENT = new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
38
+
39
+ export function createInstrumentedFetch(options: InstrumentedFetchOptions): InstrumentedFetch {
40
+ const { provider, retry, circuitBreaker } = options;
41
+ let failures = 0;
42
+ let openUntil = 0;
43
+
44
+ return async (input, init = {}) => {
45
+ const { operation = "unknown", ...requestInit } = init;
46
+ const method = (
47
+ requestInit.method ?? (input instanceof Request ? input.method : "GET")
48
+ ).toUpperCase();
49
+ const doFetch = options.fetch ?? globalThis.fetch;
50
+ const maxRetries =
51
+ retry && IDEMPOTENT.has(method) ? Math.max(0, Math.floor(retry.attempts)) : 0;
52
+ const startedAt = Date.now();
53
+ const started = performance.now();
54
+ let retries = 0;
55
+ let response: Response | undefined;
56
+ let failure: unknown;
57
+
58
+ if (circuitBreaker && failures >= circuitBreaker.failures && Date.now() < openUntil) {
59
+ failure = new Error(`${provider} ${operation}: circuit open after ${failures} failures`);
60
+ } else {
61
+ for (;;) {
62
+ try {
63
+ response = await doFetch(
64
+ maxRetries > 0 && input instanceof Request ? input.clone() : input,
65
+ requestInit,
66
+ );
67
+ failure = undefined;
68
+ } catch (error) {
69
+ response = undefined;
70
+ failure = error;
71
+ }
72
+ const retryable =
73
+ response !== undefined ? RETRY_STATUSES.has(response.status) : !isAbort(failure);
74
+ if (!retryable || retries >= maxRetries) break;
75
+ void response?.body?.cancel().catch(() => {});
76
+ await new Promise((resolve) =>
77
+ setTimeout(resolve, (retry?.backoffMs ?? 100) * 2 ** retries),
78
+ );
79
+ retries++;
80
+ }
81
+ if (circuitBreaker) {
82
+ const failed = response === undefined || response.status >= 500;
83
+ failures = failed ? failures + 1 : 0;
84
+ if (failed && failures >= circuitBreaker.failures) {
85
+ openUntil = Date.now() + circuitBreaker.cooldownMs;
86
+ }
87
+ }
88
+ }
89
+
90
+ const telemetry = currentTelemetry();
91
+ if (telemetry !== undefined) {
92
+ const labels = {
93
+ provider,
94
+ operation,
95
+ status_class: response ? `${Math.floor(response.status / 100)}xx` : "error",
96
+ // An upstream cache is the site's own `fetch` option; it marks a hit `x-cache: HIT`.
97
+ cached: response?.headers.get("x-cache") === "HIT",
98
+ retries,
99
+ };
100
+ telemetry.histogram(
101
+ "http.client.request.duration",
102
+ labels,
103
+ (performance.now() - started) / 1000,
104
+ );
105
+ if (response === undefined) {
106
+ telemetry.error(`${provider} ${operation} failed: ${describe(failure)}`, {
107
+ "error.code": "FETCH_FAILED",
108
+ provider,
109
+ operation,
110
+ });
111
+ }
112
+ if (telemetry.sampleTrace()) {
113
+ telemetry.span({
114
+ name: `${provider} ${operation}`,
115
+ kind: "client",
116
+ traceId: newTraceId(),
117
+ start: startedAt,
118
+ end: Date.now(),
119
+ attributes: { ...labels, "http.response.status_code": response?.status },
120
+ error: response === undefined || response.status >= 500,
121
+ });
122
+ }
123
+ }
124
+
125
+ if (response === undefined) throw failure;
126
+ return response;
127
+ };
128
+ }
129
+
130
+ function isAbort(error: unknown): boolean {
131
+ const name = (error as { name?: unknown } | null)?.name;
132
+ return name === "AbortError" || name === "TimeoutError";
133
+ }
@@ -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
+ }
@@ -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
+ }