@inlang/paraglide-js 2.25.4 → 2.27.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.
Files changed (124) hide show
  1. package/README.md +2 -1
  2. package/dist/bundler-plugins/per-locale-build/vite-environments.test.js +2 -2
  3. package/dist/bundler-plugins/per-locale-build/vite-environments.test.js.map +1 -1
  4. package/dist/cli/commands/init/command.js +19 -1
  5. package/dist/cli/commands/init/command.js.map +1 -1
  6. package/dist/cli/defaults.js +2 -2
  7. package/dist/cli/defaults.js.map +1 -1
  8. package/dist/cli/steps/add-inlang-check.d.ts +19 -0
  9. package/dist/cli/steps/add-inlang-check.js +60 -0
  10. package/dist/cli/steps/add-inlang-check.js.map +1 -0
  11. package/dist/cli/steps/add-inlang-check.test.d.ts +1 -0
  12. package/dist/cli/steps/add-inlang-check.test.js +88 -0
  13. package/dist/cli/steps/add-inlang-check.test.js.map +1 -0
  14. package/dist/cli/steps/agents-md-suggestion.d.ts +11 -0
  15. package/dist/cli/steps/agents-md-suggestion.js +19 -0
  16. package/dist/cli/steps/agents-md-suggestion.js.map +1 -0
  17. package/dist/cli/steps/agents-md-suggestion.test.d.ts +1 -0
  18. package/dist/cli/steps/agents-md-suggestion.test.js +36 -0
  19. package/dist/cli/steps/agents-md-suggestion.test.js.map +1 -0
  20. package/dist/cli/steps/maybe-add-machine-translation.js +3 -2
  21. package/dist/cli/steps/maybe-add-machine-translation.js.map +1 -1
  22. package/dist/cli/steps/maybe-add-sherlock.js +1 -1
  23. package/dist/cli/steps/maybe-add-sherlock.js.map +1 -1
  24. package/dist/cli/utils.d.ts +9 -0
  25. package/dist/cli/utils.js +15 -0
  26. package/dist/cli/utils.js.map +1 -1
  27. package/dist/compiler/compile-annotation.d.ts +48 -1
  28. package/dist/compiler/compile-annotation.js +238 -10
  29. package/dist/compiler/compile-annotation.js.map +1 -1
  30. package/dist/compiler/compile-bundle.d.ts +3 -2
  31. package/dist/compiler/compile-bundle.js +30 -1
  32. package/dist/compiler/compile-bundle.js.map +1 -1
  33. package/dist/compiler/compile-bundle.test.js +18 -18
  34. package/dist/compiler/compile-bundle.test.js.map +1 -1
  35. package/dist/compiler/compile-local-variable.d.ts +3 -0
  36. package/dist/compiler/compile-local-variable.js +5 -2
  37. package/dist/compiler/compile-local-variable.js.map +1 -1
  38. package/dist/compiler/compile-local-variable.test.js +44 -4
  39. package/dist/compiler/compile-local-variable.test.js.map +1 -1
  40. package/dist/compiler/compile-message.d.ts +29 -1
  41. package/dist/compiler/compile-message.exact-number.test.d.ts +1 -0
  42. package/dist/compiler/compile-message.exact-number.test.js +786 -0
  43. package/dist/compiler/compile-message.exact-number.test.js.map +1 -0
  44. package/dist/compiler/compile-message.js +162 -66
  45. package/dist/compiler/compile-message.js.map +1 -1
  46. package/dist/compiler/compile-message.locals.test.d.ts +1 -0
  47. package/dist/compiler/compile-message.locals.test.js +498 -0
  48. package/dist/compiler/compile-message.locals.test.js.map +1 -0
  49. package/dist/compiler/compile-message.test.js +111 -20
  50. package/dist/compiler/compile-message.test.js.map +1 -1
  51. package/dist/compiler/compile-pattern.d.ts +5 -0
  52. package/dist/compiler/compile-pattern.js +6 -18
  53. package/dist/compiler/compile-pattern.js.map +1 -1
  54. package/dist/compiler/compile-pattern.test.js +165 -1
  55. package/dist/compiler/compile-pattern.test.js.map +1 -1
  56. package/dist/compiler/compile-project.js +4 -1
  57. package/dist/compiler/compile-project.js.map +1 -1
  58. package/dist/compiler/compile-project.test.js +1013 -31
  59. package/dist/compiler/compile-project.test.js.map +1 -1
  60. package/dist/compiler/compile.test.js +1 -1
  61. package/dist/compiler/compile.test.js.map +1 -1
  62. package/dist/compiler/create-readme.d.ts +4 -1
  63. package/dist/compiler/create-readme.js +33 -125
  64. package/dist/compiler/create-readme.js.map +1 -1
  65. package/dist/compiler/emit-ts-declarations.interop.test.js +2 -2
  66. package/dist/compiler/emit-ts-declarations.interop.test.js.map +1 -1
  67. package/dist/compiler/emit-ts-declarations.test.js +4 -4
  68. package/dist/compiler/emit-ts-declarations.test.js.map +1 -1
  69. package/dist/compiler/index.d.ts +1 -1
  70. package/dist/compiler/index.js +1 -1
  71. package/dist/compiler/index.js.map +1 -1
  72. package/dist/compiler/input-alias.d.ts +21 -0
  73. package/dist/compiler/input-alias.js +42 -0
  74. package/dist/compiler/input-alias.js.map +1 -0
  75. package/dist/compiler/input-alias.test.d.ts +1 -0
  76. package/dist/compiler/input-alias.test.js +58 -0
  77. package/dist/compiler/input-alias.test.js.map +1 -0
  78. package/dist/compiler/message-locals.d.ts +46 -0
  79. package/dist/compiler/message-locals.js +129 -0
  80. package/dist/compiler/message-locals.js.map +1 -0
  81. package/dist/compiler/output-structure/locale-modules.js +7 -1
  82. package/dist/compiler/output-structure/locale-modules.js.map +1 -1
  83. package/dist/compiler/output-structure/locale-modules.test.js +35 -0
  84. package/dist/compiler/output-structure/locale-modules.test.js.map +1 -1
  85. package/dist/compiler/output-structure/message-modules.js +5 -3
  86. package/dist/compiler/output-structure/message-modules.js.map +1 -1
  87. package/dist/compiler/output-structure/message-modules.test.js +35 -0
  88. package/dist/compiler/output-structure/message-modules.test.js.map +1 -1
  89. package/dist/compiler/registry.d.ts +12 -0
  90. package/dist/compiler/registry.js +97 -28
  91. package/dist/compiler/registry.js.map +1 -1
  92. package/dist/compiler/runtime/create-runtime.js +24 -1
  93. package/dist/compiler/runtime/create-runtime.js.map +1 -1
  94. package/dist/compiler/runtime/extract-locale-from-url.js +11 -4
  95. package/dist/compiler/runtime/extract-locale-from-url.js.map +1 -1
  96. package/dist/compiler/runtime/generate-static-localized-urls.js +5 -3
  97. package/dist/compiler/runtime/generate-static-localized-urls.js.map +1 -1
  98. package/dist/compiler/runtime/localize-url.js +25 -54
  99. package/dist/compiler/runtime/localize-url.js.map +1 -1
  100. package/dist/compiler/runtime/route-strategy.js +9 -3
  101. package/dist/compiler/runtime/route-strategy.js.map +1 -1
  102. package/dist/compiler/runtime/type.test.js +9 -0
  103. package/dist/compiler/runtime/type.test.js.map +1 -1
  104. package/dist/compiler/runtime/url-pattern-cache.d.ts +11 -0
  105. package/dist/compiler/runtime/url-pattern-cache.js +42 -0
  106. package/dist/compiler/runtime/url-pattern-cache.js.map +1 -0
  107. package/dist/compiler/runtime/url-pattern-index.d.ts +24 -0
  108. package/dist/compiler/runtime/url-pattern-index.differential.test.d.ts +1 -0
  109. package/dist/compiler/runtime/url-pattern-index.differential.test.js +152 -0
  110. package/dist/compiler/runtime/url-pattern-index.differential.test.js.map +1 -0
  111. package/dist/compiler/runtime/url-pattern-index.js +168 -0
  112. package/dist/compiler/runtime/url-pattern-index.js.map +1 -0
  113. package/dist/compiler/runtime/url-pattern-index.test.d.ts +1 -0
  114. package/dist/compiler/runtime/url-pattern-index.test.js +262 -0
  115. package/dist/compiler/runtime/url-pattern-index.test.js.map +1 -0
  116. package/dist/compiler/server/create-server-file.js +25 -1
  117. package/dist/compiler/server/create-server-file.js.map +1 -1
  118. package/dist/compiler/server/create-server-file.test.js +20 -2
  119. package/dist/compiler/server/create-server-file.test.js.map +1 -1
  120. package/dist/compiler/server/middleware.js +29 -4
  121. package/dist/compiler/server/middleware.js.map +1 -1
  122. package/dist/services/env-variables/index.js +1 -1
  123. package/dist/services/env-variables/index.js.map +1 -1
  124. package/package.json +3 -3
