@mpen/rerouter 0.1.7 → 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 -406
  55. package/dist/bundle.d.ts +0 -2
  56. package/dist/bundle.mjs +0 -404
  57. package/dist/dev.d.ts +0 -1
  58. package/dist/log.d.ts +0 -1
  59. package/dist/uri-template.d.ts +0 -50
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2023 Mark Penner
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/dist/bundle.cjs DELETED
@@ -1,406 +0,0 @@
1
- "use strict";
2
-
3
- const PREFIX_RE = /^[+#./;?&]/;
4
-
5
- const MODIFIER_RE = /(?<repeat>\*)?(?::(?<func>[a-zA-Z][a-zA-Z0-9_]*))?(?::(?:(?<length>\d+)))?$/;
6
-
7
- const UNRESERVED = /[^a-zA-Z0-9\-._~]+/gsu;
8
-
9
- const UR_SET = /[^a-zA-Z0-9\-._~:\/?#[\]@!$&'()*+,;=]+/gsu;
10
-
11
- const PERCENT_RE = /^%[0-9a-fA-F]{2}$/;
12
-
13
- const STR = Symbol("string");
14
-
15
- const VAR = Symbol("var");
16
-
17
- const SeparatorMap = {
18
- "": ",",
19
- "+": ",",
20
- ".": ".",
21
- "/": "/",
22
- ";": ";",
23
- "?": "&",
24
- "&": "&",
25
- "#": ","
26
- };
27
-
28
- const FirstMap = {
29
- "": "",
30
- "+": "",
31
- ".": ".",
32
- "/": "/",
33
- ";": ";",
34
- "?": "?",
35
- "&": "&",
36
- "#": "#"
37
- };
38
-
39
- const Named = {
40
- "": false,
41
- "+": false,
42
- ".": false,
43
- "/": false,
44
- ";": true,
45
- "?": true,
46
- "&": true,
47
- "#": false
48
- };
49
-
50
- const IfEmp = {
51
- "": "",
52
- "+": "",
53
- ".": "",
54
- "/": "",
55
- ";": "",
56
- "?": "=",
57
- "&": "=",
58
- "#": ""
59
- };
60
-
61
- const ReservedExpansion = {
62
- "": false,
63
- "+": true,
64
- ".": false,
65
- "/": false,
66
- ";": false,
67
- "?": false,
68
- "&": false,
69
- "#": true
70
- };
71
-
72
- var VarType;
73
-
74
- (function(VarType) {
75
- VarType[VarType["NAMED"] = 0] = "NAMED";
76
- VarType[VarType["STATIC"] = 1] = "STATIC";
77
- VarType[VarType["DYNAMIC"] = 2] = "DYNAMIC";
78
- })(VarType || (VarType = {}));
79
-
80
- class UriTemplate {
81
- expandParts;
82
- matchRegex;
83
- matchMap;
84
- constructor(template) {
85
- this.expandParts = [];
86
- const re = [ "^" ];
87
- this.matchMap = new Map;
88
- let pos = 0;
89
- const matches = Array.from(template.matchAll(/\{(.+?)\}/g));
90
- let matchCounter = 0;
91
- for (const m of matches) {
92
- if (m.index > pos) {
93
- const lit = template.slice(pos, m.index);
94
- this.expandParts.push({
95
- type: STR,
96
- value: lit
97
- });
98
- const groupName = `static${matchCounter++}`;
99
- re.push(`(?<${groupName}>${escapeRegExp(lit)})`);
100
- this.matchMap.set(groupName, {
101
- type: VarType.STATIC
102
- });
103
- }
104
- pos = m.index + m[0].length;
105
- const ph = {
106
- type: VAR,
107
- prefix: "",
108
- vars: []
109
- };
110
- this.expandParts.push(ph);
111
- let varStr = m[1];
112
- const prefix = varStr.match(PREFIX_RE);
113
- if (prefix) {
114
- varStr = varStr.slice(1);
115
- ph.prefix = prefix[0];
116
- }
117
- const vars = varStr.split(",");
118
- const isNamed = Named[ph.prefix];
119
- let isFirst = true;
120
- if (!isNamed) {
121
- re.push(escapeRegExp(FirstMap[ph.prefix]));
122
- }
123
- for (const v of vars) {
124
- const item = {
125
- name: v,
126
- length: null,
127
- func: null,
128
- repeat: false
129
- };
130
- const mod = v.match(MODIFIER_RE);
131
- if (mod) {
132
- if (mod.groups.repeat !== undefined) {
133
- item.repeat = true;
134
- }
135
- if (mod.groups.length !== undefined) {
136
- item.length = Number(mod.groups.length);
137
- }
138
- if (mod.groups.func !== undefined) {
139
- item.func = mod.groups.func;
140
- }
141
- item.name = item.name.slice(0, mod.index);
142
- }
143
- ph.vars.push(item);
144
- if (!isNamed) {
145
- if (!isFirst) {
146
- re.push(escapeRegExp(SeparatorMap[ph.prefix]));
147
- }
148
- let groupName = item.name;
149
- if (!/^[a-z][a-z0-9_]*$/i.test(groupName)) {
150
- groupName = "param";
151
- }
152
- groupName += String(matchCounter++);
153
- re.push(`(?<${groupName}>`);
154
- if (item.func != null) {
155
- switch (item.func) {
156
- case "int":
157
- if (item.length != null) {
158
- re.push(`\\d{${item.length}}`);
159
- } else {
160
- re.push("-?\\d+");
161
- }
162
- break;
163
-
164
- default:
165
- throw new Error(`Unrecognized UriTemplate func: ${item.func}`);
166
- }
167
- } else {
168
- let ch;
169
- if (ph.prefix === "+") {
170
- ch = "[^?#]";
171
- } else if (ph.prefix === "#") {
172
- ch = ".";
173
- } else if (ph.prefix === "/" && item.repeat) {
174
- ch = "[^?#]";
175
- } else {
176
- ch = "[^/?#]";
177
- }
178
- if (item.length != null) {
179
- ch = `(?:%[0-9a-fA-F]{2}|${ch})`;
180
- re.push(ch, `{${item.length}}`);
181
- } else {
182
- re.push(ch, "+?");
183
- }
184
- }
185
- re.push(")");
186
- this.matchMap.set(groupName, {
187
- var: item,
188
- type: VarType.DYNAMIC,
189
- prefix: ph.prefix
190
- });
191
- }
192
- isFirst = false;
193
- }
194
- if (isNamed) {
195
- re.push("(?:", escapeRegExp(FirstMap[ph.prefix]));
196
- const groupName = `kwargs${matchCounter++}`;
197
- re.push(`(?<${groupName}>[^/?#]*)`);
198
- re.push(")?");
199
- this.matchMap.set(groupName, {
200
- vars: ph.vars,
201
- type: VarType.NAMED,
202
- prefix: ph.prefix
203
- });
204
- }
205
- }
206
- if (pos < template.length) {
207
- const lit = template.slice(pos);
208
- this.expandParts.push({
209
- type: STR,
210
- value: lit
211
- });
212
- const groupName = `static${matchCounter++}`;
213
- re.push(`(?<${groupName}>${escapeRegExp(lit)})`);
214
- this.matchMap.set(groupName, {
215
- type: VarType.STATIC
216
- });
217
- }
218
- re.push("$");
219
- this.matchRegex = new RegExp(re.join(""));
220
- }
221
- expand(variables) {
222
- const out = [];
223
- for (const p of this.expandParts) {
224
- switch (p.type) {
225
- case VAR:
226
- const vs = [];
227
- for (const v of p.vars) {
228
- if (Object.hasOwn(variables, v.name)) {
229
- const x = variables[v.name];
230
- const esc = x => percentEncodeRegExp(x, ReservedExpansion[p.prefix], v.length);
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(v.repeat ? SeparatorMap[p.prefix] : ","));
238
- }
239
- } else if (x != null && 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(v.repeat ? SeparatorMap[p.prefix] : ","));
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 percentEncodeRegExp(x, reserved, length) {
379
- if (typeof x === "number") {
380
- return String(x);
381
- }
382
- if (x === true) return "1";
383
- if (x === false) return "0";
384
- if (x === null) return "";
385
- if (length != null) {
386
- x = x.slice(0, length);
387
- }
388
- if (reserved) {
389
- return x.replace(/%[0-9a-fA-F]{2}|./gsu, (m => {
390
- let v = PERCENT_RE.test(m) ? decodeURIComponent(m) : m;
391
- if (UR_SET.test(v)) {
392
- return percentEncode(v);
393
- }
394
- return m;
395
- }));
396
- }
397
- return x.replace(UNRESERVED, percentEncode);
398
- }
399
-
400
- const UTF8_ENCODER = new TextEncoder;
401
-
402
- function percentEncode(str) {
403
- return Array.from(UTF8_ENCODER.encode(str)).map((i => "%" + i.toString(16).toUpperCase().padStart(2, "0"))).join("");
404
- }
405
-
406
- exports.UriTemplate = UriTemplate;
package/dist/bundle.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export { UriTemplate } from './uri-template';
2
- export type { UrlParamValue, UriMatch, UriParams } from './uri-template';