@mpen/rerouter 0.1.9 → 0.3.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 (59) hide show
  1. package/README.md +76 -18
  2. package/dist/bin.d.ts +29 -0
  3. package/dist/bin.js +228 -0
  4. package/dist/hooks-Dlwcb0sV.js +20 -0
  5. package/dist/hooks.d.ts +2 -0
  6. package/dist/hooks.js +2 -0
  7. package/dist/index-BYXpNitc.d.ts +5 -0
  8. package/dist/index.d.ts +265 -0
  9. package/dist/index.js +139 -0
  10. package/dist/routes-Hpf6cwcZ.js +135 -0
  11. package/examples/App.tsx +111 -0
  12. package/examples/index.html +67 -0
  13. package/examples/pages/BlogPost.tsx +17 -0
  14. package/examples/pages/FetchLoading.tsx +53 -0
  15. package/examples/pages/FetchLoadingItem.tsx +45 -0
  16. package/examples/pages/Home.tsx +3 -0
  17. package/examples/pages/KitchenSink.tsx +23 -0
  18. package/examples/pages/Login.tsx +3 -0
  19. package/examples/pages/Match.tsx +5 -0
  20. package/examples/pages/NotFound.tsx +3 -0
  21. package/examples/pages/SlowLoading.tsx +8 -0
  22. package/examples/routes.gen.ts +125 -0
  23. package/examples/routes.ts +40 -0
  24. package/package.json +37 -32
  25. package/src/bin.test.ts +199 -0
  26. package/src/bin.ts +333 -0
  27. package/src/components/Link.test.tsx +139 -0
  28. package/src/components/Link.tsx +87 -0
  29. package/src/components/NavLink.test.tsx +119 -0
  30. package/src/components/NavLink.tsx +71 -0
  31. package/src/components/Router.tsx +75 -0
  32. package/src/fixtures/bin/kitchen-sink.tsx +15 -0
  33. package/src/fixtures/bin/optional.tsx +3 -0
  34. package/src/fixtures/bin/pages/Home.tsx +3 -0
  35. package/src/fixtures/bin/pages/KitchenSink.tsx +3 -0
  36. package/src/fixtures/bin/pages/Login.tsx +3 -0
  37. package/src/fixtures/bin/pages/Match.tsx +3 -0
  38. package/src/fixtures/bin/pages/NotFound.tsx +3 -0
  39. package/src/fixtures/bin/pages/Optional.tsx +3 -0
  40. package/src/fixtures/bin/regexp-groups.tsx +11 -0
  41. package/src/fixtures/bin/simple.tsx +1 -0
  42. package/src/fixtures/bin/unnamed.tsx +4 -0
  43. package/src/hooks/index.ts +1 -0
  44. package/src/hooks/useUrl.ts +22 -0
  45. package/src/index.ts +6 -0
  46. package/src/lib/mergeSearch.test.ts +37 -0
  47. package/src/lib/mergeSearch.ts +21 -0
  48. package/src/lib/routes.test.ts +67 -0
  49. package/src/lib/routes.ts +245 -0
  50. package/src/lib/url.ts +9 -0
  51. package/tsconfig.json +9 -0
  52. package/tsdown.config.ts +22 -0
  53. package/LICENSE +0 -21
  54. package/dist/bundle.cjs +0 -422
  55. package/dist/bundle.d.ts +0 -2
  56. package/dist/bundle.mjs +0 -420
  57. package/dist/dev.d.ts +0 -1
  58. package/dist/log.d.ts +0 -1
  59. package/dist/uri-template.d.ts +0 -56
