@surgijs/router 0.0.0-stage → 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1123 @@
1
+ export { readSnapshot, serializeSnapshot } from './chunk-LY6JNBHA.js';
2
+ import { interceptLinks } from './chunk-OQUB6NVM.js';
3
+ export { autoScroll, interceptLinks, isNativeAnchor, isPlainClick } from './chunk-OQUB6NVM.js';
4
+ import { isThenable, drive, deepEqual } from './chunk-W2SIXU6O.js';
5
+
6
+ // src/history.ts
7
+ var entryOf = (state) => state && typeof state === "object" && typeof state.i === "number" ? state : null;
8
+ function browser(place, read, fromHref) {
9
+ let index = 0;
10
+ const location2 = () => ({ url: read() ?? "/", state: entryOf(history.state)?.s });
11
+ return {
12
+ kind: "browser",
13
+ read() {
14
+ const entry = entryOf(history.state);
15
+ if (entry) index = entry.i;
16
+ else history.replaceState({ i: index = 0 }, "");
17
+ return location2();
18
+ },
19
+ push(url, state) {
20
+ history.pushState({ i: ++index, s: state }, "", place(url));
21
+ },
22
+ replace(url, state) {
23
+ history.replaceState({ i: index, s: state }, "", place(url));
24
+ },
25
+ go: (delta) => history.go(delta),
26
+ listen(callback) {
27
+ const onPop = () => {
28
+ const entry = entryOf(history.state);
29
+ const i = entry ? entry.i : index + 1;
30
+ if (!entry) history.replaceState({ i }, "");
31
+ const delta = i - index;
32
+ index = i;
33
+ if (read() === null) return;
34
+ callback(location2(), delta);
35
+ };
36
+ window.addEventListener("popstate", onPop);
37
+ return () => window.removeEventListener("popstate", onPop);
38
+ },
39
+ href: place,
40
+ fromHref
41
+ };
42
+ }
43
+ var trimBase = (base) => (base ?? "").replace(/\/+$/, "").replace(/^(?!\/)(?=.)/, "/");
44
+ function slashHistory(options = {}) {
45
+ const base = trimBase(options.base);
46
+ const strip = (path) => {
47
+ if (!base) return path;
48
+ if (path === base) return "/";
49
+ return path.startsWith(base + "/") ? path.slice(base.length) : null;
50
+ };
51
+ return browser(
52
+ (url) => base + url,
53
+ () => (strip(location.pathname) ?? "/") + location.search + location.hash,
54
+ (url) => {
55
+ if (url.origin !== location.origin) return null;
56
+ const path = strip(url.pathname);
57
+ return path === null ? null : path + url.search + url.hash;
58
+ }
59
+ );
60
+ }
61
+ var withSlash = (url) => url.startsWith("/") ? url : "/" + url;
62
+ function prefixCodec(prefix) {
63
+ return {
64
+ parse: (hash) => hash.startsWith(prefix) ? withSlash(hash.slice(prefix.length)) : null,
65
+ format: (url) => prefix + url
66
+ };
67
+ }
68
+ function keyCodec(key) {
69
+ const pairs = (hash) => hash.slice(1).split("&").filter(Boolean);
70
+ const owns = (pair) => pair.startsWith(key + "=");
71
+ return {
72
+ parse(hash) {
73
+ const pair = pairs(hash).find(owns);
74
+ if (!pair) return null;
75
+ try {
76
+ return withSlash(decodeURIComponent(pair.slice(key.length + 1)));
77
+ } catch {
78
+ return null;
79
+ }
80
+ },
81
+ format(url, hash) {
82
+ const mine = `${key}=${encodeURIComponent(url)}`;
83
+ const rest = pairs(hash);
84
+ const at = rest.findIndex(owns);
85
+ if (at < 0) rest.push(mine);
86
+ else rest[at] = mine;
87
+ return "#" + rest.join("&");
88
+ }
89
+ };
90
+ }
91
+ function hashHistory(options = {}) {
92
+ const codec = options.codec ?? (options.key ? keyCodec(options.key) : prefixCodec(options.prefix ?? "#"));
93
+ return browser(
94
+ (url) => location.pathname + location.search + codec.format(url, location.hash),
95
+ () => codec.parse(location.hash),
96
+ (url) => {
97
+ if (url.origin !== location.origin || url.pathname !== location.pathname || url.search !== location.search) return null;
98
+ return codec.parse(url.hash);
99
+ }
100
+ );
101
+ }
102
+ function memoryHistory(initial = "/") {
103
+ const entries = [{ url: withSlash(initial), state: void 0 }];
104
+ let at = 0;
105
+ const listeners = /* @__PURE__ */ new Set();
106
+ return {
107
+ kind: "memory",
108
+ read: () => entries[at],
109
+ push(url, state) {
110
+ entries.splice(at + 1, entries.length, { url, state });
111
+ at++;
112
+ },
113
+ replace(url, state) {
114
+ entries[at] = { url, state };
115
+ },
116
+ go(delta) {
117
+ const next = Math.max(0, Math.min(entries.length - 1, at + delta));
118
+ const moved = next - at;
119
+ if (!moved) return;
120
+ at = next;
121
+ for (const listener of [...listeners]) listener(entries[at], moved);
122
+ },
123
+ listen(callback) {
124
+ listeners.add(callback);
125
+ return () => listeners.delete(callback);
126
+ },
127
+ href: (url) => url,
128
+ fromHref: (url) => typeof location !== "undefined" && url.origin !== location.origin ? null : url.pathname + url.search + url.hash
129
+ };
130
+ }
131
+
132
+ // src/path.ts
133
+ var STATIC = 0;
134
+ var PARAM = 1;
135
+ var OPTIONAL = 2;
136
+ var SPLAT = 3;
137
+ function parsePattern(pattern) {
138
+ const segs = [];
139
+ for (const part of pattern.split("/")) {
140
+ if (!part) continue;
141
+ const last = segs[segs.length - 1];
142
+ if (last && last.kind === SPLAT) throw new Error(`@surgijs/router: a splat must be the last segment in "${pattern}"`);
143
+ if (part[0] === "*") segs.push({ kind: SPLAT, name: part.slice(1) || "*" });
144
+ else if (part[0] === ":") {
145
+ const optional = part.endsWith("?");
146
+ const name = part.slice(1, optional ? -1 : void 0);
147
+ if (!name) throw new Error(`@surgijs/router: empty parameter name in "${pattern}"`);
148
+ segs.push({ kind: optional ? OPTIONAL : PARAM, name });
149
+ } else segs.push({ kind: STATIC, name: part });
150
+ if (last && last.kind === OPTIONAL && segs[segs.length - 1].kind !== OPTIONAL && part[0] !== "*") {
151
+ throw new Error(`@surgijs/router: an optional parameter must come last in "${pattern}"`);
152
+ }
153
+ }
154
+ return segs;
155
+ }
156
+ function patternOf(segs) {
157
+ return "/" + segs.map((s) => s.kind === STATIC ? s.name : s.kind === PARAM ? ":" + s.name : s.kind === OPTIONAL ? `:${s.name}?` : "*" + (s.name === "*" ? "" : s.name)).join("/");
158
+ }
159
+ var WEIGHT = [4, 3, 2, 1];
160
+ var scoreOf = (segs) => segs.map((s) => WEIGHT[s.kind]);
161
+ function compareScores(a, b) {
162
+ const n = Math.min(a.length, b.length);
163
+ for (let i = 0; i < n; i++) if (a[i] !== b[i]) return b[i] - a[i];
164
+ return a.length - b.length;
165
+ }
166
+ function decode(s) {
167
+ try {
168
+ return decodeURIComponent(s);
169
+ } catch {
170
+ return s;
171
+ }
172
+ }
173
+ function splitPath(path) {
174
+ const out = [];
175
+ for (const part of path.split("/")) if (part) out.push(decode(part));
176
+ return out;
177
+ }
178
+ function matchSegments(segs, parts, caseSensitive) {
179
+ const params = {};
180
+ let i = 0;
181
+ for (const s of segs) {
182
+ if (s.kind === SPLAT) {
183
+ params[s.name] = parts.slice(i).map((p2) => p2.replace(/\//g, "%2F")).join("/");
184
+ return params;
185
+ }
186
+ if (i >= parts.length) {
187
+ if (s.kind === OPTIONAL) continue;
188
+ return null;
189
+ }
190
+ const part = parts[i++];
191
+ if (s.kind === STATIC) {
192
+ if (caseSensitive ? part !== s.name : part.toLowerCase() !== s.name.toLowerCase()) return null;
193
+ } else if (s.name !== "__proto__") params[s.name] = part;
194
+ }
195
+ return i === parts.length ? params : null;
196
+ }
197
+ function matchPath(pattern, pathname, options = {}) {
198
+ return matchSegments(parsePattern(pattern), splitPath(pathname), options.caseSensitive ?? false);
199
+ }
200
+ function buildPath(segs, params) {
201
+ let out = "";
202
+ for (const s of segs) {
203
+ if (s.kind === STATIC) out += "/" + encodeURIComponent(s.name);
204
+ else {
205
+ const v = params[s.name];
206
+ if (v === void 0 || v === null || v === "") {
207
+ if (s.kind === PARAM) throw new Error(`@surgijs/router: missing path parameter "${s.name}"`);
208
+ break;
209
+ }
210
+ const text = String(v);
211
+ out += "/" + (s.kind === SPLAT ? text.split("/").map((p2) => encodeURIComponent(p2).replace(/%252F/gi, "%2F")).join("/") : encodeURIComponent(text));
212
+ }
213
+ }
214
+ return out || "/";
215
+ }
216
+ function parseQuery(search) {
217
+ const out = {};
218
+ for (const [k, v] of new URLSearchParams(search)) {
219
+ if (k === "__proto__") continue;
220
+ const prev = out[k];
221
+ if (prev === void 0) out[k] = v;
222
+ else if (Array.isArray(prev)) prev.push(v);
223
+ else out[k] = [prev, v];
224
+ }
225
+ return out;
226
+ }
227
+ function stringifyQuery(query) {
228
+ const params = new URLSearchParams();
229
+ for (const k in query) {
230
+ const v = query[k];
231
+ if (v === void 0) continue;
232
+ if (Array.isArray(v)) for (const item of v) params.append(k, item);
233
+ else params.append(k, v);
234
+ }
235
+ const s = params.toString();
236
+ return s ? "?" + s : "";
237
+ }
238
+ var KEEP = /%(24|26|2B|2C|3A|3B|3D|40|5B|5D|5E|7C)/g;
239
+ function normalizePath(path) {
240
+ const body = path.replace(/^[\\/]+/, "");
241
+ return "/" + body.split("/").map((seg) => encodeURIComponent(decode(seg)).replace(KEEP, (m) => decodeURIComponent(m))).join("/");
242
+ }
243
+ function splitUrl(url) {
244
+ const h = url.indexOf("#");
245
+ const hash = h < 0 ? "" : url.slice(h);
246
+ const rest = h < 0 ? url : url.slice(0, h);
247
+ const q = rest.indexOf("?");
248
+ const search = q < 0 ? "" : rest.slice(q);
249
+ const path = q < 0 ? rest : rest.slice(0, q);
250
+ return { path: normalizePath(path), search: search === "?" ? "" : search, hash: hash === "#" ? "" : hash };
251
+ }
252
+ var joinUrl = (u) => u.path + u.search + u.hash;
253
+ function resolveUrl(to, from) {
254
+ if (/^[\\/][\\/]|^\\/.test(to)) throw new Error(`@surgijs/router: "${to}" leaves the site; a target must not start with // or a backslash`);
255
+ if (to === "") return joinUrl(from);
256
+ if (to[0] === "#") return from.path + from.search + (to === "#" ? "" : to);
257
+ if (to[0] === "?") return from.path + (to === "?" ? "" : to);
258
+ if (to[0] === "/") return joinUrl(splitUrl(to));
259
+ const target = splitUrl("/" + to);
260
+ const stack = from.path.split("/").filter(Boolean);
261
+ for (const part of target.path.split("/")) {
262
+ if (!part || part === ".") continue;
263
+ if (part === "..") stack.pop();
264
+ else stack.push(part);
265
+ }
266
+ return "/" + stack.join("/") + target.search + target.hash;
267
+ }
268
+ var hashSuffix = (hash) => hash === "" ? "" : hash[0] === "#" ? hash : "#" + hash;
269
+
270
+ // src/schema.ts
271
+ var BAD = /* @__PURE__ */ Symbol("bad");
272
+ var toArray = (raw) => raw === void 0 ? [] : Array.isArray(raw) ? raw : [raw];
273
+ var first = (raw) => Array.isArray(raw) ? raw[0] : raw;
274
+ function make(def, hasDefault, decode2, encode, emptyIsValue = false) {
275
+ return {
276
+ hasDefault,
277
+ fallback: def,
278
+ parse(raw) {
279
+ const s = first(raw);
280
+ if (s === void 0 || s === "" && !emptyIsValue) return { ok: true, value: def };
281
+ const v = decode2(s);
282
+ return v === BAD ? { ok: false, error: `invalid value "${s}"` } : { ok: true, value: v };
283
+ },
284
+ format: (v) => encode(v)
285
+ };
286
+ }
287
+ function string(o) {
288
+ return make(
289
+ o?.default,
290
+ o?.default !== void 0,
291
+ (s) => (o?.minLength === void 0 || s.length >= o.minLength) && (o?.maxLength === void 0 || s.length <= o.maxLength) && (!o?.pattern || o.pattern.test(s)) ? s : BAD,
292
+ (v) => v,
293
+ true
294
+ );
295
+ }
296
+ var inRange = (n, o) => (o?.min === void 0 || n >= o.min) && (o?.max === void 0 || n <= o.max);
297
+ function number(o) {
298
+ return make(
299
+ o?.default,
300
+ o?.default !== void 0,
301
+ (s) => {
302
+ const n = Number(s);
303
+ return Number.isFinite(n) && inRange(n, o) ? n : BAD;
304
+ },
305
+ String
306
+ );
307
+ }
308
+ function int(o) {
309
+ return make(
310
+ o?.default,
311
+ o?.default !== void 0,
312
+ (s) => /^-?\d+$/.test(s) && inRange(+s, o) ? +s : BAD,
313
+ String
314
+ );
315
+ }
316
+ function boolean(o) {
317
+ return make(
318
+ o?.default,
319
+ o?.default !== void 0,
320
+ (s) => s === "" || s === "true" || s === "1" ? true : s === "false" || s === "0" ? false : BAD,
321
+ (v) => v ? "true" : "false",
322
+ true
323
+ );
324
+ }
325
+ function oneOf(values, o) {
326
+ return make(o?.default, o?.default !== void 0, (s) => values.includes(s) ? s : BAD, (v) => v);
327
+ }
328
+ function json(o) {
329
+ return make(
330
+ o?.default,
331
+ o?.default !== void 0,
332
+ (s) => {
333
+ try {
334
+ return JSON.parse(s);
335
+ } catch {
336
+ return BAD;
337
+ }
338
+ },
339
+ (v) => JSON.stringify(v)
340
+ );
341
+ }
342
+ function custom(decode2, encode, o) {
343
+ return make(
344
+ o?.default,
345
+ o?.default !== void 0,
346
+ (s) => {
347
+ try {
348
+ const v = decode2(s);
349
+ return v === void 0 ? BAD : v;
350
+ } catch {
351
+ return BAD;
352
+ }
353
+ },
354
+ encode
355
+ );
356
+ }
357
+ function array(item, o = {}) {
358
+ const comma = o.format === "comma";
359
+ const def = o.default ?? [];
360
+ return {
361
+ hasDefault: true,
362
+ fallback: def,
363
+ parse(raw) {
364
+ if (raw === void 0) return { ok: true, value: def };
365
+ const parts = (comma ? toArray(raw).flatMap((s) => s.split(",")) : toArray(raw)).filter((s) => s !== "");
366
+ const out = [];
367
+ for (const part of parts) {
368
+ const r = item.parse(part);
369
+ if (!r.ok || r.value === void 0) return { ok: false, error: `invalid item "${part}"` };
370
+ out.push(r.value);
371
+ }
372
+ return { ok: true, value: out };
373
+ },
374
+ format(v) {
375
+ const items = v.map((x) => item.format(x));
376
+ if (!items.length) return void 0;
377
+ return comma ? items.join(",") : items;
378
+ }
379
+ };
380
+ }
381
+ var p = { string, number, int, boolean, enum: oneOf, array, json, custom };
382
+ function looseFormat(v) {
383
+ if (v === void 0 || v === null) return void 0;
384
+ if (Array.isArray(v)) return v.map((x) => typeof x === "string" ? x : String(looseFormat(x)));
385
+ if (typeof v === "object") return JSON.stringify(v);
386
+ return String(v);
387
+ }
388
+ var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
389
+ function isStandard(spec) {
390
+ return typeof spec === "object" && spec !== null && typeof spec["~standard"]?.validate === "function";
391
+ }
392
+ function loose(values) {
393
+ const out = {};
394
+ for (const k in values) {
395
+ const raw = looseFormat(values[k]);
396
+ if (raw !== void 0) out[k] = raw;
397
+ }
398
+ return out;
399
+ }
400
+ function validate(spec, input) {
401
+ const result = spec["~standard"].validate(input);
402
+ if (isThenable(result)) throw new Error("@surgijs/router: asynchronous schemas are not supported in params and query");
403
+ return result;
404
+ }
405
+ function compileSpec(spec) {
406
+ if (isStandard(spec)) {
407
+ return {
408
+ keys: null,
409
+ parse(raw) {
410
+ const r = validate(spec, raw);
411
+ if (!r.issues) return { ok: true, value: r.value ?? {} };
412
+ const empty = validate(spec, {});
413
+ return { ok: false, value: empty.issues ? {} : empty.value ?? {} };
414
+ },
415
+ format: (values) => loose(values)
416
+ };
417
+ }
418
+ if (typeof spec === "function") {
419
+ return {
420
+ keys: null,
421
+ parse(raw) {
422
+ try {
423
+ return { ok: true, value: spec(raw) ?? {} };
424
+ } catch {
425
+ return { ok: false, value: {} };
426
+ }
427
+ },
428
+ format: (values) => loose(values)
429
+ };
430
+ }
431
+ const fields = spec;
432
+ const keys = Object.keys(fields);
433
+ return {
434
+ keys,
435
+ parse(raw) {
436
+ let ok = true;
437
+ const value = {};
438
+ for (const k of keys) {
439
+ const r = fields[k].parse(raw[k]);
440
+ if (r.ok) {
441
+ if (r.value !== void 0) value[k] = r.value;
442
+ } else {
443
+ ok = false;
444
+ const fallback = fields[k].fallback;
445
+ if (fallback !== void 0) value[k] = fallback;
446
+ }
447
+ }
448
+ return { ok, value };
449
+ },
450
+ format(values, strip) {
451
+ const out = {};
452
+ for (const k in values) {
453
+ const f = fields[k];
454
+ const v = values[k];
455
+ if (v === void 0 || v === null) continue;
456
+ const raw = f ? f.format(v) : looseFormat(v);
457
+ if (raw === void 0) continue;
458
+ if (strip && f?.hasDefault && same(raw, f.format(f.fallback))) continue;
459
+ out[k] = raw;
460
+ }
461
+ return out;
462
+ }
463
+ };
464
+ }
465
+
466
+ // src/routes.ts
467
+ var Redirect = class {
468
+ constructor(to, status, options = {}) {
469
+ this.to = to;
470
+ this.status = status;
471
+ this.options = options;
472
+ }
473
+ to;
474
+ status;
475
+ options;
476
+ };
477
+ function redirect(to, init = {}) {
478
+ const { status = 302, ...options } = typeof init === "number" ? { status: init } : init;
479
+ return new Redirect(to, status, options);
480
+ }
481
+ function defineRoute(def) {
482
+ return def;
483
+ }
484
+ function defineRoutes(routes) {
485
+ return routes;
486
+ }
487
+ var RouteRecord = class {
488
+ constructor(id, def, parent, segs) {
489
+ this.id = id;
490
+ this.def = def;
491
+ this.parent = parent;
492
+ this.segs = segs;
493
+ this.component = def.component;
494
+ this.lazy = def.lazy;
495
+ this.errorComponent = def.errorComponent;
496
+ this.meta = def.meta ?? {};
497
+ this.params = def.params ? compileSpec(def.params) : null;
498
+ this.query = def.query ? compileSpec(def.query) : null;
499
+ this.pattern = patternOf(segs);
500
+ this.score = scoreOf(segs);
501
+ }
502
+ id;
503
+ def;
504
+ parent;
505
+ segs;
506
+ component;
507
+ lazy;
508
+ loading;
509
+ errorComponent;
510
+ meta;
511
+ params;
512
+ query;
513
+ pattern;
514
+ score;
515
+ children = [];
516
+ /** The records from the outermost route down to this one. */
517
+ get chain() {
518
+ const out = [];
519
+ for (let r = this; r; r = r.parent) out.unshift(r);
520
+ return out;
521
+ }
522
+ };
523
+ function resolveChain(chain, rawParams, search, strict) {
524
+ const params = { ...rawParams };
525
+ for (const r of chain) {
526
+ if (!r.params) continue;
527
+ const res = r.params.parse(rawParams);
528
+ if (!res.ok) return null;
529
+ Object.assign(params, res.value);
530
+ }
531
+ const raw = parseQuery(search);
532
+ if (!chain.some((r) => r.query)) return { params, query: raw };
533
+ const query = {};
534
+ for (const r of chain) {
535
+ if (!r.query) continue;
536
+ const res = r.query.parse(raw);
537
+ if (!res.ok && (r.def.strictQuery ?? strict)) return null;
538
+ Object.assign(query, res.value);
539
+ }
540
+ return { params, query };
541
+ }
542
+ var LOOSE = compileSpec({});
543
+ var RouteTable = class {
544
+ records = [];
545
+ byDef = /* @__PURE__ */ new Map();
546
+ statics = /* @__PURE__ */ new Map();
547
+ dynamic = [];
548
+ cs;
549
+ strict;
550
+ constructor(defs, options = {}) {
551
+ this.cs = options.caseSensitive ?? false;
552
+ this.strict = options.strictQuery ?? false;
553
+ const attach = (def, parent) => {
554
+ if (this.byDef.has(def)) return;
555
+ const own = parsePattern(def.path);
556
+ const segs = def.path.startsWith("/") || !parent ? own : [...parent.segs, ...own];
557
+ const record = new RouteRecord(this.records.length, def, parent, segs);
558
+ this.records.push(record);
559
+ this.byDef.set(def, record);
560
+ parent?.children.push(record);
561
+ for (const child of def.children ?? []) attach(child, record);
562
+ };
563
+ let deferred = [];
564
+ for (const def of defs) {
565
+ if (def.parent) deferred.push(def);
566
+ else attach(def, null);
567
+ }
568
+ while (deferred.length) {
569
+ const next = [];
570
+ for (const def of deferred) {
571
+ const parent = this.byDef.get(def.parent);
572
+ if (parent) attach(def, parent);
573
+ else next.push(def);
574
+ }
575
+ if (next.length === deferred.length) throw new Error(`@surgijs/router: the parent of route "${next[0].path}" is not part of the routes`);
576
+ deferred = next;
577
+ }
578
+ for (const record of this.records) {
579
+ if (record.children.length) continue;
580
+ this.validate(record);
581
+ if (record.segs.every((s) => s.kind === 0)) {
582
+ const key = this.key(record.segs.map((s) => s.name));
583
+ if (!this.statics.has(key)) this.statics.set(key, record);
584
+ } else this.dynamic.push(record);
585
+ }
586
+ this.dynamic.sort((a, b) => compareScores(a.score, b.score));
587
+ }
588
+ validate(record) {
589
+ let tail = false;
590
+ for (const s of record.segs) {
591
+ if (tail) throw new Error(`@surgijs/router: "${record.pattern}" has a segment after an optional parameter or a splat`);
592
+ if (s.kind === 2 || s.kind === 3) tail = true;
593
+ }
594
+ }
595
+ key(parts) {
596
+ const joined = parts.join("/");
597
+ return this.cs ? joined : joined.toLowerCase();
598
+ }
599
+ /** The most specific route for `path` whose parameters (and, in strict mode, query) are valid. */
600
+ find(path, search) {
601
+ const parts = splitPath(path);
602
+ const hit = this.statics.get(this.key(parts));
603
+ if (hit && matchSegments(hit.segs, parts, this.cs)) {
604
+ const chain = hit.chain;
605
+ const resolved = resolveChain(chain, {}, search, this.strict);
606
+ if (resolved) return { chain, ...resolved };
607
+ }
608
+ for (const record of this.dynamic) {
609
+ const raw = matchSegments(record.segs, parts, this.cs);
610
+ if (!raw) continue;
611
+ const chain = record.chain;
612
+ const resolved = resolveChain(chain, raw, search, this.strict);
613
+ if (resolved) return { chain, ...resolved };
614
+ }
615
+ return null;
616
+ }
617
+ /** Formats typed values with the specs of `chain`; keys no spec knows are written as they are. */
618
+ formatQuery(chain, values, strip = true) {
619
+ const out = {};
620
+ const rest = { ...values };
621
+ for (const r of chain) {
622
+ if (!r.query?.keys) continue;
623
+ const own = {};
624
+ for (const k of r.query.keys) {
625
+ if (k in rest) {
626
+ own[k] = rest[k];
627
+ delete rest[k];
628
+ }
629
+ }
630
+ Object.assign(out, r.query.format(own, strip));
631
+ }
632
+ const generic = chain.find((r) => r.query && !r.query.keys)?.query;
633
+ Object.assign(out, generic ? generic.format(rest, strip) : LOOSE.format(rest, strip));
634
+ return out;
635
+ }
636
+ formatParams(chain, values) {
637
+ const out = { ...values };
638
+ for (const r of chain) {
639
+ if (!r.params) continue;
640
+ const formatted = r.params.format(values, false);
641
+ for (const k in formatted) out[k] = formatted[k];
642
+ }
643
+ return out;
644
+ }
645
+ };
646
+
647
+ // src/router.ts
648
+ var SCHEME = /^[a-z][a-z\d+.-]*:/i;
649
+ var toRedirect = (v) => v instanceof Redirect ? v : typeof v === "string" ? new Redirect(v, 302) : null;
650
+ function waitRemote(store, key, signal) {
651
+ let stop;
652
+ let finished = false;
653
+ let resolve;
654
+ const done = new Promise((r) => resolve = r);
655
+ const finish = () => {
656
+ if (finished) return;
657
+ finished = true;
658
+ resolve();
659
+ };
660
+ stop = store.subscribe(
661
+ () => store.status(key),
662
+ (st) => {
663
+ if (!st.isFetching) finish();
664
+ },
665
+ { equals: () => false }
666
+ );
667
+ const release = () => {
668
+ stop?.();
669
+ stop = void 0;
670
+ finish();
671
+ };
672
+ if (!store.status(key).isFetching) return { release, done: void 0 };
673
+ signal.addEventListener("abort", finish, { once: true });
674
+ return { release, done };
675
+ }
676
+ var slice = (s) => ({ path: s.path, params: s.params, query: s.query, hash: s.hash });
677
+ var share = (prev, next) => deepEqual(prev, next) ? prev : next;
678
+ function blank() {
679
+ return {
680
+ url: "",
681
+ path: "",
682
+ search: "",
683
+ hash: "",
684
+ params: {},
685
+ query: {},
686
+ matches: [],
687
+ route: null,
688
+ status: 0,
689
+ data: [],
690
+ state: void 0,
691
+ error: null,
692
+ redirect: null,
693
+ isPending: false,
694
+ pending: null
695
+ };
696
+ }
697
+ function createRouter(options) {
698
+ const table = new RouteTable(options.routes, options);
699
+ const driver = options.history ?? (options.url !== void 0 || typeof window === "undefined" ? memoryHistory(options.url ?? "/") : slashHistory({ base: options.base }));
700
+ const store = options.store;
701
+ const storeKey = options.storeKey ?? "route";
702
+ if (store && !(storeKey in store.get())) {
703
+ throw new Error(`@surgijs/router: the store has no "${storeKey}" field; add \`${storeKey}: { path: '/', params: {}, query: {}, hash: '' }\` to createStore`);
704
+ }
705
+ let state = blank();
706
+ let dataKeys = [];
707
+ let navId = 0;
708
+ let ctrl = null;
709
+ let ignorePops = 0;
710
+ let popOffset = 0;
711
+ let retained = [];
712
+ let snapshot = options.snapshot;
713
+ const subs = /* @__PURE__ */ new Set();
714
+ const each = [];
715
+ const after = /* @__PURE__ */ new Set();
716
+ const leaving = /* @__PURE__ */ new Set();
717
+ const notify = () => {
718
+ for (const sub of [...subs]) {
719
+ try {
720
+ const value = sub.selector(state);
721
+ if (sub.equals(sub.value, value)) continue;
722
+ const prev = sub.value;
723
+ sub.value = value;
724
+ sub.listener(value, prev);
725
+ } catch (e) {
726
+ console.error("[@surgijs/router]", e);
727
+ }
728
+ }
729
+ };
730
+ const runAfter = (to, from, info) => {
731
+ for (const hook of [...after]) {
732
+ try {
733
+ hook(to, from);
734
+ } catch (e) {
735
+ console.error("[@surgijs/router]", e);
736
+ }
737
+ }
738
+ if (!info) return;
739
+ try {
740
+ options.scroll?.(to, from, info);
741
+ } catch (e) {
742
+ console.error("[@surgijs/router]", e);
743
+ }
744
+ };
745
+ const loadLazy = (rec) => {
746
+ if (!rec.lazy) return Promise.resolve();
747
+ return rec.loading ||= rec.lazy().then(
748
+ (mod) => {
749
+ rec.component = mod && typeof mod === "object" && "default" in mod ? mod.default : mod;
750
+ rec.lazy = void 0;
751
+ },
752
+ (error) => {
753
+ rec.loading = void 0;
754
+ throw error;
755
+ }
756
+ );
757
+ };
758
+ const keyOf = (rec, params, search) => {
759
+ const own = {};
760
+ for (const s of rec.segs) if (s.kind !== 0) own[s.name] = params[s.name];
761
+ return JSON.stringify([rec.id, own, search]);
762
+ };
763
+ const redirectUrl = (r, from) => {
764
+ const { params, query, hash } = r.options;
765
+ return resolve(r.to, { params, query, hash }, from);
766
+ };
767
+ function resolve(to, opts = {}, base) {
768
+ const cur = base ?? state;
769
+ const from = splitUrl(cur.url || driver.read().url);
770
+ const tail = (path, search, hash, chain2) => path + (opts.query ? stringifyQuery(table.formatQuery(chain2, opts.query)) : search) + (opts.hash !== void 0 ? hashSuffix(opts.hash) : hash);
771
+ if (typeof to === "string") {
772
+ if (SCHEME.test(to)) throw new Error(`@surgijs/router: "${to}" is outside the router; use a plain <a href> or location.assign`);
773
+ const url = splitUrl(resolveUrl(to, from));
774
+ if (!opts.query) return tail(url.path, url.search, opts.hash !== void 0 ? "" : url.hash, []);
775
+ return tail(url.path, "", url.hash, table.find(url.path, "")?.chain ?? []);
776
+ }
777
+ const rec = table.byDef.get(to);
778
+ if (!rec) throw new Error(`@surgijs/router: route "${to.path}" is not part of this router's routes`);
779
+ const chain = rec.chain;
780
+ const params = table.formatParams(chain, { ...cur.params, ...opts.params });
781
+ return tail(buildPath(rec.segs, params), "", "", chain);
782
+ }
783
+ const setPending = (url) => {
784
+ state = { ...state, isPending: true, pending: url };
785
+ notify();
786
+ };
787
+ const releaseAll = (list) => {
788
+ for (const release of list) release();
789
+ };
790
+ function* pipeline(req, id, signal) {
791
+ const from = state.url ? state : null;
792
+ const stale = () => id !== navId;
793
+ const cancelled = () => ({ type: "cancelled", state });
794
+ const blocked = () => ({ type: "blocked", state });
795
+ const aborted = new Promise((resolve2) => signal.addEventListener("abort", () => resolve2(), { once: true }));
796
+ const wait = (v) => isThenable(v) ? Promise.race([v, aborted]) : v;
797
+ const first2 = splitUrl(req.url);
798
+ if (from && !req.initial && first2.path === from.path && first2.search === from.search) {
799
+ const url2 = joinUrl(first2);
800
+ if (!req.pop) driver[req.replace || url2 === from.url ? "replace" : "push"](url2, req.state);
801
+ state = { ...from, url: url2, hash: first2.hash, state: req.state, redirect: null, isPending: false, pending: null };
802
+ popOffset = 0;
803
+ if (store) store.set(storeKey, slice(state));
804
+ notify();
805
+ runAfter(state, from, req.pop ? null : { pop: false });
806
+ return { type: "done", state };
807
+ }
808
+ if (from) {
809
+ for (const guard of [...leaving]) {
810
+ const ok = yield wait(guard({ to: req.url, from }));
811
+ if (stale()) return cancelled();
812
+ if (ok === false) return blocked();
813
+ }
814
+ }
815
+ let url = req.url;
816
+ let replace = req.replace;
817
+ let redirected = null;
818
+ for (let hop = 0; ; hop++) {
819
+ if (hop > 8) throw new Error(`@surgijs/router: too many redirects starting at "${req.url}"`);
820
+ const parts = splitUrl(url);
821
+ const found = table.find(parts.path, parts.search);
822
+ const chain = found?.chain ?? [];
823
+ const leaf = chain[chain.length - 1];
824
+ const loc = {
825
+ url: joinUrl(parts),
826
+ path: parts.path,
827
+ search: parts.search,
828
+ hash: parts.hash,
829
+ params: found?.params ?? {},
830
+ query: found?.query ?? parseQuery(parts.search),
831
+ matches: chain.map((route) => ({ route, params: found.params })),
832
+ route: leaf ?? null
833
+ };
834
+ if (options.canonical && found) {
835
+ const raw = parseQuery(parts.search);
836
+ for (const k in found.query) delete raw[k];
837
+ for (const rec of chain) rec.query?.keys?.forEach((k) => delete raw[k]);
838
+ const search = stringifyQuery({ ...raw, ...table.formatQuery(chain, found.query) });
839
+ if (search !== parts.search) {
840
+ url = parts.path + search + parts.hash;
841
+ continue;
842
+ }
843
+ }
844
+ const ctx = { to: loc, from, params: loc.params, query: loc.query, signal, store, router };
845
+ const box = { target: null, failure: null };
846
+ const fail = (error, level) => {
847
+ if (error instanceof Redirect) box.target ??= error;
848
+ else if (!box.failure || level < box.failure.level) box.failure = { error, level };
849
+ };
850
+ if (leaf?.def.redirect) {
851
+ const r = leaf.def.redirect;
852
+ box.target = toRedirect(typeof r === "function" ? r(ctx) : r);
853
+ }
854
+ if (!box.target) {
855
+ const steps = [
856
+ ...each.map((g) => [g, Math.max(0, chain.length - 1)]),
857
+ ...chain.flatMap((rec, level) => [].concat(rec.def.beforeEnter ?? []).map((g) => [g, level]))
858
+ ];
859
+ for (const [guard, level] of steps) {
860
+ let res;
861
+ try {
862
+ res = yield wait(guard(ctx));
863
+ } catch (error) {
864
+ if (stale()) return cancelled();
865
+ fail(error, level);
866
+ break;
867
+ }
868
+ if (stale()) return cancelled();
869
+ if (res === false) return blocked();
870
+ if (box.target = toRedirect(res)) break;
871
+ }
872
+ }
873
+ if (box.target) {
874
+ const r = box.target;
875
+ url = redirectUrl(r, loc);
876
+ redirected = { from: redirected?.from ?? req.url, status: r.status };
877
+ replace = r.options.replace ?? replace;
878
+ continue;
879
+ }
880
+ const data = new Array(chain.length);
881
+ const keys = chain.map((rec) => keyOf(rec, loc.params, parts.search));
882
+ const work = [];
883
+ const next = [];
884
+ const denied = box.failure !== null;
885
+ const hydrated = req.initial && snapshot && splitUrl(snapshot.url).path === parts.path && splitUrl(snapshot.url).search === parts.search ? snapshot.data : null;
886
+ if (!denied) chain.forEach((rec, level) => {
887
+ if (rec.lazy) work.push(loadLazy(rec).catch((e) => fail(e, level)));
888
+ });
889
+ if (store && !denied) {
890
+ const preload = /* @__PURE__ */ new Map();
891
+ chain.forEach((rec, level) => rec.def.preload?.forEach((key) => preload.has(key) || preload.set(key, level)));
892
+ if (preload.size) {
893
+ store.set(storeKey, slice(loc));
894
+ for (const [key, level] of preload) {
895
+ try {
896
+ const w = waitRemote(store, key, signal);
897
+ next.push(w.release);
898
+ if (w.done) work.push(w.done);
899
+ } catch (e) {
900
+ fail(e, level);
901
+ }
902
+ }
903
+ }
904
+ }
905
+ if (!denied) chain.forEach((rec, level) => {
906
+ const load = rec.def.load;
907
+ if (!load) return;
908
+ if (hydrated) {
909
+ data[level] = hydrated[level];
910
+ return;
911
+ }
912
+ if (from && dataKeys[level] === keys[level] && from.matches[level]?.route === rec && from.error?.level !== level) {
913
+ data[level] = from.data[level];
914
+ return;
915
+ }
916
+ try {
917
+ const result = load(ctx);
918
+ if (isThenable(result)) {
919
+ work.push(
920
+ Promise.resolve(result).then(
921
+ (v) => void (data[level] = v),
922
+ (e) => fail(e, level)
923
+ )
924
+ );
925
+ } else data[level] = result;
926
+ } catch (e) {
927
+ fail(e, level);
928
+ }
929
+ });
930
+ if (work.length) yield wait(Promise.all(work));
931
+ if (stale()) {
932
+ releaseAll(next);
933
+ return cancelled();
934
+ }
935
+ const late = box.target;
936
+ if (late) {
937
+ releaseAll(next);
938
+ const r = late;
939
+ url = redirectUrl(r, loc);
940
+ redirected = { from: redirected?.from ?? req.url, status: r.status };
941
+ replace = r.options.replace ?? replace;
942
+ continue;
943
+ }
944
+ const failed = box.failure;
945
+ let at2 = failed ? failed.level : 0;
946
+ if (failed) {
947
+ for (let i = failed.level; i >= 0; i--) if (chain[i].errorComponent) {
948
+ at2 = i;
949
+ break;
950
+ }
951
+ }
952
+ const params = share(state.params, loc.params);
953
+ const committed = {
954
+ ...loc,
955
+ params,
956
+ query: share(state.query, loc.query),
957
+ matches: chain.map((route, i) => {
958
+ const prev = state.matches[i];
959
+ return prev && prev.route === route && prev.params === params ? prev : { route, params };
960
+ }),
961
+ status: failed ? 500 : leaf?.def.status ?? (found ? 200 : 404),
962
+ data: share(state.data, data),
963
+ state: req.state,
964
+ error: failed ? { error: failed.error, level: failed.level, at: at2 } : null,
965
+ redirect: redirected,
966
+ isPending: false,
967
+ pending: null
968
+ };
969
+ const finalUrl = committed.url;
970
+ if (req.initial) {
971
+ if (finalUrl !== driver.read().url) driver.replace(finalUrl, req.state);
972
+ } else if (req.pop) {
973
+ if (finalUrl !== req.url) driver.replace(finalUrl, req.state);
974
+ } else driver[replace || finalUrl === from?.url ? "replace" : "push"](finalUrl, req.state);
975
+ const old = retained;
976
+ retained = next;
977
+ state = committed;
978
+ dataKeys = keys;
979
+ popOffset = 0;
980
+ if (store) store.set(storeKey, slice(committed));
981
+ releaseAll(old);
982
+ notify();
983
+ runAfter(committed, from, req.initial ? null : { pop: !!req.pop });
984
+ return { type: "done", state: committed };
985
+ }
986
+ }
987
+ const start = (req) => {
988
+ const id = ++navId;
989
+ ctrl?.abort();
990
+ ctrl = new AbortController();
991
+ const settle = () => {
992
+ if (id === navId && state.isPending) {
993
+ state = { ...state, isPending: false, pending: null };
994
+ notify();
995
+ }
996
+ };
997
+ let out;
998
+ try {
999
+ out = drive(pipeline({ ...req, url: joinUrl(splitUrl(req.url)) }, id, ctrl.signal), () => id === navId && setPending(req.url));
1000
+ } catch (e) {
1001
+ settle();
1002
+ return Promise.reject(e);
1003
+ }
1004
+ return Promise.resolve(out).then(
1005
+ (result) => {
1006
+ if (result.type !== "done") {
1007
+ settle();
1008
+ if (store && state.url && id === navId) store.set(storeKey, slice(state));
1009
+ if (result.type === "blocked" && req.pop && id === navId) {
1010
+ if (popOffset) {
1011
+ ignorePops++;
1012
+ driver.go(-popOffset);
1013
+ } else driver.replace(state.url, state.state);
1014
+ }
1015
+ }
1016
+ return result;
1017
+ },
1018
+ (e) => {
1019
+ settle();
1020
+ if (store && state.url && id === navId) store.set(storeKey, slice(state));
1021
+ throw e;
1022
+ }
1023
+ );
1024
+ };
1025
+ const navigate = (replace) => ((to, opts = {}) => start({ url: resolve(to, opts), replace: replace ?? !!opts.replace, state: opts.state }));
1026
+ const unlisten = driver.listen((loc, delta) => {
1027
+ popOffset += delta;
1028
+ if (ignorePops > 0) {
1029
+ ignorePops--;
1030
+ return;
1031
+ }
1032
+ start({ url: loc.url, replace: true, state: loc.state, pop: true, delta }).catch((e) => console.error("[@surgijs/router]", e));
1033
+ });
1034
+ const router = {
1035
+ history: driver,
1036
+ store,
1037
+ routes: table.records,
1038
+ get: ((selector) => selector ? selector(state) : state),
1039
+ subscribe(selector, listener, opts) {
1040
+ const sub = { selector, listener, equals: opts?.equals ?? deepEqual, value: selector(state) };
1041
+ subs.add(sub);
1042
+ if (opts?.fireImmediately) listener(sub.value, sub.value);
1043
+ return () => void subs.delete(sub);
1044
+ },
1045
+ navigate: navigate(void 0),
1046
+ push: navigate(false),
1047
+ replace: navigate(true),
1048
+ back: () => driver.go(-1),
1049
+ forward: () => driver.go(1),
1050
+ go: (delta) => driver.go(delta),
1051
+ setQuery(patch, opts) {
1052
+ const cur = state.query;
1053
+ const next = typeof patch === "function" ? patch(cur) : { ...cur, ...patch };
1054
+ const rest = parseQuery(state.search);
1055
+ for (const k in cur) delete rest[k];
1056
+ for (const k in next) delete rest[k];
1057
+ const chain = state.matches.map((m) => m.route);
1058
+ const search = stringifyQuery({ ...rest, ...table.formatQuery(chain, next) });
1059
+ return start({ url: state.path + search + state.hash, replace: !!opts?.replace, state: opts?.state });
1060
+ },
1061
+ href: ((to, opts) => driver.href(resolve(to, opts))),
1062
+ resolve: ((to, opts) => resolve(to, opts)),
1063
+ isActive(to, opts = {}) {
1064
+ const fold = (path) => (options.caseSensitive ? path : path.toLowerCase()).split("/").filter(Boolean);
1065
+ const target = fold(splitUrl(resolve(to, { params: opts.params })).path);
1066
+ const cur = fold(state.path);
1067
+ if (opts.exact) return target.length === cur.length && target.every((s, i) => s === cur[i]);
1068
+ return target.length <= cur.length && target.every((s, i) => s === cur[i]);
1069
+ },
1070
+ async prefetch(to, opts) {
1071
+ const url = splitUrl(resolve(to, opts));
1072
+ const found = table.find(url.path, url.search);
1073
+ await Promise.all((found?.chain ?? []).map((rec) => loadLazy(rec).catch(() => {
1074
+ })));
1075
+ },
1076
+ beforeEach(guard) {
1077
+ each.push(guard);
1078
+ return () => void each.splice(each.indexOf(guard) >>> 0, 1);
1079
+ },
1080
+ afterEach(hook) {
1081
+ after.add(hook);
1082
+ return () => void after.delete(hook);
1083
+ },
1084
+ beforeLeave(guard) {
1085
+ leaving.add(guard);
1086
+ return () => void leaving.delete(guard);
1087
+ },
1088
+ ready: () => initial,
1089
+ snapshot(opts) {
1090
+ return { url: state.path + state.search, data: state.data, store: store?.dehydrate?.(opts) };
1091
+ },
1092
+ destroy() {
1093
+ ctrl?.abort();
1094
+ navId++;
1095
+ unlisten();
1096
+ stopIntercept();
1097
+ releaseAll(retained);
1098
+ retained = [];
1099
+ subs.clear();
1100
+ }
1101
+ };
1102
+ if (snapshot?.store && store?.hydrate) store.hydrate(snapshot.store);
1103
+ const at = driver.read();
1104
+ const initial = start({ url: at.url, replace: true, state: at.state, initial: true }).then(
1105
+ () => {
1106
+ snapshot = void 0;
1107
+ },
1108
+ (e) => {
1109
+ snapshot = void 0;
1110
+ console.error("[@surgijs/router]", e);
1111
+ throw e;
1112
+ }
1113
+ );
1114
+ initial.catch(() => {
1115
+ });
1116
+ const stopIntercept = (options.intercept ?? driver.kind === "browser") && typeof document !== "undefined" ? interceptLinks(router) : () => {
1117
+ };
1118
+ return router;
1119
+ }
1120
+
1121
+ export { Redirect, RouteRecord, createRouter, defineRoute, defineRoutes, hashHistory, matchPath, memoryHistory, p, parseQuery, redirect, slashHistory, stringifyQuery };
1122
+ //# sourceMappingURL=index.js.map
1123
+ //# sourceMappingURL=index.js.map