@bleedingdev/modern-js-i18n-runtime-extensions 3.9.0-ultramodern.9 → 3.9.3-ultramodern.2

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 (104) hide show
  1. package/dist/cjs/index.js +10 -10
  2. package/dist/cjs/localeRedirectPolicy.js +6 -6
  3. package/dist/cjs/native.js +160 -0
  4. package/dist/cjs/paths.js +11 -3
  5. package/dist/cjs/requestLanguage.js +195 -0
  6. package/dist/cjs/router-navigation/adapter.js +93 -0
  7. package/dist/cjs/{localisedUrls/config.js → router-navigation/index.js} +5 -14
  8. package/dist/cjs/ssrLanguageHandoff.js +94 -0
  9. package/dist/cjs/urlRewrite.js +64 -0
  10. package/dist/esm/index.mjs +1 -1
  11. package/dist/esm/localeRedirectPolicy.mjs +1 -1
  12. package/dist/esm/native.mjs +112 -0
  13. package/dist/esm/paths.mjs +7 -2
  14. package/dist/esm/requestLanguage.mjs +148 -0
  15. package/dist/esm/router-navigation/adapter.mjs +55 -0
  16. package/dist/esm/router-navigation/index.mjs +1 -0
  17. package/dist/esm/ssrLanguageHandoff.mjs +44 -0
  18. package/dist/esm/urlRewrite.mjs +26 -0
  19. package/dist/esm-node/index.mjs +1 -1
  20. package/dist/esm-node/localeRedirectPolicy.mjs +1 -1
  21. package/dist/esm-node/native.mjs +113 -0
  22. package/dist/esm-node/paths.mjs +7 -2
  23. package/dist/esm-node/requestLanguage.mjs +149 -0
  24. package/dist/esm-node/router-navigation/adapter.mjs +56 -0
  25. package/dist/esm-node/router-navigation/index.mjs +2 -0
  26. package/dist/esm-node/ssrLanguageHandoff.mjs +45 -0
  27. package/dist/esm-node/urlRewrite.mjs +27 -0
  28. package/dist/types/index.d.ts +1 -1
  29. package/dist/types/localeRedirectPolicy.d.ts +1 -1
  30. package/dist/types/native.d.ts +21 -0
  31. package/dist/types/paths.d.ts +8 -1
  32. package/dist/types/requestLanguage.d.ts +60 -0
  33. package/dist/types/router-navigation/adapter.d.ts +23 -0
  34. package/dist/types/router-navigation/index.d.ts +1 -0
  35. package/dist/types/ssrLanguageHandoff.d.ts +60 -0
  36. package/dist/types/urlRewrite.d.ts +60 -0
  37. package/package.json +101 -14
  38. package/src/index.ts +1 -1
  39. package/src/localeRedirectPolicy.ts +2 -2
  40. package/src/native.ts +212 -0
  41. package/src/paths.ts +23 -2
  42. package/src/requestLanguage.ts +311 -0
  43. package/src/router-navigation/adapter.tsx +120 -0
  44. package/src/router-navigation/index.ts +6 -0
  45. package/src/ssrLanguageHandoff.ts +138 -0
  46. package/src/urlRewrite.ts +107 -0
  47. package/dist/cjs/localisedUrls/index.js +0 -98
  48. package/dist/cjs/localisedUrls/normalise.js +0 -87
  49. package/dist/cjs/localisedUrls/pathname.js +0 -68
  50. package/dist/cjs/localisedUrls/patterns.js +0 -214
  51. package/dist/cjs/localisedUrls/redirect.js +0 -100
  52. package/dist/cjs/localisedUrls/resolve.js +0 -78
  53. package/dist/cjs/localisedUrls/routeIdentity.js +0 -118
  54. package/dist/cjs/localisedUrls/routes.js +0 -210
  55. package/dist/cjs/localisedUrls/types.js +0 -18
  56. package/dist/esm/localisedUrls/config.mjs +0 -11
  57. package/dist/esm/localisedUrls/index.mjs +0 -8
  58. package/dist/esm/localisedUrls/normalise.mjs +0 -37
  59. package/dist/esm/localisedUrls/pathname.mjs +0 -24
  60. package/dist/esm/localisedUrls/patterns.mjs +0 -152
  61. package/dist/esm/localisedUrls/redirect.mjs +0 -53
  62. package/dist/esm/localisedUrls/resolve.mjs +0 -37
  63. package/dist/esm/localisedUrls/routeIdentity.mjs +0 -77
  64. package/dist/esm/localisedUrls/routes.mjs +0 -169
  65. package/dist/esm/localisedUrls/types.mjs +0 -0
  66. package/dist/esm-node/localisedUrls/config.mjs +0 -12
  67. package/dist/esm-node/localisedUrls/index.mjs +0 -9
  68. package/dist/esm-node/localisedUrls/normalise.mjs +0 -38
  69. package/dist/esm-node/localisedUrls/pathname.mjs +0 -25
  70. package/dist/esm-node/localisedUrls/patterns.mjs +0 -153
  71. package/dist/esm-node/localisedUrls/redirect.mjs +0 -54
  72. package/dist/esm-node/localisedUrls/resolve.mjs +0 -38
  73. package/dist/esm-node/localisedUrls/routeIdentity.mjs +0 -78
  74. package/dist/esm-node/localisedUrls/routes.mjs +0 -170
  75. package/dist/esm-node/localisedUrls/types.mjs +0 -1
  76. package/dist/types/localisedUrls/config.d.ts +0 -9
  77. package/dist/types/localisedUrls/index.d.ts +0 -10
  78. package/dist/types/localisedUrls/normalise.d.ts +0 -10
  79. package/dist/types/localisedUrls/pathname.d.ts +0 -4
  80. package/dist/types/localisedUrls/patterns.d.ts +0 -11
  81. package/dist/types/localisedUrls/redirect.d.ts +0 -19
  82. package/dist/types/localisedUrls/resolve.d.ts +0 -7
  83. package/dist/types/localisedUrls/routeIdentity.d.ts +0 -24
  84. package/dist/types/localisedUrls/routes.d.ts +0 -3
  85. package/dist/types/localisedUrls/types.d.ts +0 -14
  86. package/rslib.config.mts +0 -4
  87. package/rstest.config.mts +0 -36
  88. package/src/localisedUrls/config.ts +0 -18
  89. package/src/localisedUrls/index.ts +0 -28
  90. package/src/localisedUrls/normalise.ts +0 -62
  91. package/src/localisedUrls/pathname.ts +0 -60
  92. package/src/localisedUrls/patterns.ts +0 -283
  93. package/src/localisedUrls/redirect.ts +0 -107
  94. package/src/localisedUrls/resolve.ts +0 -106
  95. package/src/localisedUrls/routeIdentity.ts +0 -107
  96. package/src/localisedUrls/routes.ts +0 -432
  97. package/src/localisedUrls/types.ts +0 -18
  98. package/tests/languageSyncController.test.ts +0 -136
  99. package/tests/localeRedirectPolicy.test.ts +0 -173
  100. package/tests/localisedUrls.test.ts +0 -532
  101. package/tests/paths.test.ts +0 -24
  102. package/tests/reactLanguageSync.test.tsx +0 -136
  103. package/tests/tsconfig.json +0 -11
  104. package/tsconfig.json +0 -11