package/dist/bundle.mjs DELETED
@@ -1,420 +0,0 @@
1
- const PREFIX_RE = /^[+#./;?&]/;
2
-
3
- const MODIFIER_RE = /(?<repeat>\*)?(?::(?<func>[a-zA-Z][a-zA-Z0-9_]*))?(?::(?:(?<length>\d+)))?$/;
4
-
5
- const UNRESERVED = /[^a-zA-Z0-9\-._~]+/gsu;
6
-
7
- const UR_SET = /[^a-zA-Z0-9\-._~:\/?#[\]@!$&'()*+,;=]+/gsu;
8
-
9
- const PERCENT_RE = /^%[0-9a-fA-F]{2}$/;
10
-
11
- const STR = Symbol("string");
12
-
13
- const VAR = Symbol("var");
14
-
15
- const SeparatorMap = {
16
- "": ",",
17
- "+": ",",
18
- ".": ".",
19
- "/": "/",
20
- ";": ";",
21
- "?": "&",
22
- "&": "&",
23
- "#": ","
24
- };
25
-
26
- const FirstMap = {
27
- "": "",
28
- "+": "",
29
- ".": ".",
30
- "/": "/",
31
- ";": ";",
32
- "?": "?",
33
- "&": "&",
34
- "#": "#"
35
- };
36
-
37
- const Named = {
38
- "": false,
39
- "+": false,
40
- ".": false,
41
- "/": false,
42
- ";": true,
43
- "?": true,
44
- "&": true,
45
- "#": false
46
- };
47
-
48
- const IfEmp = {
49
- "": "",
50
- "+": "",
51
- ".": "",
52
- "/": "",
53
- ";": "",
54
- "?": "=",
55
- "&": "=",
56
- "#": ""
57
- };
58
-
59
- const ReservedExpansion = {
60
- "": false,
61
- "+": true,
62
- ".": false,
63
- "/": false,
64
- ";": false,
65
- "?": false,
66
- "&": false,
67
- "#": true
68
- };
69
-
70
- var VarType;
71
-
72
- (function(VarType) {
73
- VarType[VarType["NAMED"] = 0] = "NAMED";
74
- VarType[VarType["STATIC"] = 1] = "STATIC";
75
- VarType[VarType["DYNAMIC"] = 2] = "DYNAMIC";
76
- })(VarType || (VarType = {}));
77
-
78
- class UriTemplate {
79
- expandParts;
80
- matchRegex;
81
- matchMap;
82
- constructor(template) {
83
- this.expandParts = [];
84
- const re = [ "^" ];
85
- this.matchMap = new Map;
86
- let pos = 0;
87
- const matches = Array.from(template.matchAll(/\{(.+?)\}/g));
88
- let matchCounter = 0;
89
- for (const m of matches) {
90
- if (m.index > pos) {
91
- const lit = template.slice(pos, m.index);
92
- this.expandParts.push({
93
- type: STR,
94
- value: lit
95
- });
96
- const groupName = `static${matchCounter++}`;
97
- re.push(`(?<${groupName}>${escapeRegExp(lit)})`);
98
- this.matchMap.set(groupName, {
99
- type: VarType.STATIC
100
- });
101
- }
102
- pos = m.index + m[0].length;
103
- const ph = {
104
- type: VAR,
105
- prefix: "",
106
- vars: []
107
- };
108
- this.expandParts.push(ph);
109
- let varStr = m[1];
110
- const prefix = varStr.match(PREFIX_RE);
111
- if (prefix) {
112
- varStr = varStr.slice(1);
113
- ph.prefix = prefix[0];
114
- }
115
- const vars = varStr.split(",");
116
- const isNamed = Named[ph.prefix];
117
- let isFirst = true;
118
- if (!isNamed) {
119
- re.push(escapeRegExp(FirstMap[ph.prefix]));
120
- }
121
- for (const v of vars) {
122
- const item = {
123
- name: v,
124
- length: null,
125
- func: null,
126
- repeat: false
127
- };
128
- const mod = v.match(MODIFIER_RE);
129
- if (mod) {
130
- if (mod.groups.repeat !== undefined) {
131
- item.repeat = true;
132
- }
133
- if (mod.groups.length !== undefined) {
134
- item.length = Number(mod.groups.length);
135
- }
136
- if (mod.groups.func !== undefined) {
137
- item.func = mod.groups.func;
138
- }
139
- item.name = item.name.slice(0, mod.index);
140
- }
141
- ph.vars.push(item);
142
- if (!isNamed) {
143
- if (!isFirst) {
144
- re.push(escapeRegExp(SeparatorMap[ph.prefix]));
145
- }
146
- let groupName = item.name;
147
- if (!/^[a-z][a-z0-9_]*$/i.test(groupName)) {
148
- groupName = "param";
149
- }
150
- groupName += String(matchCounter++);
151
- re.push(`(?<${groupName}>`);
152
- if (item.func != null) {
153
- switch (item.func) {
154
- case "int":
155
- if (item.length != null) {
156
- re.push(`\\d{${item.length}}`);
157
- } else {
158
- re.push("-?\\d+");
159
- }
160
- break;
161
-
162
- default:
163
- throw new Error(`Unrecognized UriTemplate func: ${item.func}`);
164
- }
165
- } else {
166
- let ch;
167
- if (ph.prefix === "+") {
168
- ch = "[^?#]";
169
- } else if (ph.prefix === "#") {
170
- ch = ".";
171
- } else if (ph.prefix === "/" && item.repeat) {
172
- ch = "[^?#]";
173
- } else {
174
- ch = "[^/?#]";
175
- }
176
- if (item.length != null) {
177
- ch = `(?:%[0-9a-fA-F]{2}|${ch})`;
178
- re.push(ch, `{${item.length}}`);
179
- } else {
180
- re.push(ch, "+?");
181
- }
182
- }
183
- re.push(")");
184
- this.matchMap.set(groupName, {
185
- var: item,
186
- type: VarType.DYNAMIC,
187
- prefix: ph.prefix
188
- });
189
- }
190
- isFirst = false;
191
- }
192
- if (isNamed) {
193
- re.push("(?:", escapeRegExp(FirstMap[ph.prefix]));
194
- const groupName = `kwargs${matchCounter++}`;
195
- re.push(`(?<${groupName}>[^/?#]*)`);
196
- re.push(")?");
197
- this.matchMap.set(groupName, {
198
- vars: ph.vars,
199
- type: VarType.NAMED,
200
- prefix: ph.prefix
201
- });
202
- }
203
- }
204
- if (pos < template.length) {
205
- const lit = template.slice(pos);
206
- this.expandParts.push({
207
- type: STR,
208
- value: lit
209
- });
210
- const groupName = `static${matchCounter++}`;
211
- re.push(`(?<${groupName}>${escapeRegExp(lit)})`);
212
- this.matchMap.set(groupName, {
213
- type: VarType.STATIC
214
- });
215
- }
216
- re.push("$");
217
- this.matchRegex = new RegExp(re.join(""));
218
- }
219
- expand(variables) {
220
- const out = [];
221
- for (const p of this.expandParts) {
222
- switch (p.type) {
223
- case VAR:
224
- const vs = [];
225
- for (const v of p.vars) {
226
- if (Object.hasOwn(variables, v.name)) {
227
- const x = variables[v.name];
228
- if (x == null) continue;
229
- const sep = v.repeat ? SeparatorMap[p.prefix] : ",";
230
- const esc = x => percentEncodeRegExp(x, ReservedExpansion[p.prefix], v.length, v.repeat ? "=" : ",");
231
- let pre = "";
232
- if (Named[p.prefix]) {
233
- pre = v.name + (isEmpty(x) ? IfEmp[p.prefix] : "=");
234
- }
235
- if (Array.isArray(x)) {
236
- if (x.length) {
237
- vs.push((v.repeat ? "" : pre) + x.map((z => (v.repeat ? pre : "") + esc(z))).join(sep));
238
- }
239
- } else if (typeof x === "object") {
240
- if (Object.keys(x).length) {
241
- vs.push((v.repeat ? "" : pre) + Object.entries(x).map((([ok, ov]) => `${esc(ok)}${v.repeat ? "=" : ","}${esc(ov)}`)).join(sep));
242
- }
243
- } else {
244
- vs.push(pre + esc(x));
245
- }
246
- }
247
- }
248
- if (vs.length) {
249
- out.push(FirstMap[p.prefix], vs.join(SeparatorMap[p.prefix]));
250
- }
251
- break;
252
-
253
- case STR:
254
- out.push(p.value);
255
- break;
256
- }
257
- }
258
- return out.join("");
259
- }
260
- match(url) {
261
- let score = 0;
262
- const m = url.match(this.matchRegex);
263
- if (m !== null) {
264
- let params = [];
265
- if (m.groups != null) {
266
- for (const [k, v] of Object.entries(m.groups)) {
267
- const itemSpec = this.matchMap.get(k);
268
- let value;
269
- switch (itemSpec.type) {
270
- case VarType.NAMED:
271
- {
272
- const parsed = v == null ? Object.create(null) : parseParams(v, SeparatorMap[itemSpec.prefix]);
273
- for (const vs of itemSpec.vars) {
274
- if (vs.repeat) {
275
- score -= 1;
276
- if (isEmpty(parsed)) {
277
- params.push([ vs.name, EMPTY_OBJ ]);
278
- } else {
279
- params.push([ vs.name, mapValues(parsed, (x => formatElement(x, vs))) ]);
280
- }
281
- break;
282
- } else {
283
- if (parsed[vs.name] !== undefined) {
284
- score += 2;
285
- params.push([ vs.name, formatElement(parsed[vs.name], vs) ]);
286
- delete parsed[vs.name];
287
- } else {
288
- params.push([ vs.name, null ]);
289
- }
290
- }
291
- }
292
- }
293
- break;
294
-
295
- case VarType.DYNAMIC:
296
- {
297
- score += 2;
298
- if (v == null) {
299
- if (itemSpec.var.repeat) {
300
- if (Named[itemSpec.prefix]) {
301
- value = EMPTY_OBJ;
302
- } else {
303
- value = EMPTY_ARR;
304
- }
305
- } else {
306
- value = null;
307
- }
308
- } else {
309
- value = v;
310
- if (itemSpec.var.repeat) {
311
- value = value.split(SeparatorMap[itemSpec.prefix]).map((x => formatElement(x, itemSpec.var)));
312
- } else {
313
- value = formatElement(value, itemSpec.var);
314
- }
315
- }
316
- params.push([ itemSpec.var.name, value ]);
317
- }
318
- break;
319
-
320
- case VarType.STATIC:
321
- {
322
- score += 3;
323
- }
324
- break;
325
- }
326
- }
327
- }
328
- return {
329
- score,
330
- params: Object.fromEntries(params)
331
- };
332
- }
333
- return null;
334
- }
335
- }
336
-
337
- function formatElement(str, varSpec) {
338
- if (str == null) return null;
339
- let out = decodeURIComponent(str);
340
- if (varSpec.length != null) {
341
- out = out.slice(0, varSpec.length);
342
- }
343
- if (varSpec.func === "int") {
344
- out = Number(out);
345
- }
346
- return out;
347
- }
348
-
349
- function mapValues(obj, callback) {
350
- return Object.fromEntries(Object.entries(obj).map((([key, value]) => [ key, callback(value) ])));
351
- }
352
-
353
- function parseParams(queryString, separator) {
354
- const pairs = queryString.split(separator);
355
- return Object.fromEntries(pairs.map((pair => {
356
- const idx = pair.indexOf("=");
357
- if (idx === -1) {
358
- return [ pair, null ];
359
- }
360
- const key = pair.slice(0, idx);
361
- const value = pair.slice(idx + 1);
362
- return [ key, value ];
363
- })));
364
- }
365
-
366
- const EMPTY_OBJ = Object.freeze(Object.create(null));
367
-
368
- const EMPTY_ARR = Object.freeze([]);
369
-
370
- function isEmpty(x) {
371
- return x == null || x === "" || (Array.isArray(x) ? !x.length : typeof x === "object" && !Object.keys(x).length);
372
- }
373
-
374
- function escapeRegExp(string) {
375
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
376
- }
377
-
378
- function fullWide(n) {
379
- try {
380
- return n.toLocaleString("en-US", {
381
- useGrouping: false,
382
- maximumFractionDigits: 20
383
- });
384
- } catch {
385
- return n.toFixed(14).replace(/\.?0+$/, "");
386
- }
387
- }
388
-
389
- function percentEncodeRegExp(value, reserved, length, separator) {
390
- if (typeof value === "number") {
391
- return fullWide(value);
392
- }
393
- if (value === true) return "1";
394
- if (value === false) return "0";
395
- if (value == null) return "";
396
- if (Array.isArray(value)) {
397
- return value.map((v => percentEncodeRegExp(v, reserved, length, separator))).join(separator);
398
- }
399
- if (length != null) {
400
- value = value.slice(0, length);
401
- }
402
- if (reserved) {
403
- return value.replace(/%[0-9a-fA-F]{2}|./gsu, (m => {
404
- let v = PERCENT_RE.test(m) ? decodeURIComponent(m) : m;
405
- if (UR_SET.test(v)) {
406
- return percentEncode(v);
407
- }
408
- return m;
409
- }));
410
- }
411
- return value.replace(UNRESERVED, percentEncode);
412
- }
413
-
414
- const UTF8_ENCODER = new TextEncoder;
415
-
416
- function percentEncode(str) {
417
- return Array.from(UTF8_ENCODER.encode(str)).map((i => "%" + i.toString(16).toUpperCase().padStart(2, "0"))).join("");
418
- }
419
-
420
- export { UriTemplate };
package/dist/dev.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/dist/log.d.ts DELETED
@@ -1 +0,0 @@
1
- export default function log(...vars: any): void;
@@ -1,56 +0,0 @@
1
- declare const STR: unique symbol;
2
- declare const VAR: unique symbol;
3
- interface Placeholder {
4
- type: typeof VAR;
5
- prefix: string;
6
- vars: VarSpec[];
7
- }
8
- interface StringLiteral {
9
- type: typeof STR;
10
- value: string;
11
- }
12
- type TemplateParts = Array<Placeholder | StringLiteral>;
13
- interface VarSpec {
14
- name: string;
15
- /** Max length, in characters. */
16
- length: number | null;
17
- func: string | null;
18
- repeat: boolean;
19
- }
20
- declare enum VarType {
21
- NAMED = 0,
22
- STATIC = 1,
23
- DYNAMIC = 2
24
- }
25
- type MapItem = {
26
- type: VarType.DYNAMIC;
27
- var: VarSpec;
28
- prefix: string;
29
- } | {
30
- type: VarType.NAMED;
31
- vars: VarSpec[];
32
- prefix: string;
33
- } | {
34
- type: VarType.STATIC;
35
- };
36
- export declare class UriTemplate<P extends UriParams> {
37
- expandParts: TemplateParts;
38
- matchRegex: RegExp;
39
- matchMap: Map<string, MapItem>;
40
- constructor(template: string);
41
- expand(variables: P): string;
42
- match(url: string): UriMatch<P> | null;
43
- }
44
- type Primitive = string | number | boolean | null;
45
- type PrimitivePair = [key: string, value: Primitive];
46
- type PrimitiveMap = {
47
- [K in string]: Primitive;
48
- };
49
- export type UrlParamValue = Primitive | Primitive[] | PrimitivePair[] | PrimitiveMap;
50
- export declare function fullWide(n: number): string;
51
- export type UriParams = Record<string, UrlParamValue>;
52
- export type UriMatch<P extends UriParams> = {
53
- score: number;
54
- params: P;
55
- };
56
- export {};