@@ -0,0 +1,152 @@
1
+ import { expect, test } from "vitest";
2
+ import { URLPattern as PolyfillURLPattern } from "urlpattern-polyfill";
3
+ import { createRuntimeFile } from "./create-runtime.js";
4
+ import { defaultCompilerOptions } from "../compiler-options.js";
5
+ const engines = [PolyfillURLPattern];
6
+ const nativeURLPattern = Reflect.get(globalThis, "URLPattern");
7
+ if (nativeURLPattern && nativeURLPattern !== PolyfillURLPattern) {
8
+ engines.push(nativeURLPattern);
9
+ }
10
+ let moduleId = 0;
11
+ const patterns = [
12
+ "/section/:slug",
13
+ "/section/:slug?",
14
+ "/section/:slug*",
15
+ "/section/:slug+",
16
+ "/section/:slug(.*)?",
17
+ "/section/:slug(.*)",
18
+ "/section/literal",
19
+ "/section/:slug/details",
20
+ "/section/:a/:b?",
21
+ "/section/:slug(\\d+)",
22
+ "/section/{literal}?",
23
+ "/section%2Fliteral/:slug",
24
+ "/section//:slug",
25
+ "/section/../other/:slug",
26
+ "https://example.com/section/:slug",
27
+ "section/:slug",
28
+ "/section/:slug/:slug",
29
+ "/section/:slug([)",
30
+ ];
31
+ const paths = [
32
+ "/",
33
+ "/section",
34
+ "/section/",
35
+ "/section/literal",
36
+ "/section/story",
37
+ "/section/123",
38
+ "/section/story/details",
39
+ "/section/story/other",
40
+ "/section//story",
41
+ "/section%2Fliteral/story",
42
+ "/other/story",
43
+ "/unknown",
44
+ ];
45
+ function outcome(fn) {
46
+ try {
47
+ const result = fn();
48
+ return {
49
+ value: result instanceof URL
50
+ ? result.href
51
+ : Array.isArray(result)
52
+ ? result.map((url) => url.href)
53
+ : result,
54
+ };
55
+ }
56
+ catch (error) {
57
+ return {
58
+ error: error instanceof Error ? [error.name, error.message] : String(error),
59
+ };
60
+ }
61
+ }
62
+ for (const ctor of engines) {
63
+ test(`${ctor === PolyfillURLPattern ? "polyfill" : "native"} candidate index agrees with native ordered scans`, async () => {
64
+ const previous = Reflect.get(globalThis, "URLPattern");
65
+ Object.defineProperty(globalThis, "URLPattern", {
66
+ configurable: true,
67
+ writable: true,
68
+ value: ctor,
69
+ });
70
+ let comparisons = 0;
71
+ try {
72
+ for (const pattern of patterns) {
73
+ for (const trailingSlash of [undefined, "always", "never"]) {
74
+ for (const catchAllFirst of [false, true]) {
75
+ const specific = {
76
+ pattern,
77
+ localized: [
78
+ ["en", pattern],
79
+ ["de", `/de${pattern}`],
80
+ ],
81
+ };
82
+ const catchAll = {
83
+ pattern: "/:path(.*)?",
84
+ localized: [
85
+ ["de", "/de/:path(.*)?"],
86
+ ["en", "/:path(.*)?"],
87
+ ],
88
+ };
89
+ const code = createRuntimeFile({
90
+ baseLocale: "en",
91
+ locales: ["en", "de", "fr"],
92
+ compilerOptions: {
93
+ ...defaultCompilerOptions,
94
+ strategy: ["url", "baseLocale"],
95
+ trailingSlash,
96
+ urlPatterns: catchAllFirst
97
+ ? [catchAll, specific]
98
+ : [specific, catchAll],
99
+ routeStrategies: [
100
+ { match: pattern, exclude: true },
101
+ { match: "/:path(.*)?", strategy: ["url"] },
102
+ ],
103
+ },
104
+ }).replace('import "@inlang/paraglide-js/urlpattern-polyfill";', "");
105
+ // The reference keeps native construction/matching and all filling
106
+ // logic, but enumerates the original arrays without pruning.
107
+ const scan = code
108
+ .replace("return patternCandidates(urlPatternIndex, url, urlPatterns);", "return urlPatterns;")
109
+ .replace("return patternCandidates(routeStrategyIndex, url, routeStrategies);", "return routeStrategies;");
110
+ expect(scan).not.toBe(code);
111
+ expect(scan).not.toContain("return patternCandidates(");
112
+ const load = (source) => import(
113
+ /* @vite-ignore */ "data:text/javascript;base64," +
114
+ Buffer.from(source + `\n// isolated fixture ${moduleId++}`).toString("base64"));
115
+ const indexed = await load(code);
116
+ const original = await load(scan);
117
+ for (const pathname of paths.flatMap((path) => [
118
+ path,
119
+ `/de${path}`,
120
+ ])) {
121
+ for (const asObject of [false, true]) {
122
+ const href = `https://user:pass@example.com${pathname}?redirect=%2Faccount#section`;
123
+ const input = asObject ? new URL(href) : href;
124
+ const operations = [
125
+ (runtime) => runtime.localizeUrl(input, { locale: "de" }),
126
+ (runtime) => runtime.localizeUrl(input, { locale: "fr" }),
127
+ (runtime) => runtime.deLocalizeUrl(input),
128
+ (runtime) => runtime.extractLocaleFromUrl(input),
129
+ (runtime) => runtime.findMatchingRouteStrategy(input),
130
+ (runtime) => runtime.generateStaticLocalizedUrls([input]),
131
+ ];
132
+ for (const operation of operations) {
133
+ expect(outcome(() => operation(indexed)), `${pattern}, slash=${trailingSlash}, catchAllFirst=${catchAllFirst}, ${href}`).toEqual(outcome(() => operation(original)));
134
+ comparisons++;
135
+ }
136
+ }
137
+ }
138
+ }
139
+ }
140
+ }
141
+ expect(comparisons).toBe(31104);
142
+ }
143
+ finally {
144
+ Object.defineProperty(globalThis, "URLPattern", {
145
+ configurable: true,
146
+ writable: true,
147
+ value: previous,
148
+ });
149
+ }
150
+ }, 30000);
151
+ }
152
+ //# sourceMappingURL=url-pattern-index.differential.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-pattern-index.differential.test.js","sourceRoot":"","sources":["../../../src/compiler/runtime/url-pattern-index.differential.test.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AACtC,OAAO,EAAE,UAAU,IAAI,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,MAAM,OAAO,GAAG,CAAC,kBAAkD,CAAC,CAAC;AACrE,MAAM,gBAAgB,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,YAAY,CAEjD,CAAC;AACb,IAAI,gBAAgB,IAAI,gBAAgB,KAAK,kBAAkB,EAAE,CAAC;IACjE,OAAO,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;AAChC,CAAC;AACD,IAAI,QAAQ,GAAG,CAAC,CAAC;AAEjB,MAAM,QAAQ,GAAG;IAChB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,iBAAiB;IACjB,qBAAqB;IACrB,oBAAoB;IACpB,kBAAkB;IAClB,wBAAwB;IACxB,iBAAiB;IACjB,sBAAsB;IACtB,qBAAqB;IACrB,0BAA0B;IAC1B,iBAAiB;IACjB,yBAAyB;IACzB,mCAAmC;IACnC,eAAe;IACf,sBAAsB;IACtB,mBAAmB;CACnB,CAAC;AACF,MAAM,KAAK,GAAG;IACb,GAAG;IACH,UAAU;IACV,WAAW;IACX,kBAAkB;IAClB,gBAAgB;IAChB,cAAc;IACd,wBAAwB;IACxB,sBAAsB;IACtB,iBAAiB;IACjB,0BAA0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EAAE,EAAE,CAC3B,OAAO,CAAC,yBAAyB,CAAC,KAAK,CAAC;oCACzC,CAAC,OAAuB,EAAE,EAAE,CAC3B,OAAO,CAAC,2BAA2B,CAAC,CAAC,KAAK,CAAC,CAAC;iCAC7C,CAAC;gCACF,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;oCACpC,MAAM,CACL,OAAO,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EACjC,GAAG,OAAO,WAAW,aAAa,mBAAmB,aAAa,KAAK,IAAI,EAAE,CAC7E,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;oCAC9C,WAAW,EAAE,CAAC;gCACf,CAAC;4BACF,CAAC;wBACF,CAAC;oBACF,CAAC;gBACF,CAAC;YACF,CAAC;YACD,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC;gBAAS,CAAC;YACV,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,YAAY,EAAE;gBAC/C,YAAY,EAAE,IAAI;gBAClB,QAAQ,EAAE,IAAI;gBACd,KAAK,EAAE,QAAQ;aACf,CAAC,CAAC;QACJ,CAAC;IACF,CAAC,EAAE,KAAK,CAAC,CAAC;AACX,CAAC","sourcesContent":["import { expect, test } from \"vitest\";\nimport { URLPattern as PolyfillURLPattern } from \"urlpattern-polyfill\";\nimport { createRuntimeFile } from \"./create-runtime.js\";\nimport { defaultCompilerOptions } from \"../compiler-options.js\";\n\nconst engines = [PolyfillURLPattern as unknown as typeof URLPattern];\nconst nativeURLPattern = Reflect.get(globalThis, \"URLPattern\") as\n\t| typeof URLPattern\n\t| undefined;\nif (nativeURLPattern && nativeURLPattern !== PolyfillURLPattern) {\n\tengines.push(nativeURLPattern);\n}\nlet moduleId = 0;\n\nconst patterns = [\n\t\"/section/:slug\",\n\t\"/section/:slug?\",\n\t\"/section/:slug*\",\n\t\"/section/:slug+\",\n\t\"/section/:slug(.*)?\",\n\t\"/section/:slug(.*)\",\n\t\"/section/literal\",\n\t\"/section/:slug/details\",\n\t\"/section/:a/:b?\",\n\t\"/section/:slug(\\\\d+)\",\n\t\"/section/{literal}?\",\n\t\"/section%2Fliteral/:slug\",\n\t\"/section//:slug\",\n\t\"/section/../other/:slug\",\n\t\"https://example.com/section/:slug\",\n\t\"section/:slug\",\n\t\"/section/:slug/:slug\",\n\t\"/section/:slug([)\",\n];\nconst paths = [\n\t\"/\",\n\t\"/section\",\n\t\"/section/\",\n\t\"/section/literal\",\n\t\"/section/story\",\n\t\"/section/123\",\n\t\"/section/story/details\",\n\t\"/section/story/other\",\n\t\"/section//story\",\n\t\"/section%2Fliteral/story\",\n\t\"/other/story\",\n\t\"/unknown\",\n];\n\nfunction outcome(fn: () => unknown) {\n\ttry {\n\t\tconst result = fn();\n\t\treturn {\n\t\t\tvalue:\n\t\t\t\tresult instanceof URL\n\t\t\t\t\t? result.href\n\t\t\t\t\t: Array.isArray(result)\n\t\t\t\t\t\t? result.map((url) => url.href)\n\t\t\t\t\t\t: result,\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\terror:\n\t\t\t\terror instanceof Error ? [error.name, error.message] : String(error),\n\t\t};\n\t}\n}\n\nfor (const ctor of engines) {\n\ttest(`${ctor === PolyfillURLPattern ? \"polyfill\" : \"native\"} candidate index agrees with native ordered scans`, async () => {\n\t\tconst previous = Reflect.get(globalThis, \"URLPattern\");\n\t\tObject.defineProperty(globalThis, \"URLPattern\", {\n\t\t\tconfigurable: true,\n\t\t\twritable: true,\n\t\t\tvalue: ctor,\n\t\t});\n\t\tlet comparisons = 0;\n\t\ttry {\n\t\t\tfor (const pattern of patterns) {\n\t\t\t\tfor (const trailingSlash of [undefined, \"always\", \"never\"] as const) {\n\t\t\t\t\tfor (const catchAllFirst of [false, true]) {\n\t\t\t\t\t\tconst specific = {\n\t\t\t\t\t\t\tpattern,\n\t\t\t\t\t\t\tlocalized: [\n\t\t\t\t\t\t\t\t[\"en\", pattern],\n\t\t\t\t\t\t\t\t[\"de\", `/de${pattern}`],\n\t\t\t\t\t\t\t] as Array<[string, string]>,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst catchAll = {\n\t\t\t\t\t\t\tpattern: \"/:path(.*)?\",\n\t\t\t\t\t\t\tlocalized: [\n\t\t\t\t\t\t\t\t[\"de\", \"/de/:path(.*)?\"],\n\t\t\t\t\t\t\t\t[\"en\", \"/:path(.*)?\"],\n\t\t\t\t\t\t\t] as Array<[string, string]>,\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst code = createRuntimeFile({\n\t\t\t\t\t\t\tbaseLocale: \"en\",\n\t\t\t\t\t\t\tlocales: [\"en\", \"de\", \"fr\"],\n\t\t\t\t\t\t\tcompilerOptions: {\n\t\t\t\t\t\t\t\t...defaultCompilerOptions,\n\t\t\t\t\t\t\t\tstrategy: [\"url\", \"baseLocale\"],\n\t\t\t\t\t\t\t\ttrailingSlash,\n\t\t\t\t\t\t\t\turlPatterns: catchAllFirst\n\t\t\t\t\t\t\t\t\t? [catchAll, specific]\n\t\t\t\t\t\t\t\t\t: [specific, catchAll],\n\t\t\t\t\t\t\t\trouteStrategies: [\n\t\t\t\t\t\t\t\t\t{ match: pattern, exclude: true },\n\t\t\t\t\t\t\t\t\t{ match: \"/:path(.*)?\", strategy: [\"url\"] },\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}).replace(\n\t\t\t\t\t\t\t'import \"@inlang/paraglide-js/urlpattern-polyfill\";',\n\t\t\t\t\t\t\t\"\"\n\t\t\t\t\t\t);\n\t\t\t\t\t\t// The reference keeps native construction/matching and all filling\n\t\t\t\t\t\t// logic, but enumerates the original arrays without pruning.\n\t\t\t\t\t\tconst scan = code\n\t\t\t\t\t\t\t.replace(\n\t\t\t\t\t\t\t\t\"return patternCandidates(urlPatternIndex, url, urlPatterns);\",\n\t\t\t\t\t\t\t\t\"return urlPatterns;\"\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.replace(\n\t\t\t\t\t\t\t\t\"return patternCandidates(routeStrategyIndex, url, routeStrategies);\",\n\t\t\t\t\t\t\t\t\"return routeStrategies;\"\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\texpect(scan).not.toBe(code);\n\t\t\t\t\t\texpect(scan).not.toContain(\"return patternCandidates(\");\n\t\t\t\t\t\tconst load = (source: string) =>\n\t\t\t\t\t\t\timport(\n\t\t\t\t\t\t\t\t/* @vite-ignore */ \"data:text/javascript;base64,\" +\n\t\t\t\t\t\t\t\t\tBuffer.from(\n\t\t\t\t\t\t\t\t\t\tsource + `\\n// isolated fixture ${moduleId++}`\n\t\t\t\t\t\t\t\t\t).toString(\"base64\")\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tconst indexed = await load(code);\n\t\t\t\t\t\tconst original = await load(scan);\n\t\t\t\t\t\tfor (const pathname of paths.flatMap((path) => [\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\t`/de${path}`,\n\t\t\t\t\t\t])) {\n\t\t\t\t\t\t\tfor (const asObject of [false, true]) {\n\t\t\t\t\t\t\t\tconst href = `https://user:pass@example.com${pathname}?redirect=%2Faccount#section`;\n\t\t\t\t\t\t\t\tconst input = asObject ? new URL(href) : href;\n\t\t\t\t\t\t\t\tconst operations = [\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) =>\n\t\t\t\t\t\t\t\t\t\truntime.localizeUrl(input, { locale: \"de\" }),\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) =>\n\t\t\t\t\t\t\t\t\t\truntime.localizeUrl(input, { locale: \"fr\" }),\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) => runtime.deLocalizeUrl(input),\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) =>\n\t\t\t\t\t\t\t\t\t\truntime.extractLocaleFromUrl(input),\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) =>\n\t\t\t\t\t\t\t\t\t\truntime.findMatchingRouteStrategy(input),\n\t\t\t\t\t\t\t\t\t(runtime: typeof indexed) =>\n\t\t\t\t\t\t\t\t\t\truntime.generateStaticLocalizedUrls([input]),\n\t\t\t\t\t\t\t\t];\n\t\t\t\t\t\t\t\tfor (const operation of operations) {\n\t\t\t\t\t\t\t\t\texpect(\n\t\t\t\t\t\t\t\t\t\toutcome(() => operation(indexed)),\n\t\t\t\t\t\t\t\t\t\t`${pattern}, slash=${trailingSlash}, catchAllFirst=${catchAllFirst}, ${href}`\n\t\t\t\t\t\t\t\t\t).toEqual(outcome(() => operation(original)));\n\t\t\t\t\t\t\t\t\tcomparisons++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\texpect(comparisons).toBe(31104);\n\t\t} finally {\n\t\t\tObject.defineProperty(globalThis, \"URLPattern\", {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true,\n\t\t\t\tvalue: previous,\n\t\t\t});\n\t\t}\n\t}, 30000);\n}\n"]}
@@ -0,0 +1,168 @@
1
+ import { urlPatterns, routeStrategies } from "./variables.js";
2
+ /** @typedef {{ children: Map<string, PrefixNode>, ranks: Set<number> }} PrefixNode */
3
+ /** @typedef {{ items: any[], snapshots: any[], root: PrefixNode }} PatternIndex */
4
+ /** @type {PatternIndex | undefined} */
5
+ let urlPatternIndex;
6
+ /** @type {PatternIndex | undefined} */
7
+ let routeStrategyIndex;
8
+ let routingConfigVersion = 0;
9
+ /**
10
+ * Validate the public mutable configuration before reusing derived routing data.
11
+ * String/reference comparisons intentionally remain O(n): they preserve edits
12
+ * through retained array/object references without changing the public objects.
13
+ * Native matching of unrelated routes is the expensive work this index avoids.
14
+ * @returns {number}
15
+ */
16
+ export function getRoutingConfigVersion() {
17
+ if (!indexIsCurrent(urlPatternIndex, urlPatterns, false)) {
18
+ urlPatternIndex = buildPatternIndex(urlPatterns, false);
19
+ routingConfigVersion++;
20
+ }
21
+ if (!indexIsCurrent(routeStrategyIndex, routeStrategies, true)) {
22
+ routeStrategyIndex = buildPatternIndex(routeStrategies, true);
23
+ routingConfigVersion++;
24
+ }
25
+ return routingConfigVersion;
26
+ }
27
+ /** @returns {number} */
28
+ export function currentRoutingConfigVersion() {
29
+ return routingConfigVersion;
30
+ }
31
+ /** @param {URL} url @returns {typeof urlPatterns} */
32
+ export function getUrlPatternCandidates(url) {
33
+ getRoutingConfigVersion();
34
+ return patternCandidates(urlPatternIndex, url, urlPatterns);
35
+ }
36
+ /** @param {URL} url @returns {typeof routeStrategies} */
37
+ export function getRouteStrategyCandidates(url) {
38
+ getRoutingConfigVersion();
39
+ return patternCandidates(routeStrategyIndex, url, routeStrategies);
40
+ }
41
+ /**
42
+ * Only a complete, conservative root-relative grammar is eligible. Unknown
43
+ * syntax stays unconditional, including invalid patterns whose constructor
44
+ * errors must remain observable. Stop indexing at the first dynamic segment.
45
+ * @param {string} pattern
46
+ * @returns {string[]}
47
+ */
48
+ function mandatoryPathSegments(pattern) {
49
+ if (typeof pattern !== "string" ||
50
+ !pattern.startsWith("/") ||
51
+ pattern.startsWith("//"))
52
+ return [];
53
+ const segments = pattern.slice(1).split("/");
54
+ const names = new Set();
55
+ const literal = /^[A-Za-z0-9_-]+$/;
56
+ const parameter = /^:([A-Za-z_][A-Za-z0-9_]*)(?:[?*+]|\(\.\*\)\??)?$/;
57
+ for (let i = 0; i < segments.length; i++) {
58
+ const segment = segments[i] ?? "";
59
+ if (segment === "" && i === segments.length - 1)
60
+ continue;
61
+ if (literal.test(segment))
62
+ continue;
63
+ const match = parameter.exec(segment);
64
+ if (!match || names.has(match[1]))
65
+ return [];
66
+ names.add(match[1]);
67
+ }
68
+ const prefix = [];
69
+ for (const segment of segments) {
70
+ if (!literal.test(segment))
71
+ break;
72
+ prefix.push(segment);
73
+ }
74
+ return prefix;
75
+ }
76
+ /** @param {PatternIndex | undefined} index @param {any[]} items @param {boolean} policies */
77
+ function indexIsCurrent(index, items, policies) {
78
+ if (!index ||
79
+ index.items !== items ||
80
+ index.snapshots.length !== items.length)
81
+ return false;
82
+ for (let i = 0; i < items.length; i++) {
83
+ const item = items[i];
84
+ const saved = index.snapshots[i];
85
+ if (item !== saved.item ||
86
+ (policies ? item?.match : item?.pattern) !== saved.pattern)
87
+ return false;
88
+ if (policies)
89
+ continue;
90
+ const localized = item?.localized;
91
+ if (!Array.isArray(localized) ||
92
+ saved.localized !== localized ||
93
+ saved.entries.length !== localized.length)
94
+ return false;
95
+ for (let j = 0; j < localized.length; j++) {
96
+ const entry = localized[j];
97
+ const previous = saved.entries[j];
98
+ if (entry !== previous.entry ||
99
+ entry?.[0] !== previous.locale ||
100
+ entry?.[1] !== previous.pattern)
101
+ return false;
102
+ }
103
+ }
104
+ return true;
105
+ }
106
+ /** @param {any[]} items @param {boolean} policies @returns {PatternIndex} */
107
+ function buildPatternIndex(items, policies) {
108
+ /** @type {PrefixNode} */
109
+ const root = { children: new Map(), ranks: new Set() };
110
+ const snapshots = [];
111
+ for (let rank = 0; rank < items.length; rank++) {
112
+ const item = items[rank];
113
+ const pattern = policies ? item?.match : item?.pattern;
114
+ const localized = policies ? undefined : item?.localized;
115
+ const entries = Array.isArray(localized)
116
+ ? Array.from(localized, (entry) => ({
117
+ entry,
118
+ locale: entry?.[0],
119
+ pattern: entry?.[1],
120
+ }))
121
+ : [];
122
+ snapshots.push({ item, pattern, localized, entries });
123
+ const paths = [pattern, ...entries.map((entry) => entry.pattern)].map(mandatoryPathSegments);
124
+ // A malformed element must also remain in the original native scan.
125
+ if ((!policies &&
126
+ (!Array.isArray(localized) ||
127
+ entries.some(({ entry }) => !Array.isArray(entry)))) ||
128
+ paths.some((path) => path.length === 0)) {
129
+ root.ranks.add(rank);
130
+ continue;
131
+ }
132
+ for (const path of paths) {
133
+ let node = root;
134
+ for (const segment of path) {
135
+ let child = node.children.get(segment);
136
+ if (!child) {
137
+ child = { children: new Map(), ranks: new Set() };
138
+ node.children.set(segment, child);
139
+ }
140
+ node = child;
141
+ }
142
+ node.ranks.add(rank);
143
+ }
144
+ }
145
+ return { items, snapshots, root };
146
+ }
147
+ /** @param {PatternIndex | undefined} index @param {URL} url @param {any[]} items @returns {any[]} */
148
+ function patternCandidates(index, url, items) {
149
+ // Root-relative constructor/base behavior for other schemes is deliberately
150
+ // left to URLPattern, as are configurations with no prunable prefixes.
151
+ if (!index ||
152
+ !/^https?:$/.test(url.protocol) ||
153
+ index.root.ranks.size === items.length)
154
+ return items;
155
+ const ranks = new Set(index.root.ranks);
156
+ let node = index.root;
157
+ for (const segment of url.pathname.slice(1).split("/")) {
158
+ const child = node.children.get(segment);
159
+ if (!child)
160
+ break;
161
+ node = child;
162
+ for (const rank of node.ranks)
163
+ ranks.add(rank);
164
+ }
165
+ // Specificity must never change precedence, including unconditional patterns.
166
+ return [...ranks].sort((a, b) => a - b).map((rank) => items[rank]);
167
+ }
168
+ //# sourceMappingURL=url-pattern-index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url-pattern-index.js","sourceRoot":"","sources":["../../../src/compiler/runtime/url-pattern-index.js"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAE9D,sFAAsF;AACtF,mFAAmF;AAEnF,uCAAuC;AACvC,IAAI,eAAe,CAAC;AACpB,uCAAuC;AACvC,IAAI,kBAAkB,CAAC;AACvB,IAAI,oBAAoB,GAAG,CAAC,CAAC;AAE7B;;;;;;GAMG;AACH,MAAM,UAAU,uBAAuB;IACtC,IAAI,CAAC,cAAc,CAAC,eAAe,EAAE,WAAW,EAAE,KAAK,CAAC,EAAE,CAAC;QAC1D,eAAe,GAAG,iBAAiB,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC;QACxD,oBAAoB,EAAE,CAAC;IACxB,CAAC;IACD,IAAI,CAAC,cAAc,CAAC,kBAAkB,EAAE,eAAe,EAAE,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AC;IAChD,CAAC;IACD,8EAA8E;IAC9E,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { urlPatterns, routeStrategies } from \"./variables.js\";\n\n/** @typedef {{ children: Map<string, PrefixNode>, ranks: Set<number> }} PrefixNode */\n/** @typedef {{ items: any[], snapshots: any[], root: PrefixNode }} PatternIndex */\n\n/** @type {PatternIndex | undefined} */\nlet urlPatternIndex;\n/** @type {PatternIndex | undefined} */\nlet routeStrategyIndex;\nlet routingConfigVersion = 0;\n\n/**\n * Validate the public mutable configuration before reusing derived routing data.\n * String/reference comparisons intentionally remain O(n): they preserve edits\n * through retained array/object references without changing the public objects.\n * Native matching of unrelated routes is the expensive work this index avoids.\n * @returns {number}\n */\nexport function getRoutingConfigVersion() {\n\tif (!indexIsCurrent(urlPatternIndex, urlPatterns, false)) {\n\t\turlPatternIndex = buildPatternIndex(urlPatterns, false);\n\t\troutingConfigVersion++;\n\t}\n\tif (!indexIsCurrent(routeStrategyIndex, routeStrategies, true)) {\n\t\trouteStrategyIndex = buildPatternIndex(routeStrategies, true);\n\t\troutingConfigVersion++;\n\t}\n\treturn routingConfigVersion;\n}\n\n/** @returns {number} */\nexport function currentRoutingConfigVersion() {\n\treturn routingConfigVersion;\n}\n\n/** @param {URL} url @returns {typeof urlPatterns} */\nexport function getUrlPatternCandidates(url) {\n\tgetRoutingConfigVersion();\n\treturn patternCandidates(urlPatternIndex, url, urlPatterns);\n}\n\n/** @param {URL} url @returns {typeof routeStrategies} */\nexport function getRouteStrategyCandidates(url) {\n\tgetRoutingConfigVersion();\n\treturn patternCandidates(routeStrategyIndex, url, routeStrategies);\n}\n\n/**\n * Only a complete, conservative root-relative grammar is eligible. Unknown\n * syntax stays unconditional, including invalid patterns whose constructor\n * errors must remain observable. Stop indexing at the first dynamic segment.\n * @param {string} pattern\n * @returns {string[]}\n */\nfunction mandatoryPathSegments(pattern) {\n\tif (\n\t\ttypeof pattern !== \"string\" ||\n\t\t!pattern.startsWith(\"/\") ||\n\t\tpattern.startsWith(\"//\")\n\t)\n\t\treturn [];\n\tconst segments = pattern.slice(1).split(\"/\");\n\tconst names = new Set();\n\tconst literal = /^[A-Za-z0-9_-]+$/;\n\tconst parameter = /^:([A-Za-z_][A-Za-z0-9_]*)(?:[?*+]|\\(\\.\\*\\)\\??)?$/;\n\tfor (let i = 0; i < segments.length; i++) {\n\t\tconst segment = segments[i] ?? \"\";\n\t\tif (segment === \"\" && i === segments.length - 1) continue;\n\t\tif (literal.test(segment)) continue;\n\t\tconst match = parameter.exec(segment);\n\t\tif (!match || names.has(match[1])) return [];\n\t\tnames.add(match[1]);\n\t}\n\tconst prefix = [];\n\tfor (const segment of segments) {\n\t\tif (!literal.test(segment)) break;\n\t\tprefix.push(segment);\n\t}\n\treturn prefix;\n}\n\n/** @param {PatternIndex | undefined} index @param {any[]} items @param {boolean} policies */\nfunction indexIsCurrent(index, items, policies) {\n\tif (\n\t\t!index ||\n\t\tindex.items !== items ||\n\t\tindex.snapshots.length !== items.length\n\t)\n\t\treturn false;\n\tfor (let i = 0; i < items.length; i++) {\n\t\tconst item = items[i];\n\t\tconst saved = index.snapshots[i];\n\t\tif (\n\t\t\titem !== saved.item ||\n\t\t\t(policies ? item?.match : item?.pattern) !== saved.pattern\n\t\t)\n\t\t\treturn false;\n\t\tif (policies) continue;\n\t\tconst localized = item?.localized;\n\t\tif (\n\t\t\t!Array.isArray(localized) ||\n\t\t\tsaved.localized !== localized ||\n\t\t\tsaved.entries.length !== localized.length\n\t\t)\n\t\t\treturn false;\n\t\tfor (let j = 0; j < localized.length; j++) {\n\t\t\tconst entry = localized[j];\n\t\t\tconst previous = saved.entries[j];\n\t\t\tif (\n\t\t\t\tentry !== previous.entry ||\n\t\t\t\tentry?.[0] !== previous.locale ||\n\t\t\t\tentry?.[1] !== previous.pattern\n\t\t\t)\n\t\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\n/** @param {any[]} items @param {boolean} policies @returns {PatternIndex} */\nfunction buildPatternIndex(items, policies) {\n\t/** @type {PrefixNode} */\n\tconst root = { children: new Map(), ranks: new Set() };\n\tconst snapshots = [];\n\tfor (let rank = 0; rank < items.length; rank++) {\n\t\tconst item = items[rank];\n\t\tconst pattern = policies ? item?.match : item?.pattern;\n\t\tconst localized = policies ? undefined : item?.localized;\n\t\tconst entries = Array.isArray(localized)\n\t\t\t? Array.from(localized, (entry) => ({\n\t\t\t\t\tentry,\n\t\t\t\t\tlocale: entry?.[0],\n\t\t\t\t\tpattern: entry?.[1],\n\t\t\t\t}))\n\t\t\t: [];\n\t\tsnapshots.push({ item, pattern, localized, entries });\n\t\tconst paths = [pattern, ...entries.map((entry) => entry.pattern)].map(\n\t\t\tmandatoryPathSegments\n\t\t);\n\t\t// A malformed element must also remain in the original native scan.\n\t\tif (\n\t\t\t(!policies &&\n\t\t\t\t(!Array.isArray(localized) ||\n\t\t\t\t\tentries.some(({ entry }) => !Array.isArray(entry)))) ||\n\t\t\tpaths.some((path) => path.length === 0)\n\t\t) {\n\t\t\troot.ranks.add(rank);\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const path of paths) {\n\t\t\tlet node = root;\n\t\t\tfor (const segment of path) {\n\t\t\t\tlet child = node.children.get(segment);\n\t\t\t\tif (!child) {\n\t\t\t\t\tchild = { children: new Map(), ranks: new Set() };\n\t\t\t\t\tnode.children.set(segment, child);\n\t\t\t\t}\n\t\t\t\tnode = child;\n\t\t\t}\n\t\t\tnode.ranks.add(rank);\n\t\t}\n\t}\n\treturn { items, snapshots, root };\n}\n\n/** @param {PatternIndex | undefined} index @param {URL} url @param {any[]} items @returns {any[]} */\nfunction patternCandidates(index, url, items) {\n\t// Root-relative constructor/base behavior for other schemes is deliberately\n\t// left to URLPattern, as are configurations with no prunable prefixes.\n\tif (\n\t\t!index ||\n\t\t!/^https?:$/.test(url.protocol) ||\n\t\tindex.root.ranks.size === items.length\n\t)\n\t\treturn items;\n\tconst ranks = new Set(index.root.ranks);\n\tlet node = index.root;\n\tfor (const segment of url.pathname.slice(1).split(\"/\")) {\n\t\tconst child = node.children.get(segment);\n\t\tif (!child) break;\n\t\tnode = child;\n\t\tfor (const rank of node.ranks) ranks.add(rank);\n\t}\n\t// Specificity must never change precedence, including unconditional patterns.\n\treturn [...ranks].sort((a, b) => a - b).map((rank) => items[rank]);\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,262 @@
1
+ import { expect, test } from "vitest";
2
+ import { URLPattern as PolyfillURLPattern } from "urlpattern-polyfill";
3
+ import { createParaglide } from "../create-paraglide.js";
4
+ import { newProject } from "@inlang/sdk";
5
+ const nativeURLPattern = Reflect.get(globalThis, "URLPattern");
6
+ const engines = [];
7
+ let runtimeModuleNonce = 0;
8
+ if (typeof nativeURLPattern === "function" &&
9
+ nativeURLPattern !== PolyfillURLPattern) {
10
+ engines.push(["native", nativeURLPattern]);
11
+ }
12
+ engines.push(["polyfill", PolyfillURLPattern]);
13
+ async function withURLPattern(ctor, fn) {
14
+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "URLPattern");
15
+ Object.defineProperty(globalThis, "URLPattern", {
16
+ configurable: true,
17
+ writable: true,
18
+ value: ctor,
19
+ });
20
+ try {
21
+ return await fn();
22
+ }
23
+ finally {
24
+ if (descriptor) {
25
+ Object.defineProperty(globalThis, "URLPattern", descriptor);
26
+ }
27
+ else {
28
+ Reflect.deleteProperty(globalThis, "URLPattern");
29
+ }
30
+ }
31
+ }
32
+ async function withRuntime(options, ctor, fn) {
33
+ return withURLPattern(ctor, async () => fn(await createParaglide({
34
+ blob: await newProject({
35
+ settings: { baseLocale: "en", locales: ["en", "de"] },
36
+ }),
37
+ cookieName: `pattern-index-test-${runtimeModuleNonce++}`,
38
+ strategy: ["url", "baseLocale"],
39
+ ...options,
40
+ })));
41
+ }
42
+ for (const [engineName, ctor] of engines) {
43
+ test(`${engineName} URLPattern keeps ordered routing and URL parts`, async () => {
44
+ await withRuntime({
45
+ urlPatterns: [
46
+ {
47
+ pattern: "/specific-path",
48
+ localized: [
49
+ ["en", "/specific-path"],
50
+ ["de", "/de/404"],
51
+ ],
52
+ },
53
+ {
54
+ pattern: "/:path(.*)?",
55
+ localized: [
56
+ ["en", "/:path(.*)?"],
57
+ ["de", "/de/:path(.*)?"],
58
+ ],
59
+ },
60
+ ],
61
+ routeStrategies: [
62
+ { match: "/specific-path", exclude: true },
63
+ { match: "/:path(.*)?", strategy: ["url"] },
64
+ ],
65
+ }, ctor, async (runtime) => {
66
+ const input = "https://alice:secret@example.com/specific-path?redirect=%2Faccount#section";
67
+ expect(runtime.localizeUrl(input, { locale: "de" }).href).toBe("https://alice:secret@example.com/de/404?redirect=%2Faccount#section");
68
+ expect(runtime.deLocalizeUrl("https://alice:secret@example.com/de/404?redirect=%2Faccount#section").href).toBe("https://alice:secret@example.com/specific-path?redirect=%2Faccount#section");
69
+ expect(runtime.extractLocaleFromUrl(input)).toBe("en");
70
+ expect(runtime.isExcludedByRouteStrategy("https://example.com/specific-path")).toBe(true);
71
+ expect(runtime.getStrategyForUrl("https://example.com/other")).toEqual([
72
+ "url",
73
+ ]);
74
+ expect(runtime
75
+ .generateStaticLocalizedUrls(["https://example.com/specific-path"])
76
+ .map((url) => url.href)).toEqual([
77
+ "https://example.com/specific-path",
78
+ "https://example.com/de/404",
79
+ ]);
80
+ });
81
+ });
82
+ test(`${engineName} URLPattern refreshes ordered indexes and same-URL caches after edits`, async () => {
83
+ await withRuntime({
84
+ urlPatterns: [
85
+ {
86
+ pattern: "/:path(.*)?",
87
+ localized: [
88
+ ["en", "/:path(.*)?"],
89
+ ["de", "/de/:path(.*)?"],
90
+ ],
91
+ },
92
+ ],
93
+ routeStrategies: [{ match: "/old/:slug", exclude: true }],
94
+ }, ctor, async (runtime) => {
95
+ const url = "https://example.com/old/story";
96
+ expect(runtime.extractLocaleFromUrl(url)).toBe("en");
97
+ expect(runtime.localizeUrl(url, { locale: "de" }).pathname).toBe("/de/old/story");
98
+ expect(runtime.isExcludedByRouteStrategy(url)).toBe(true);
99
+ const pattern = runtime.urlPatterns[0];
100
+ pattern.pattern = "/new/:path(.*)?";
101
+ pattern.localized[0][1] = "/new/:path(.*)?";
102
+ pattern.localized[1][1] = "/de/new/:path(.*)?";
103
+ runtime.routeStrategies[0].match = "/new/:slug";
104
+ // Reuse the exact href so both one-entry result caches must notice
105
+ // the config version change and the fast-path parse must be refreshed.
106
+ expect(runtime.extractLocaleFromUrl(url)).toBe(undefined);
107
+ expect(runtime.localizeUrl(url, { locale: "de" }).href).toBe(url);
108
+ expect(runtime.isExcludedByRouteStrategy(url)).toBe(false);
109
+ expect(runtime.localizeUrl("https://example.com/new/story", { locale: "de" })
110
+ .pathname).toBe("/de/new/story");
111
+ });
112
+ });
113
+ test(`${engineName} URLPattern refreshes warmed winners after collection and reference edits`, async () => {
114
+ await withRuntime({
115
+ urlPatterns: [
116
+ {
117
+ pattern: "/same/:slug",
118
+ localized: [["de", "/same/:slug"]],
119
+ },
120
+ ],
121
+ routeStrategies: [{ match: "/same/:slug", strategy: ["url"] }],
122
+ }, ctor, async (runtime) => {
123
+ const url = "https://example.com/same/story";
124
+ expect(runtime.extractLocaleFromUrl(url)).toBe("de");
125
+ expect(runtime.getStrategyForUrl(url)).toEqual(["url"]);
126
+ // A pushed earlier pattern changes the extraction winner. Splicing it
127
+ // back out must restore the original winner on this same cached URL.
128
+ runtime.urlPatterns.unshift({
129
+ pattern: "/same/:slug",
130
+ localized: [["en", "/same/:slug"]],
131
+ });
132
+ expect(runtime.extractLocaleFromUrl(url)).toBe("en");
133
+ runtime.urlPatterns.splice(0, 1);
134
+ expect(runtime.extractLocaleFromUrl(url)).toBe("de");
135
+ // Replacing the localized array and its locale string changes the
136
+ // first matching locale even though its pattern text is unchanged.
137
+ const entry = runtime.urlPatterns[0];
138
+ entry.localized = [["en", "/same/:slug"]];
139
+ expect(runtime.extractLocaleFromUrl(url)).toBe("en");
140
+ // Replacing a strategy object with the same match string must refresh
141
+ // the warmed rule result as well as the candidate index snapshot.
142
+ runtime.routeStrategies[0] = {
143
+ match: "/same/:slug",
144
+ strategy: ["baseLocale"],
145
+ };
146
+ expect(runtime.getStrategyForUrl(url)).toEqual(["baseLocale"]);
147
+ });
148
+ });
149
+ test(`${engineName} URLPattern keeps invalid-pattern errors ahead of later matches`, async () => {
150
+ await withRuntime({
151
+ urlPatterns: [
152
+ { pattern: "/broken/:id(", localized: [] },
153
+ {
154
+ pattern: "/valid/:id",
155
+ localized: [
156
+ ["en", "/valid/:id"],
157
+ ["de", "/de/valid/:id"],
158
+ ],
159
+ },
160
+ ],
161
+ }, ctor, async (runtime) => {
162
+ expect(() => runtime.localizeUrl("https://example.com/valid/7", { locale: "de" })).toThrow();
163
+ });
164
+ });
165
+ test(`${engineName} URLPattern keeps malformed localized entries unconditional`, async () => {
166
+ await withRuntime({ urlPatterns: [] }, ctor, async (runtime) => {
167
+ runtime.urlPatterns.push({
168
+ pattern: "/unrelated/:slug",
169
+ localized: [null],
170
+ });
171
+ // This route cannot be pruned by its path prefix: the original generic
172
+ // scan would encounter the malformed localized entry and throw.
173
+ expect(() => runtime.localizeUrl("https://example.com/elsewhere", { locale: "de" })).toThrow();
174
+ });
175
+ });
176
+ test(`${engineName} URLPattern preserves trailing-slash alias captures`, async () => {
177
+ await withRuntime({
178
+ trailingSlash: "always",
179
+ urlPatterns: [
180
+ {
181
+ pattern: "/:path(.*)",
182
+ localized: [
183
+ ["en", "/:path(.*)"],
184
+ ["de", "/de/:path(.*)/details"],
185
+ ],
186
+ },
187
+ ],
188
+ }, ctor, async (runtime) => {
189
+ expect(runtime.localizeUrl("https://example.com/foo", { locale: "de" }).href).toBe("https://example.com/de/foo/details/");
190
+ });
191
+ });
192
+ test(`${engineName} URLPattern keeps file-host bases separate`, async () => {
193
+ await withRuntime({
194
+ urlPatterns: [
195
+ {
196
+ pattern: "/section/:slug",
197
+ localized: [
198
+ ["en", "/section/:slug"],
199
+ ["de", "/de/section/:slug"],
200
+ ],
201
+ },
202
+ ],
203
+ routeStrategies: [{ match: "/section/:slug", exclude: true }],
204
+ }, ctor, async (runtime) => {
205
+ const first = new URL("file://server-one/section/story");
206
+ const second = new URL("file://server-two/section/story");
207
+ expect(runtime.extractLocaleFromUrl(first)).toBe("en");
208
+ expect(runtime.extractLocaleFromUrl(second)).toBe("en");
209
+ // Policy matching uses url.origin ("null" for both file hosts) as a
210
+ // URLPattern base and therefore retains the preexisting Invalid URL
211
+ // error. The locale extraction above exercises cache isolation safely.
212
+ });
213
+ });
214
+ }
215
+ for (const [engineName, ctor] of engines) {
216
+ test(`${engineName} URLPattern avoids unrelated late-route scans across APIs`, async () => {
217
+ let constructions = 0;
218
+ let executions = 0;
219
+ class CountingURLPattern extends ctor {
220
+ constructor(pattern, baseURL) {
221
+ if (baseURL === undefined)
222
+ super(pattern);
223
+ else
224
+ super(pattern, String(baseURL));
225
+ constructions++;
226
+ }
227
+ exec(input, baseURL) {
228
+ executions++;
229
+ return baseURL === undefined
230
+ ? super.exec(input)
231
+ : super.exec(input, baseURL);
232
+ }
233
+ }
234
+ const urlPatterns = Array.from({ length: 67 }, (_, index) => ({
235
+ pattern: `/route${index}/:slug`,
236
+ localized: [
237
+ ["en", `/route${index}/:slug`],
238
+ ["de", `/de/route${index}/:slug`],
239
+ ],
240
+ }));
241
+ const routeStrategies = Array.from({ length: 67 }, (_, index) => ({
242
+ match: `/route${index}/:slug`,
243
+ exclude: true,
244
+ }));
245
+ await withRuntime({ urlPatterns, routeStrategies }, CountingURLPattern, async (runtime) => {
246
+ expect(runtime.localizeUrl("https://example.com/route66/story", {
247
+ locale: "de",
248
+ }).pathname).toBe("/de/route66/story");
249
+ expect(runtime.deLocalizeUrl("https://example.com/de/route66/story").pathname).toBe("/route66/story");
250
+ expect(runtime.extractLocaleFromUrl("https://example.com/de/route66/story")).toBe("de");
251
+ expect(runtime.isExcludedByRouteStrategy("https://example.com/route66/story")).toBe(true);
252
+ expect(runtime
253
+ .generateStaticLocalizedUrls(["https://example.com/route66/story"])
254
+ .map((url) => url.pathname)).toEqual(["/route66/story", "/de/route66/story"]);
255
+ // Includes createParaglide's capability probe. URLPattern work across
256
+ // five APIs stays proportional to the few matching patterns, not 67.
257
+ expect(constructions).toBeLessThanOrEqual(4);
258
+ expect(executions).toBeLessThanOrEqual(20);
259
+ });
260
+ });
261
+ }
262
+ //# sourceMappingURL=url-pattern-index.test.js.map