@@ -1,432 +0,0 @@
1
- import {
2
- getLeadingLocaleParam,
3
- normalisePathPattern,
4
- normaliseRoutePath,
5
- stripLeadingLocaleParam,
6
- } from './normalise';
7
- import {
8
- doPathPatternsOverlap,
9
- getOrderedPathParamSignature,
10
- getPathParamSignature,
11
- getPathPatternValidationIssue,
12
- getPhysicalPathPattern,
13
- haveEqualPatternSpecificity,
14
- } from './patterns';
15
- import type {
16
- LocalisedRoute,
17
- LocalisedUrlPathMap,
18
- LocalisedUrlsMap,
19
- } from './types';
20
-
21
- const isLocalisableRoutePath = (path?: string): path is string => {
22
- const pathWithoutLocale = stripLeadingLocaleParam(path);
23
-
24
- if (
25
- !pathWithoutLocale ||
26
- pathWithoutLocale === '/' ||
27
- pathWithoutLocale === '*'
28
- ) {
29
- return false;
30
- }
31
-
32
- return true;
33
- };
34
-
35
- const joinPath = (parentPath: string, routePath?: string): string => {
36
- if (!isLocalisableRoutePath(routePath)) {
37
- return parentPath;
38
- }
39
-
40
- const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
41
- return normalisePathPattern(`${parentPath}/${segment}`);
42
- };
43
-
44
- const isFrameworkInternalRoutePath = (canonicalPath: string) =>
45
- canonicalPath === '/_mf' || canonicalPath.startsWith('/_mf/');
46
-
47
- const legalRouteIdPart = (value: string): string =>
48
- value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
49
-
50
- const formatParamSignature = (signature: string[]): string =>
51
- signature.length > 0 ? signature.join(', ') : '(none)';
52
-
53
- const validateLocalisedUrlPatterns = (
54
- languages: string[],
55
- localisedUrls: LocalisedUrlsMap,
56
- ) => {
57
- const physicalPatterns = new Map<
58
- string,
59
- { canonicalPath: string; source: string }
60
- >();
61
- const claimedPatterns: Array<{
62
- canonicalPath: string;
63
- pattern: string;
64
- source: string;
65
- }> = [];
66
-
67
- const claimPhysicalPattern = (
68
- sourcePattern: string,
69
- canonicalPath: string,
70
- source: string,
71
- ) => {
72
- const physicalPattern = getPhysicalPathPattern(sourcePattern);
73
- const existing = physicalPatterns.get(physicalPattern);
74
- if (existing && existing.canonicalPath !== canonicalPath) {
75
- throw new Error(
76
- `localisedUrls["${existing.canonicalPath}"] ${existing.source} and localisedUrls["${canonicalPath}"] ${source} generate the same physical route pattern "${physicalPattern}". Localised route patterns must identify exactly one canonical route.`,
77
- );
78
- }
79
-
80
- const overlapping = claimedPatterns.find(
81
- claimed =>
82
- claimed.canonicalPath !== canonicalPath &&
83
- haveEqualPatternSpecificity(claimed.pattern, sourcePattern) &&
84
- doPathPatternsOverlap(claimed.pattern, sourcePattern),
85
- );
86
- if (overlapping) {
87
- throw new Error(
88
- `localisedUrls["${overlapping.canonicalPath}"] ${overlapping.source} pattern "${overlapping.pattern}" and localisedUrls["${canonicalPath}"] ${source} pattern "${sourcePattern}" are equal-specificity overlapping route patterns. Localised route patterns must identify exactly one canonical route.`,
89
- );
90
- }
91
-
92
- physicalPatterns.set(physicalPattern, { canonicalPath, source });
93
- claimedPatterns.push({ canonicalPath, pattern: sourcePattern, source });
94
- };
95
-
96
- for (const [canonicalPath, entry] of Object.entries(localisedUrls).sort(
97
- ([left], [right]) => (left < right ? -1 : left > right ? 1 : 0),
98
- )) {
99
- const canonicalIssue = getPathPatternValidationIssue(canonicalPath);
100
- if (canonicalIssue) {
101
- throw new Error(
102
- `localisedUrls["${canonicalPath}"] canonical pattern has ${canonicalIssue}.`,
103
- );
104
- }
105
- const expectedSignature = getPathParamSignature(canonicalPath);
106
- const expectedOrderedSignature =
107
- getOrderedPathParamSignature(canonicalPath);
108
- claimPhysicalPattern(canonicalPath, canonicalPath, 'canonical pattern');
109
-
110
- for (const language of languages) {
111
- const localisedPattern = entry[language];
112
- if (!localisedPattern) {
113
- continue;
114
- }
115
-
116
- const localisedIssue = getPathPatternValidationIssue(localisedPattern);
117
- if (localisedIssue) {
118
- throw new Error(
119
- `localisedUrls["${canonicalPath}"].${language} has ${localisedIssue}.`,
120
- );
121
- }
122
-
123
- const actualSignature = getPathParamSignature(localisedPattern);
124
- if (
125
- actualSignature.length !== expectedSignature.length ||
126
- actualSignature.some(
127
- (parameter, index) => parameter !== expectedSignature[index],
128
- )
129
- ) {
130
- throw new Error(
131
- `localisedUrls["${canonicalPath}"].${language} must use the same parameter signature as "${canonicalPath}": expected ${formatParamSignature(
132
- expectedSignature,
133
- )}; received ${formatParamSignature(actualSignature)}.`,
134
- );
135
- }
136
-
137
- const actualOrderedSignature =
138
- getOrderedPathParamSignature(localisedPattern);
139
- if (
140
- expectedOrderedSignature.some(
141
- parameter => parameter === '*' || parameter.endsWith('?'),
142
- ) &&
143
- actualOrderedSignature.some(
144
- (parameter, index) => parameter !== expectedOrderedSignature[index],
145
- )
146
- ) {
147
- throw new Error(
148
- `localisedUrls["${canonicalPath}"].${language} must keep optional and splat parameters in canonical order: expected ${formatParamSignature(
149
- expectedOrderedSignature,
150
- )}; received ${formatParamSignature(actualOrderedSignature)}.`,
151
- );
152
- }
153
-
154
- claimPhysicalPattern(localisedPattern, canonicalPath, `.${language}`);
155
- }
156
- }
157
- };
158
-
159
- const ensureLocalisedUrlsForPath = (
160
- canonicalPath: string,
161
- languages: string[],
162
- localisedUrls: LocalisedUrlsMap,
163
- ): LocalisedUrlPathMap => {
164
- const entry = localisedUrls[canonicalPath];
165
- if (!entry) {
166
- throw new Error(
167
- `localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(
168
- ', ',
169
- )}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`,
170
- );
171
- }
172
-
173
- const missingLanguages = languages.filter(language => !entry[language]);
174
- if (missingLanguages.length > 0) {
175
- throw new Error(
176
- `localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(
177
- ', ',
178
- )}. Every configured language must have a localised URL.`,
179
- );
180
- }
181
-
182
- return entry;
183
- };
184
-
185
- export const validateLocalisedUrls = (
186
- routes: LocalisedRoute[],
187
- languages: string[],
188
- localisedUrls: LocalisedUrlsMap,
189
- ) => {
190
- validateLocalisedUrlPatterns(languages, localisedUrls);
191
-
192
- const visit = (route: LocalisedRoute, parentPath: string) => {
193
- const canonicalPath = joinPath(parentPath, route.path);
194
- if (
195
- isLocalisableRoutePath(route.path) &&
196
- !isFrameworkInternalRoutePath(canonicalPath)
197
- ) {
198
- ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
199
- }
200
-
201
- if ('children' in route && route.children) {
202
- route.children.forEach(child => visit(child, canonicalPath));
203
- }
204
- };
205
-
206
- routes.forEach(route => visit(route, ''));
207
- };
208
-
209
- const getLocalisedRouteIdSuffixes = (
210
- paths: string[],
211
- ): Array<string | undefined> => {
212
- const usedSuffixes = new Set<string>();
213
-
214
- return paths.map((path, index) => {
215
- if (index === 0) {
216
- return undefined;
217
- }
218
-
219
- const baseSuffix = legalRouteIdPart(path);
220
- let suffix = baseSuffix;
221
- let disambiguator = 2;
222
- while (usedSuffixes.has(suffix)) {
223
- suffix = `${baseSuffix}_${disambiguator++}`;
224
- }
225
- usedSuffixes.add(suffix);
226
- return suffix;
227
- });
228
- };
229
-
230
- const getLocalisedRoutePaths = (
231
- canonicalPath: string,
232
- parentLocalisedPaths: Record<string, string>,
233
- languages: string[],
234
- entry: LocalisedUrlPathMap,
235
- ): string[] => {
236
- const paths = languages.map(language => {
237
- const fullPath = normalisePathPattern(entry[language]);
238
- const parentPath = normalisePathPattern(
239
- parentLocalisedPaths[language] || '/',
240
- );
241
- if (parentPath === '/') {
242
- return normaliseRoutePath(fullPath) || undefined;
243
- }
244
-
245
- const parentPrefix = `${parentPath}/`;
246
- if (!fullPath.startsWith(parentPrefix)) {
247
- throw new Error(
248
- `localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`,
249
- );
250
- }
251
-
252
- return normaliseRoutePath(fullPath.slice(parentPath.length));
253
- });
254
-
255
- const uniquePaths = Array.from(new Set(paths.filter(Boolean) as string[]));
256
- return uniquePaths;
257
- };
258
-
259
- const transformLocalisedRoute = (
260
- route: LocalisedRoute,
261
- parentCanonicalPath: string,
262
- parentLocalisedPaths: Record<string, string>,
263
- languages: string[],
264
- localisedUrls: LocalisedUrlsMap,
265
- ): LocalisedRoute[] => {
266
- const canonicalPath = joinPath(parentCanonicalPath, route.path);
267
- const localisedUrlEntry =
268
- isLocalisableRoutePath(route.path) &&
269
- !isFrameworkInternalRoutePath(canonicalPath)
270
- ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls)
271
- : undefined;
272
- const routeLocalisedPaths = localisedUrlEntry
273
- ? languages.reduce<Record<string, string>>((acc, language) => {
274
- acc[language] = normalisePathPattern(localisedUrlEntry[language]);
275
- return acc;
276
- }, {})
277
- : parentLocalisedPaths;
278
-
279
- const children =
280
- 'children' in route && route.children
281
- ? route.children.flatMap(child =>
282
- transformLocalisedRoute(
283
- child,
284
- canonicalPath,
285
- routeLocalisedPaths,
286
- languages,
287
- localisedUrls,
288
- ),
289
- )
290
- : undefined;
291
-
292
- const baseRoute = {
293
- ...route,
294
- ...(!isFrameworkInternalRoutePath(canonicalPath)
295
- ? {
296
- modernLocalisedRoute: {
297
- id: route.id,
298
- path: route.path,
299
- canonicalPath,
300
- paths: localisedUrlEntry,
301
- },
302
- }
303
- : {}),
304
- ...(children ? { children } : {}),
305
- } as LocalisedRoute;
306
-
307
- if (!localisedUrlEntry) {
308
- return [baseRoute];
309
- }
310
-
311
- const localisedPaths = getLocalisedRoutePaths(
312
- canonicalPath,
313
- parentLocalisedPaths,
314
- languages,
315
- localisedUrlEntry,
316
- );
317
- const leadingLocaleParam = getLeadingLocaleParam(route.path);
318
- const routeIdPaths = leadingLocaleParam
319
- ? localisedPaths.map(path =>
320
- normaliseRoutePath(`${leadingLocaleParam}/${path}`),
321
- )
322
- : localisedPaths;
323
- const routeIdSuffixes = getLocalisedRouteIdSuffixes(routeIdPaths);
324
-
325
- return localisedPaths.map((localisedPath, index) =>
326
- cloneRouteWithLocalisedPath(
327
- baseRoute,
328
- localisedPath,
329
- routeIdSuffixes[index],
330
- canonicalPath,
331
- ),
332
- );
333
- };
334
-
335
- const suffixRouteIds = <T extends LocalisedRoute>(
336
- route: T,
337
- suffix: string,
338
- ): T => {
339
- const children =
340
- 'children' in route && route.children
341
- ? route.children.map(child => suffixRouteIds(child, suffix))
342
- : undefined;
343
-
344
- return {
345
- ...route,
346
- ...(route.id ? { id: `${route.id}__localised_${suffix}` } : {}),
347
- ...(children ? { children } : {}),
348
- };
349
- };
350
-
351
- const collectRouteIdCounts = (
352
- routes: LocalisedRoute[],
353
- counts = new Map<string, number>(),
354
- ): Map<string, number> => {
355
- for (const route of routes) {
356
- if (route.id) {
357
- counts.set(route.id, (counts.get(route.id) ?? 0) + 1);
358
- }
359
- if ('children' in route && route.children) {
360
- collectRouteIdCounts(route.children, counts);
361
- }
362
- }
363
- return counts;
364
- };
365
-
366
- const validateNoNewRouteIdCollisions = (
367
- sourceRoutes: LocalisedRoute[],
368
- localisedRoutes: LocalisedRoute[],
369
- ) => {
370
- const sourceCounts = collectRouteIdCounts(sourceRoutes);
371
- const localisedCounts = collectRouteIdCounts(localisedRoutes);
372
-
373
- for (const [routeId, count] of localisedCounts) {
374
- if (count > 1 && count > (sourceCounts.get(routeId) ?? 0)) {
375
- throw new Error(
376
- `Localised route expansion generated duplicate route ID "${routeId}". Change the source route ID or localised path so every generated route remains identifiable.`,
377
- );
378
- }
379
- }
380
- };
381
-
382
- const cloneRouteWithLocalisedPath = (
383
- route: LocalisedRoute,
384
- path: string,
385
- routeIdSuffix: string | undefined,
386
- canonicalPath: string,
387
- ): LocalisedRoute => {
388
- const leadingLocaleParam = getLeadingLocaleParam(route.path);
389
- const localisedPath = leadingLocaleParam
390
- ? normaliseRoutePath(`${leadingLocaleParam}/${path}`)
391
- : path;
392
- const routeWithPath = {
393
- ...route,
394
- path: localisedPath,
395
- } as LocalisedRoute;
396
- // Language-agnostic source pattern; lets downstream codegen collapse the
397
- // localized physical variants back to one canonical route.
398
- (routeWithPath as { modernCanonicalPath?: string }).modernCanonicalPath =
399
- canonicalPath;
400
-
401
- return routeIdSuffix
402
- ? suffixRouteIds(routeWithPath, routeIdSuffix)
403
- : routeWithPath;
404
- };
405
-
406
- export const applyLocalisedUrlsToRoutes = (
407
- routes: LocalisedRoute[],
408
- languages: string[],
409
- localisedUrls: LocalisedUrlsMap,
410
- ): LocalisedRoute[] => {
411
- const rootLocalisedPaths = languages.reduce<Record<string, string>>(
412
- (acc, language) => {
413
- acc[language] = '/';
414
- return acc;
415
- },
416
- {},
417
- );
418
-
419
- validateLocalisedUrls(routes, languages, localisedUrls);
420
-
421
- const localisedRoutes = routes.flatMap(route =>
422
- transformLocalisedRoute(
423
- route,
424
- '',
425
- rootLocalisedPaths,
426
- languages,
427
- localisedUrls,
428
- ),
429
- );
430
- validateNoNewRouteIdCollisions(routes, localisedRoutes);
431
- return localisedRoutes;
432
- };
@@ -1,18 +0,0 @@
1
- export type LocalisedRoute = {
2
- type: 'nested' | 'page';
3
- path?: string;
4
- id?: string;
5
- children?: LocalisedRoute[];
6
- [key: string]: any;
7
- };
8
-
9
- export type LocalisedUrlPathMap = Record<string, string>;
10
-
11
- export type LocalisedUrlsMap = Record<string, LocalisedUrlPathMap>;
12
-
13
- export type LocalisedUrlsOption = boolean | LocalisedUrlsMap;
14
-
15
- export interface ResolvedLocalisedUrlsConfig {
16
- enabled: boolean;
17
- map: LocalisedUrlsMap;
18
- }
@@ -1,136 +0,0 @@
1
- import {
2
- createLatestLanguageSyncBinding,
3
- type LanguageSyncFailure,
4
- } from '../src/language-sync/controller';
5
-
6
- interface Target {
7
- language: string;
8
- }
9
-
10
- interface PendingChange {
11
- language: string;
12
- promise: Promise<void>;
13
- reject: (error: Error) => void;
14
- resolve: () => void;
15
- }
16
-
17
- const deferredChanger = (target: Target) => {
18
- const pending: PendingChange[] = [];
19
- const changeLanguage = (_target: Target, language: string) => {
20
- let resolvePromise!: () => void;
21
- let rejectPromise!: (error: Error) => void;
22
- const promise = new Promise<void>((resolve, reject) => {
23
- resolvePromise = resolve;
24
- rejectPromise = reject;
25
- });
26
- pending.push({
27
- language,
28
- promise,
29
- reject: rejectPromise,
30
- resolve: () => {
31
- target.language = language;
32
- resolvePromise();
33
- },
34
- });
35
- return promise;
36
- };
37
- return { changeLanguage, pending };
38
- };
39
-
40
- const flush = async () => {
41
- await Promise.resolve();
42
- await Promise.resolve();
43
- };
44
-
45
- describe('latest language synchronization coordinator', () => {
46
- afterEach(() => {
47
- rstest.useRealTimers();
48
- rstest.restoreAllMocks();
49
- });
50
-
51
- test('retains a request issued before commit-phase activation', async () => {
52
- const target = { language: 'en' };
53
- const changeLanguage = rstest.fn(async () => undefined);
54
- const binding = createLatestLanguageSyncBinding<Target>();
55
- binding.updateCallbacks({
56
- changeLanguage,
57
- commitLanguage: () => undefined,
58
- readLanguage: current => current.language,
59
- });
60
-
61
- binding.request('cs');
62
- expect(changeLanguage).not.toHaveBeenCalled();
63
- binding.activate(target);
64
- expect(changeLanguage).toHaveBeenCalledWith(target, 'cs');
65
- await flush();
66
- binding.deactivate();
67
- });
68
-
69
- test('starts newer work immediately and repairs a late stale mutation', async () => {
70
- const target = { language: 'en' };
71
- const { changeLanguage, pending } = deferredChanger(target);
72
- const commits: string[] = [];
73
- const binding = createLatestLanguageSyncBinding<Target>();
74
- binding.updateCallbacks({
75
- changeLanguage,
76
- commitLanguage: (_target, language) => commits.push(language),
77
- readLanguage: current => current.language,
78
- });
79
- binding.activate(target);
80
-
81
- binding.request('cs');
82
- binding.request('de');
83
-
84
- pending[1].resolve();
85
- await pending[1].promise;
86
- await flush();
87
- expect(commits).toEqual(['de']);
88
-
89
- pending[0].resolve();
90
- await pending[0].promise;
91
- await flush();
92
- expect(target.language).toBe('cs');
93
-
94
- pending[2].resolve();
95
- await pending[2].promise;
96
- await flush();
97
- expect(target.language).toBe('de');
98
- expect(commits.at(-1)).toBe('de');
99
- });
100
-
101
- test('bounds permanent failures and reports the final consequence once', async () => {
102
- rstest.useFakeTimers();
103
- const target = { language: 'en' };
104
- const failures: LanguageSyncFailure[] = [];
105
- const changeLanguage = rstest.fn(async () => {
106
- throw new Error('resources unavailable');
107
- });
108
- const binding = createLatestLanguageSyncBinding<Target>({
109
- attemptTimeoutMs: 1_000,
110
- maxAttempts: 3,
111
- retryDelayMs: () => 10,
112
- });
113
- binding.updateCallbacks({
114
- changeLanguage,
115
- commitLanguage: () => undefined,
116
- readLanguage: current => current.language,
117
- reportFailure: failure => failures.push(failure),
118
- });
119
- binding.activate(target);
120
- binding.request('cs');
121
-
122
- await flush();
123
- await rstest.advanceTimersByTimeAsync(10);
124
- await flush();
125
- await rstest.advanceTimersByTimeAsync(10);
126
- await flush();
127
-
128
- expect(changeLanguage).toHaveBeenCalledTimes(3);
129
- expect(failures).toHaveLength(1);
130
- expect(failures[0]).toMatchObject({
131
- attempts: 3,
132
- language: 'cs',
133
- reason: 'rejected',
134
- });
135
- });
136
- });