@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
@@ -1,109 +0,0 @@
1
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { loadDecofileDirectory } from "./loadDecofileDirectory";
6
-
7
- describe("loadDecofileDirectory", () => {
8
- let dir: string;
9
-
10
- beforeEach(() => {
11
- dir = mkdtempSync(join(tmpdir(), "decofile-test-"));
12
- });
13
-
14
- afterEach(() => {
15
- rmSync(dir, { recursive: true, force: true });
16
- });
17
-
18
- it("loads every .json file in the directory into a keyed map", async () => {
19
- writeFileSync(
20
- join(dir, "pages-home-123.json"),
21
- JSON.stringify({ __resolveType: "website/pages/Page.tsx", path: "/" }),
22
- );
23
- writeFileSync(
24
- join(dir, "Banner Grid - 01.json"),
25
- JSON.stringify({ __resolveType: "site/sections/BannerGrid.tsx" }),
26
- );
27
-
28
- const blocks = await loadDecofileDirectory(dir);
29
-
30
- expect(Object.keys(blocks)).toHaveLength(2);
31
- expect(blocks["pages-home-123"]).toEqual({
32
- __resolveType: "website/pages/Page.tsx",
33
- path: "/",
34
- });
35
- expect(blocks["Banner Grid - 01"]).toEqual({
36
- __resolveType: "site/sections/BannerGrid.tsx",
37
- });
38
- });
39
-
40
- it("ignores non-.json files", async () => {
41
- writeFileSync(join(dir, "readme.md"), "not a block");
42
- writeFileSync(join(dir, "a.json"), JSON.stringify({ x: 1 }));
43
-
44
- const blocks = await loadDecofileDirectory(dir);
45
- expect(Object.keys(blocks)).toEqual(["a"]);
46
- });
47
-
48
- it("throws with the filename on invalid JSON", async () => {
49
- writeFileSync(join(dir, "broken.json"), "{not valid json");
50
- await expect(loadDecofileDirectory(dir)).rejects.toThrow(/broken\.json/);
51
- });
52
-
53
- it("URL-decodes the filename stem once to produce the block key", async () => {
54
- // Classic deco stores blocks as encodeURIComponent(<block id>).json and
55
- // derives the id back with one decodeURIComponent (parseBlockId). Content
56
- // references saved blocks by the DECODED id ("Cores dos preços"), so the
57
- // map must be keyed by it or every such reference dangles.
58
- writeFileSync(
59
- join(dir, "Cores%20dos%20pre%C3%A7os.json"),
60
- JSON.stringify({ __resolveType: "site/loaders/priceColors.ts" }),
61
- );
62
- // Double-encoded page snapshot (deco.cx corpus shape): decodes ONCE.
63
- writeFileSync(
64
- join(dir, "pages-Acess%25C3%25B3rios-421596.json"),
65
- JSON.stringify({ __resolveType: "website/pages/Page.tsx" }),
66
- );
67
- // Encoded slash becomes a real slash in the id — ids are plain map keys.
68
- writeFileSync(join(dir, "collections%2Fblog%2Fauthors.json"), JSON.stringify({ authors: [] }));
69
-
70
- const blocks = await loadDecofileDirectory(dir);
71
-
72
- expect(blocks["Cores dos preços"]).toEqual({
73
- __resolveType: "site/loaders/priceColors.ts",
74
- });
75
- expect(blocks["pages-Acess%C3%B3rios-421596"]).toEqual({
76
- __resolveType: "website/pages/Page.tsx",
77
- });
78
- expect(blocks["collections/blog/authors"]).toEqual({ authors: [] });
79
- // The raw stems must NOT appear as keys.
80
- expect(blocks["Cores%20dos%20pre%C3%A7os"]).toBeUndefined();
81
- expect(blocks["pages-Acess%25C3%25B3rios-421596"]).toBeUndefined();
82
- });
83
-
84
- it("keeps a stem verbatim when it is not valid percent-encoding", async () => {
85
- // A lone % (e.g. a page literally named "50% off") throws in
86
- // decodeURIComponent — the stem is already the id, keep it.
87
- writeFileSync(join(dir, "pages-50% off-7.json"), JSON.stringify({ x: 1 }));
88
-
89
- const blocks = await loadDecofileDirectory(dir);
90
- expect(blocks["pages-50% off-7"]).toEqual({ x: 1 });
91
- });
92
-
93
- it("resolves decoded-key collisions deterministically (last sorted filename wins) and warns", async () => {
94
- writeFileSync(join(dir, "A B.json"), JSON.stringify({ raw: true }));
95
- writeFileSync(join(dir, "A%20B.json"), JSON.stringify({ encoded: true }));
96
-
97
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
98
- try {
99
- const blocks = await loadDecofileDirectory(dir);
100
- // Code-unit sort: " " (0x20) < "%" (0x25), so "A B.json" comes first
101
- // and "A%20B.json" is processed last — the encoded file wins.
102
- expect(blocks["A B"]).toEqual({ encoded: true });
103
- expect(Object.keys(blocks)).toHaveLength(1);
104
- expect(warn).toHaveBeenCalledWith(expect.stringContaining("A%20B.json"));
105
- } finally {
106
- warn.mockRestore();
107
- }
108
- });
109
- });
@@ -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
- }
@@ -1,200 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
2
- import { findPageByPath, matchPath, setBlocks } from "./loader";
3
-
4
- // Mirrors the behavior of the original deco-cx/deco Fresh framework
5
- // (runtime/features/render.tsx), which uses native `URLPattern` directly
6
- // and returns `result.pathname.groups`. Splats become numbered groups
7
- // ("0", "1", …) — there is no `_splat` rename.
8
-
9
- describe("matchPath", () => {
10
- describe("literal segments", () => {
11
- it("matches the root path", () => {
12
- expect(matchPath("/", "/")).toEqual({});
13
- });
14
-
15
- it("matches exact literal paths", () => {
16
- expect(matchPath("/foo/bar", "/foo/bar")).toEqual({});
17
- });
18
-
19
- it("returns null when literals differ", () => {
20
- expect(matchPath("/foo/bar", "/foo/baz")).toBeNull();
21
- });
22
-
23
- it("returns null when literal-only pattern does not span the whole URL", () => {
24
- expect(matchPath("/foo", "/foo/bar")).toBeNull();
25
- });
26
- });
27
-
28
- describe("named params (:slug)", () => {
29
- it("captures a single param", () => {
30
- expect(matchPath("/foo/:slug", "/foo/sabonete")).toEqual({ slug: "sabonete" });
31
- });
32
-
33
- it("captures a param sandwiched between literals (VTEX PDP)", () => {
34
- expect(matchPath("/produto/:slug/p", "/produto/sabonete/p")).toEqual({
35
- slug: "sabonete",
36
- });
37
- });
38
-
39
- it("returns null when the URL is shorter than the pattern", () => {
40
- expect(matchPath("/foo/:slug", "/foo")).toBeNull();
41
- });
42
- });
43
-
44
- describe("trailing splat (*)", () => {
45
- it("captures the rest as group '0'", () => {
46
- expect(matchPath("/*", "/foo/bar")).toEqual({ "0": "foo/bar" });
47
- });
48
-
49
- it("matches root with empty splat", () => {
50
- expect(matchPath("/*", "/")).toEqual({ "0": "" });
51
- });
52
-
53
- it("captures the remainder under a prefix", () => {
54
- expect(matchPath("/foo/*", "/foo/bar/baz")).toEqual({ "0": "bar/baz" });
55
- });
56
-
57
- // Intentional bug fix: the previous custom matchPath accidentally matched
58
- // `/foo` against `/foo/*` due to its naive split("/") logic, which also
59
- // mis-handled trailing slashes. Native URLPattern (and the Fresh original)
60
- // require at least one segment after `/foo/`.
61
- it("does NOT match the bare prefix without a trailing segment", () => {
62
- expect(matchPath("/foo/*", "/foo")).toBeNull();
63
- });
64
- });
65
-
66
- describe("URLPattern optional groups ({...}?)", () => {
67
- // Patterns emitted by the deco-cx admin / present in production CMS data.
68
- // These are the cases that issue #213 documents as broken.
69
-
70
- it("matches with the optional group present", () => {
71
- expect(matchPath("/{granado/}?*", "/granado/perfumaria")).toEqual({
72
- "0": "perfumaria",
73
- });
74
- });
75
-
76
- it("matches with the optional group absent", () => {
77
- expect(matchPath("/{granado/}?*", "/perfumaria")).toEqual({ "0": "perfumaria" });
78
- });
79
-
80
- it("matches root when optional prefix and splat collapse to empty", () => {
81
- expect(matchPath("/{granado/}?*", "/")).toEqual({ "0": "" });
82
- });
83
-
84
- it("matches with an optional prefix before a literal segment", () => {
85
- expect(matchPath("/{granado/}?campanhas/*", "/granado/campanhas/destaques-2023")).toEqual({
86
- "0": "destaques-2023",
87
- });
88
- expect(matchPath("/{granado/}?campanhas/*", "/campanhas/destaques-2023")).toEqual({
89
- "0": "destaques-2023",
90
- });
91
- });
92
-
93
- it("matches an optional suffix group present and absent", () => {
94
- expect(matchPath("/black-friday{/70-off}?", "/black-friday")).toEqual({});
95
- expect(matchPath("/black-friday{/70-off}?", "/black-friday/70-off")).toEqual({});
96
- });
97
- });
98
-
99
- describe("error tolerance", () => {
100
- it("returns null for malformed patterns instead of throwing", () => {
101
- expect(() => matchPath("/[invalid", "/anything")).not.toThrow();
102
- expect(matchPath("/[invalid", "/anything")).toBeNull();
103
- });
104
-
105
- // Node <= 22 has no URLPattern global. The malformed-pattern try/catch
106
- // above must NOT absorb that ReferenceError — a missing API has to fail
107
- // loudly at first match, not degrade into every CMS page silently
108
- // returning null (which renders as sitewide 404s).
109
- it("throws a descriptive error when the runtime lacks URLPattern", () => {
110
- const g = globalThis as { URLPattern?: unknown };
111
- const saved = g.URLPattern;
112
- // biome-ignore lint/performance/noDelete: restoring exact global state
113
- delete g.URLPattern;
114
- try {
115
- expect(() => matchPath("/foo/:slug", "/foo/bar")).toThrow(/URLPattern.*Node\.js >= 24/s);
116
- } finally {
117
- if (saved !== undefined) g.URLPattern = saved;
118
- }
119
- });
120
- });
121
- });
122
-
123
- describe("findPageByPath specificity", () => {
124
- beforeEach(() => {
125
- setBlocks({
126
- "pages-bf": {
127
- name: "Black Friday",
128
- path: "/black-friday",
129
- sections: [],
130
- },
131
- "pages-bf-splat": {
132
- name: "Black Friday with optional suffix",
133
- path: "/black-friday{/70-off}?",
134
- sections: [],
135
- },
136
- "pages-pdp-plp": {
137
- name: "PDP & PLP",
138
- path: "/{granado/}?*",
139
- sections: [],
140
- },
141
- "pages-product": {
142
- name: "Product",
143
- path: "/produto/:slug/p",
144
- sections: [],
145
- },
146
- });
147
- });
148
-
149
- afterEach(() => {
150
- setBlocks({});
151
- });
152
-
153
- it("prefers an exact literal over an optional-group splat", () => {
154
- const match = findPageByPath("/black-friday");
155
- expect(match?.blockKey).toBe("pages-bf");
156
- });
157
-
158
- it("prefers the home page over an optional-group splat catch-all", () => {
159
- // Regression: /{granado/}?* matches "/" and was out-ranking the home
160
- // because the `{granado` segment counted as a param. The home block
161
- // is a literal-only `/` path and must always win.
162
- setBlocks({
163
- "pages-home": {
164
- name: "Home",
165
- path: "/",
166
- sections: [],
167
- },
168
- "pages-pdp-plp": {
169
- name: "PDP & PLP",
170
- path: "/{granado/}?*",
171
- sections: [],
172
- },
173
- });
174
- const match = findPageByPath("/");
175
- expect(match?.blockKey).toBe("pages-home");
176
- });
177
-
178
- it("falls back to the splat page for unknown URLs", () => {
179
- const match = findPageByPath("/perfumaria");
180
- expect(match?.blockKey).toBe("pages-pdp-plp");
181
- expect(match?.params).toEqual({ "0": "perfumaria" });
182
- });
183
-
184
- it("matches the param-bearing route ahead of the splat catch-all", () => {
185
- const match = findPageByPath("/produto/sabonete/p");
186
- expect(match?.blockKey).toBe("pages-product");
187
- expect(match?.params).toEqual({ slug: "sabonete" });
188
- });
189
-
190
- it("returns null when no page matches", () => {
191
- setBlocks({
192
- "pages-only-bf": {
193
- name: "Black Friday",
194
- path: "/black-friday",
195
- sections: [],
196
- },
197
- });
198
- expect(findPageByPath("/nope")).toBeNull();
199
- });
200
- });