@oomfware/stacker 0.1.0 → 0.1.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.
package/README.md CHANGED
@@ -78,6 +78,9 @@ const routes = defineRoutes({
78
78
  });
79
79
  ```
80
80
 
81
+ routes are matched in declaration order, so declare specific paths ahead of broader ones that would
82
+ also match.
83
+
81
84
  configure `type` to control page instance lifetimes:
82
85
 
83
86
  ```ts
@@ -110,6 +113,19 @@ route({
110
113
  path parameters are always required. query parameters without a default or optional codec must be
111
114
  present in the URL to match the route.
112
115
 
116
+ end a path with `*name` to capture the rest of the URL, separators included. a splat also matches
117
+ its bare parent path, where the remainder is empty:
118
+
119
+ ```ts
120
+ route({ component: Docs, params: { rest: string() }, path: '/docs/*rest' });
121
+
122
+ // /docs/guide/intro -> { rest: 'guide/intro' }
123
+ // /docs -> { rest: '' }
124
+ ```
125
+
126
+ swap `string()` for `nonEmpty()` to reject the empty remainder, which leaves `/docs` to fall through
127
+ to the next matching route.
128
+
113
129
  write custom codecs by defining `decode` and `encode` methods:
114
130
 
115
131
  ```ts
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as HistoryLocation, i as HistoryListener, n as HistoryAction, o as HistoryNavigateOptions, r as HistoryEntry, s as HistoryUpdate, t as History } from "./types-Dj7Al7f8.mjs";
1
+ import { a as HistoryLocation, c as HistoryUpdate, i as HistoryListener, n as HistoryAction, o as HistoryNavigateOptions, r as HistoryEntry, s as HistoryScrollBehavior, t as History } from "./types-KOb6CZ7N.mjs";
2
2
  import { AnchorHTMLAttributes, ComponentType, EffectCallback, ReactElement, ReactNode } from "react";
3
3
  //#region src/codec.d.ts
4
4
  /**
@@ -74,6 +74,16 @@ declare const boolean: () => Codec<boolean>;
74
74
  * @returns the enum codec
75
75
  */
76
76
  declare const enumOf: <const V extends readonly string[]>(values: V) => Codec<V[number]>;
77
+ /**
78
+ * creates a codec for a string that rejects the empty value.
79
+ *
80
+ * this is how a splat route demands at least one trailing segment: `/docs/*rest` otherwise matches `/docs`
81
+ * itself with an empty remainder, and rejecting it lets the URL fall through to a later route. ordinary path
82
+ * params can never be empty, so the distinction only matters for splats and query params.
83
+ *
84
+ * @returns the non-empty string codec
85
+ */
86
+ declare const nonEmpty: () => Codec<string>;
77
87
  /**
78
88
  * wraps a codec to allow its parameter to be absent.
79
89
  *
@@ -354,6 +364,8 @@ interface RouterOptions<R extends RouteRegistry<unknown>> {
354
364
  readonly pins?: readonly string[];
355
365
  /** compiled route registry. */
356
366
  readonly routes: R;
367
+ /** window whose scroll position the router restores, defaulting to the global one where there is one. */
368
+ readonly window?: Window;
357
369
  }
358
370
  /**
359
371
  * manages navigation state, history subscriptions, and active views.
@@ -545,4 +557,4 @@ interface LinkProps extends Omit<AnchorHTMLAttributes<HTMLAnchorElement>, 'href'
545
557
  */
546
558
  declare const Link: ({ children, onClick, replace, to, ...rest }: LinkProps) => ReactElement;
547
559
  //#endregion
548
- export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
560
+ export { type BuildParamsOf, type Codec, type DefaultedCodec, type History, type HistoryAction, type HistoryEntry, type HistoryListener, type HistoryLocation, type HistoryNavigateOptions, type HistoryScrollBehavior, type HistoryUpdate, type Infer, type InstanceNode, type LayoutConfig, type LayoutNode, type LeafType, Link, type LinkProps, type MatchedNode, NavigationHistory, type NavigationHistoryOptions, type OptionalCodec, Outlet, type ParamsOf, type QueryPatchOf, type ReadonlyURLSearchParams, type ResolvedLeaf, type ResolvedNode, type RouteChildren, type RouteConfig, type RouteLeaf, type RouteMatch, type RouteMeta, type RouteName, type RouteNode, type RouteRegistry, Router, type RouterHooks, type RouterOptions, RouterView, type View, type WhenContext, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as parsePath, t as createPath } from "./url-CoOVqRk_.mjs";
1
+ import { i as parsePath, n as decodeRemainder, r as encodeRemainder, t as createPath } from "./url-gf-m_-s3.mjs";
2
2
  import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
3
3
  import { Suspense, createContext, useContext, useEffect, useLayoutEffect, useMemo, useSyncExternalStore } from "react";
4
4
  import { Fragment, jsx } from "react/jsx-runtime";
@@ -59,6 +59,22 @@ const enumOf = (values) => {
59
59
  };
60
60
  };
61
61
  /**
62
+ * creates a codec for a string that rejects the empty value.
63
+ *
64
+ * this is how a splat route demands at least one trailing segment: `/docs/*rest` otherwise matches `/docs`
65
+ * itself with an empty remainder, and rejecting it lets the URL fall through to a later route. ordinary path
66
+ * params can never be empty, so the distinction only matters for splats and query params.
67
+ *
68
+ * @returns the non-empty string codec
69
+ */
70
+ const nonEmpty = () => ({
71
+ decode: (raw) => raw === "" ? void 0 : raw,
72
+ encode: (value) => {
73
+ if (value === "") throw new Error("stacker: nonEmpty() cannot encode an empty string");
74
+ return value;
75
+ }
76
+ });
77
+ /**
62
78
  * wraps a codec to allow its parameter to be absent.
63
79
  *
64
80
  * @param codec the inner codec
@@ -110,14 +126,40 @@ const layout = (config) => ({
110
126
  ...config
111
127
  });
112
128
  const PATH_PARAM = /:([A-Za-z_]\w*)/g;
129
+ const SPLAT = /\/\*([A-Za-z_]\w*)$/;
130
+ /**
131
+ * splits a route pattern into the part before its trailing splat and the splat parameter name.
132
+ *
133
+ * @param path the route path pattern
134
+ * @returns the head preceding the splat, and the splat name when the pattern declares one
135
+ */
136
+ const splitSplat = (path) => {
137
+ const match = SPLAT.exec(path);
138
+ return match === null ? {
139
+ head: path,
140
+ splat: void 0
141
+ } : {
142
+ head: path.slice(0, match.index),
143
+ splat: match[1]
144
+ };
145
+ };
113
146
  const pathParamNames = (path) => {
147
+ const { head, splat } = splitSplat(path);
114
148
  const names = [];
115
- for (const match of path.matchAll(PATH_PARAM)) {
149
+ for (const match of head.matchAll(PATH_PARAM)) {
116
150
  const name = match[1];
117
151
  if (name !== void 0) names.push(name);
118
152
  }
153
+ if (splat !== void 0) names.push(splat);
119
154
  return names;
120
155
  };
156
+ /**
157
+ * rejects a `*` that is not a well-formed trailing splat, so that a typo fails at load time rather than
158
+ * silently compiling into a literal asterisk.
159
+ */
160
+ const assertSplatPlacement = (key, path) => {
161
+ if (splitSplat(path).head.includes("*")) throw new Error(`stacker: route '${key}' path '${path}' may only use '*' as a named trailing splat, as in '/docs/*rest'`);
162
+ };
121
163
  const sameKeySet = (a, b) => {
122
164
  if (a.length !== b.length) return false;
123
165
  const set = new Set(a);
@@ -155,6 +197,7 @@ const defineRoutes = (tree) => {
155
197
  }
156
198
  if (leaves.has(key)) throw new Error(`stacker: duplicate route name '${key}'`);
157
199
  if (!node.path.startsWith("/")) throw new Error(`stacker: route '${key}' path '${node.path}' must start with '/'`);
200
+ assertSplatPlacement(key, node.path);
158
201
  const query = node.query ?? {};
159
202
  const ownPathParams = pathParamNames(node.path);
160
203
  const declaredParams = Object.keys(params);
@@ -199,20 +242,30 @@ const resolveMeta = (match, key) => {
199
242
  const SEGMENT$1 = /:[A-Za-z_]\w*/g;
200
243
  const escapeRegExp = (segment) => segment.replaceAll(/[$()*+.?[\\\]^{|}]/g, "\\$&");
201
244
  const compile = (path) => {
245
+ const { head, splat } = splitSplat(path);
202
246
  const paramNames = [];
203
247
  let pattern = "";
204
248
  let lastIndex = 0;
205
- for (const match of path.matchAll(SEGMENT$1)) {
249
+ for (const match of head.matchAll(SEGMENT$1)) {
206
250
  const whole = match[0];
207
251
  const at = match.index;
208
252
  if (at === void 0) continue;
209
253
  paramNames.push(whole.slice(1));
210
- pattern += `${escapeRegExp(path.slice(lastIndex, at))}([^/]+)`;
254
+ pattern += `${escapeRegExp(head.slice(lastIndex, at))}([^/]+)`;
211
255
  lastIndex = at + whole.length;
212
256
  }
213
- pattern += escapeRegExp(path.slice(lastIndex));
257
+ pattern += escapeRegExp(head.slice(lastIndex));
258
+ if (splat !== void 0) {
259
+ paramNames.push(splat);
260
+ return {
261
+ hasSplat: true,
262
+ paramNames,
263
+ regex: new RegExp(`^${pattern}(?:/(.*))?$`)
264
+ };
265
+ }
214
266
  const suffix = pattern.endsWith("/") ? "" : "/?";
215
267
  return {
268
+ hasSplat: false,
216
269
  paramNames,
217
270
  regex: new RegExp(`^${pattern}${suffix}$`)
218
271
  };
@@ -222,8 +275,9 @@ var Matcher = class {
222
275
  #compiled;
223
276
  constructor(registry) {
224
277
  this.#compiled = [...registry.leaves.values()].map((leaf) => {
225
- const { paramNames, regex } = compile(leaf.path);
278
+ const { hasSplat, paramNames, regex } = compile(leaf.path);
226
279
  return {
280
+ hasSplat,
227
281
  leaf,
228
282
  paramNames,
229
283
  regex
@@ -238,10 +292,11 @@ var Matcher = class {
238
292
  rawSearch,
239
293
  search
240
294
  };
241
- for (const { leaf, paramNames, regex } of this.#compiled) {
295
+ for (const compiled of this.#compiled) {
296
+ const { leaf, regex } = compiled;
242
297
  const execed = regex.exec(pathname);
243
298
  if (execed === null) continue;
244
- const raw = this.#rawValues(paramNames, execed);
299
+ const raw = this.#rawValues(compiled, execed);
245
300
  if (raw === void 0) continue;
246
301
  const perNode = this.#decodeChain(leaf.chain, raw);
247
302
  if (perNode === void 0) continue;
@@ -266,10 +321,19 @@ var Matcher = class {
266
321
  };
267
322
  }
268
323
  }
269
- #rawValues(paramNames, execed) {
324
+ #rawValues({ hasSplat, paramNames }, execed) {
325
+ const splatIndex = hasSplat ? paramNames.length - 1 : -1;
270
326
  const raw = {};
271
327
  for (const [i, name] of paramNames.entries()) {
272
328
  const value = execed[i + 1];
329
+ if (i === splatIndex) {
330
+ try {
331
+ raw[name] = decodeRemainder(value ?? "");
332
+ } catch {
333
+ return;
334
+ }
335
+ continue;
336
+ }
273
337
  if (value === void 0) return;
274
338
  try {
275
339
  raw[name] = decodeURIComponent(value);
@@ -345,6 +409,7 @@ var NavigationHistory = class {
345
409
  this.#ignore = options.ignore;
346
410
  this.#location = this.#read();
347
411
  this.#nav.addEventListener("navigate", this.#onNavigate);
412
+ this.#win.history.scrollRestoration = "manual";
348
413
  }
349
414
  get location() {
350
415
  return this.#location;
@@ -430,16 +495,18 @@ var NavigationHistory = class {
430
495
  if (action !== "traverse" && this.#ignore?.(new URL(event.destination.url))) return;
431
496
  const envelope = isEnvelope(event.info) ? event.info : void 0;
432
497
  const info = envelope === void 0 ? event.info : envelope.info;
433
- const preserve = (envelope?.scroll ?? "auto") === "preserve";
498
+ const scroll = envelope?.scroll ?? "auto";
499
+ const preserve = scroll === "preserve";
434
500
  event.intercept({
435
501
  focusReset: preserve ? "manual" : "after-transition",
436
- scroll: preserve ? "manual" : "after-transition",
502
+ scroll: "manual",
437
503
  handler: async () => {
438
504
  this.#location = this.#read();
439
505
  const update = {
440
506
  action,
441
507
  info,
442
- location: this.#location
508
+ location: this.#location,
509
+ scroll
443
510
  };
444
511
  await Promise.all([...this.#listeners].map(async (listener) => listener(update)));
445
512
  }
@@ -465,12 +532,26 @@ var Builder = class {
465
532
  buildPath(name, params = {}) {
466
533
  const leaf = this.#registry.leaves.get(name);
467
534
  if (leaf === void 0) throw new Error(`stacker: unknown route '${name}'`);
468
- const pathname = leaf.path.replaceAll(SEGMENT, (_full, paramName) => {
535
+ const encodeParam = (paramName) => {
469
536
  const codec = leaf.params[paramName];
470
537
  const value = params[paramName];
471
538
  if (codec === void 0 || value === void 0) throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
472
- return encodeURIComponent(codec.encode(value));
539
+ return codec.encode(value);
540
+ };
541
+ const rejectDotSegments = (segments, paramName) => {
542
+ for (const segment of segments) if (segment === "." || segment === "..") throw new Error(`stacker: path param '${paramName}' for route '${name}' cannot contain a '${segment}' segment`);
543
+ };
544
+ const { head, splat } = splitSplat(leaf.path);
545
+ let pathname = head.replaceAll(SEGMENT, (_full, paramName) => {
546
+ const encoded = encodeParam(paramName);
547
+ rejectDotSegments([encoded], paramName);
548
+ return encodeURIComponent(encoded);
473
549
  });
550
+ if (splat !== void 0) {
551
+ const remainder = encodeParam(splat);
552
+ rejectDotSegments(remainder.split("/"), splat);
553
+ if (remainder !== "") pathname += `/${encodeRemainder(remainder)}`;
554
+ }
474
555
  const search = new URLSearchParams();
475
556
  for (const [paramName, codec] of Object.entries(leaf.query)) {
476
557
  const value = params[paramName];
@@ -581,6 +662,10 @@ const computeView = (cached, pinned, activeKey) => {
581
662
  //#endregion
582
663
  //#region src/router.ts
583
664
  const DefaultNotFound = () => null;
665
+ const TOP = {
666
+ x: 0,
667
+ y: 0
668
+ };
584
669
  /**
585
670
  * manages navigation state, history subscriptions, and active views.
586
671
  *
@@ -596,6 +681,7 @@ var Router = class {
596
681
  #defaultFallback;
597
682
  #notFound;
598
683
  #pins;
684
+ #win;
599
685
  #updates = new SimpleEventEmitter();
600
686
  #unlisten;
601
687
  #activePins = /* @__PURE__ */ new Set();
@@ -614,18 +700,34 @@ var Router = class {
614
700
  this.#defaultFallback = options.defaultFallback;
615
701
  this.#notFound = makeNotFound(options.notFound ?? DefaultNotFound);
616
702
  this.#pins = new Map((options.pins ?? []).map((name) => [name, this.#makePin(name)]));
703
+ this.#win = options.window ?? (typeof window === "undefined" ? null : window);
617
704
  const location = this.#history.location;
618
705
  this.#activeKey = location.key;
619
- this.#record(location);
706
+ this.#record(location, TOP);
620
707
  this.#view = this.#recompute();
621
- this.#unlisten = this.#history.listen(async ({ location: next }) => {
708
+ this.#unlisten = this.#history.listen(async ({ action, location: next, scroll }) => {
709
+ const win = this.#win;
710
+ const restoring = scroll === "auto" && win !== null;
711
+ if (restoring) {
712
+ const outgoing = this.#entries.get(this.#activeKey);
713
+ if (outgoing !== void 0) outgoing.scrollPos = {
714
+ x: win.scrollX,
715
+ y: win.scrollY
716
+ };
717
+ }
622
718
  this.#prune();
623
- this.#record(next);
719
+ const target = (action === "traverse" ? this.#entries.get(next.key)?.scrollPos : void 0) ?? TOP;
720
+ this.#record(next, target);
624
721
  this.#activeKey = next.key;
625
722
  this.#view = this.#recompute();
626
723
  const committed = this.#awaitCommit();
627
724
  this.#updates.emit();
628
725
  await committed;
726
+ if (restoring) win.scrollTo({
727
+ behavior: "instant",
728
+ left: target.x,
729
+ top: target.y
730
+ });
629
731
  });
630
732
  }
631
733
  /** current view structure. */
@@ -804,11 +906,12 @@ var Router = class {
804
906
  const live = new Set(this.#history.entries().map((entry) => entry.key));
805
907
  for (const key of this.#entries.keys()) if (!live.has(key)) this.#entries.delete(key);
806
908
  }
807
- #record(location) {
909
+ #record(location, scrollPos) {
808
910
  const entry = {
809
911
  index: location.index,
810
912
  key: location.key,
811
- match: this.#match(location)
913
+ match: this.#match(location),
914
+ scrollPos
812
915
  };
813
916
  this.#entries.set(location.key, entry);
814
917
  this.#recency = [entry.key, ...this.#recency.filter((key) => key !== entry.key)];
@@ -1099,4 +1202,4 @@ const Link = ({ children, onClick, replace, to, ...rest }) => {
1099
1202
  });
1100
1203
  };
1101
1204
  //#endregion
1102
- export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
1205
+ export { Link, NavigationHistory, Outlet, Router, RouterView, boolean, createRouterHooks, defineRoutes, enumOf, integer, layout, nonEmpty, optional, resolveMeta, route, string, useFocusEffect, useIsFocused, useLocation, useParams, useRoute, useRouter, withDefault };
@@ -1,4 +1,4 @@
1
- import { a as HistoryLocation, i as HistoryListener, o as HistoryNavigateOptions, r as HistoryEntry, t as History } from "./types-Dj7Al7f8.mjs";
1
+ import { a as HistoryLocation, i as HistoryListener, o as HistoryNavigateOptions, r as HistoryEntry, t as History } from "./types-KOb6CZ7N.mjs";
2
2
  //#region src/history/memory.d.ts
3
3
  /** options for the memory history constructor. */
4
4
  interface MemoryHistoryOptions {
package/dist/testing.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { r as resolvePath, t as createPath } from "./url-CoOVqRk_.mjs";
1
+ import { a as resolvePath, t as createPath } from "./url-gf-m_-s3.mjs";
2
2
  import { SimpleEventEmitter } from "@mary-ext/simple-event-emitter";
3
3
  //#region src/history/memory.ts
4
4
  const ROOT = {
@@ -50,7 +50,8 @@ var MemoryHistory = class {
50
50
  this.#emit({
51
51
  action: "push",
52
52
  info: options.info,
53
- location
53
+ location,
54
+ scroll: options.scroll ?? "auto"
54
55
  });
55
56
  }
56
57
  replace(to, options = {}) {
@@ -60,7 +61,8 @@ var MemoryHistory = class {
60
61
  this.#emit({
61
62
  action: "replace",
62
63
  info: options.info,
63
- location
64
+ location,
65
+ scroll: options.scroll ?? "auto"
64
66
  });
65
67
  }
66
68
  traverseTo(key) {
@@ -75,7 +77,8 @@ var MemoryHistory = class {
75
77
  this.#emit({
76
78
  action: "traverse",
77
79
  info: void 0,
78
- location: this.#current()
80
+ location: this.#current(),
81
+ scroll: "auto"
79
82
  });
80
83
  }
81
84
  back() {
@@ -40,11 +40,11 @@ interface HistoryLocation {
40
40
  readonly state: unknown;
41
41
  }
42
42
  /**
43
- * how a history write treats the user's place on the page — scroll position and focus, which the browser
44
- * resets together and which a write therefore cannot sensibly split apart.
43
+ * how a history write treats the user's place on the page — scroll position and focus, which a write cannot
44
+ * sensibly split apart.
45
45
  *
46
- * - `auto` — a new screen. the browser restores scroll on a traversal or resets it on a push, and moves focus
47
- * to the new content.
46
+ * - `auto` — a new screen. scroll is restored on a traversal if the offset is still known and reset to the top
47
+ * otherwise, and focus moves to the new content.
48
48
  * - `preserve` — the same screen with different state, like an in-place parameter patch. scroll and focus are
49
49
  * both left exactly where the user put them.
50
50
  */
@@ -64,11 +64,13 @@ interface HistoryUpdate {
64
64
  /** metadata passed to the write operation. */
65
65
  readonly info: unknown;
66
66
  readonly location: HistoryLocation;
67
+ /** viewport behavior, which listeners apply. */
68
+ readonly scroll: HistoryScrollBehavior;
67
69
  }
68
70
  /**
69
71
  * history update callback subscriber.
70
72
  *
71
- * listeners can return a promise to defer scroll restoration and focus resets.
73
+ * listeners can return a promise to defer focus resets.
72
74
  */
73
75
  type HistoryListener = (update: HistoryUpdate) => void | Promise<void>;
74
76
  /** history manager interface modeled on the web navigation API. */
@@ -126,4 +128,4 @@ interface History {
126
128
  traverseTo(key: string): void;
127
129
  }
128
130
  //#endregion
129
- export { HistoryLocation as a, HistoryListener as i, HistoryAction as n, HistoryNavigateOptions as o, HistoryEntry as r, HistoryUpdate as s, History as t };
131
+ export { HistoryLocation as a, HistoryUpdate as c, HistoryListener as i, HistoryAction as n, HistoryNavigateOptions as o, HistoryEntry as r, HistoryScrollBehavior as s, History as t };
@@ -27,6 +27,14 @@ const resolvePath = (to, base) => {
27
27
  search: resolved.search
28
28
  };
29
29
  };
30
+ /**
31
+ * decodes a splat remainder one segment at a time, so that separators survive decoding.
32
+ *
33
+ * an encoded `%2F` therefore decodes to a literal `/` and is indistinguishable from a real separator.
34
+ */
35
+ const decodeRemainder = (raw) => raw.split("/").map(decodeURIComponent).join("/");
36
+ /** encodes a splat remainder one segment at a time, the inverse of {@link decodeRemainder}. */
37
+ const encodeRemainder = (value) => value.split("/").map(encodeURIComponent).join("/");
30
38
  const createPath = ({ hash, pathname, search }) => {
31
39
  let out = pathname || "/";
32
40
  if (search && search !== "?") out += search.startsWith("?") ? search : `?${search}`;
@@ -34,4 +42,4 @@ const createPath = ({ hash, pathname, search }) => {
34
42
  return out;
35
43
  };
36
44
  //#endregion
37
- export { parsePath as n, resolvePath as r, createPath as t };
45
+ export { resolvePath as a, parsePath as i, decodeRemainder as n, encodeRemainder as r, createPath as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oomfware/stacker",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "type-safe stack router for React",
5
5
  "license": "0BSD",
6
6
  "repository": {
@@ -8,12 +8,7 @@
8
8
  "url": "https://codeberg.org/oomfware/stacker"
9
9
  },
10
10
  "files": [
11
- "dist/",
12
- "src/",
13
- "!src/**/*.test.ts",
14
- "!src/**/*.test.tsx",
15
- "!src/**/*.test-d.ts",
16
- "!src/test-support.ts"
11
+ "dist/"
17
12
  ],
18
13
  "type": "module",
19
14
  "types": "./dist/index.d.mts",
@@ -47,13 +42,13 @@
47
42
  "bumpp": "^11.1.0",
48
43
  "oxfmt": "^0.59.0",
49
44
  "oxlint": "^1.74.0",
50
- "oxlint-tsgolint": "^0.24.0",
45
+ "oxlint-tsgolint": "^0.25.0",
51
46
  "playwright": "^1.61.1",
52
47
  "react": "^19.2.7",
53
48
  "react-dom": "^19.2.7",
54
- "tsdown": "^0.22.8",
49
+ "tsdown": "^0.22.9",
55
50
  "typescript": "^7.0.2",
56
- "vite": "^8.1.4",
51
+ "vite": "^8.1.5",
57
52
  "vitest": "^4.1.10"
58
53
  },
59
54
  "peerDependencies": {
package/src/build.ts DELETED
@@ -1,53 +0,0 @@
1
- import { getDefault, isOptional } from './codec.ts';
2
- import type { BuildParamsOf, RouteName, RouteRegistry } from './routes.ts';
3
- import { createPath } from './url.ts';
4
-
5
- const SEGMENT = /:([A-Za-z_]\w*)/g;
6
-
7
- export type BuildArgs<R, K extends RouteName<R>> =
8
- Record<never, never> extends BuildParamsOf<R, K>
9
- ? [params?: BuildParamsOf<R, K>]
10
- : [params: BuildParamsOf<R, K>];
11
-
12
- export class Builder<R extends RouteRegistry<unknown> = RouteRegistry<unknown>> {
13
- readonly #registry: R;
14
-
15
- constructor(registry: R) {
16
- this.#registry = registry;
17
- }
18
-
19
- build<K extends RouteName<R>>(name: K, ...args: BuildArgs<R, K>): string {
20
- return this.buildPath(name, args[0] ?? {});
21
- }
22
-
23
- buildPath(name: string, params: Readonly<Record<string, unknown>> = {}): string {
24
- const leaf = this.#registry.leaves.get(name);
25
- if (leaf === undefined) {
26
- throw new Error(`stacker: unknown route '${name}'`);
27
- }
28
-
29
- const pathname = leaf.path.replaceAll(SEGMENT, (_full, paramName: string) => {
30
- const codec = leaf.params[paramName];
31
- const value = params[paramName];
32
- if (codec === undefined || value === undefined) {
33
- throw new Error(`stacker: missing path param '${paramName}' for route '${name}'`);
34
- }
35
- return encodeURIComponent(codec.encode(value));
36
- });
37
-
38
- const search = new URLSearchParams();
39
- for (const [paramName, codec] of Object.entries(leaf.query)) {
40
- const value = params[paramName];
41
- if (value === undefined) {
42
- if (!isOptional(codec) && getDefault(codec) === undefined) {
43
- throw new Error(`stacker: missing required query param '${paramName}' for route '${name}'`);
44
- }
45
- continue;
46
- }
47
- search.set(paramName, codec.encode(value));
48
- }
49
- const query = search.toString();
50
-
51
- return createPath({ hash: '', pathname, search: query ? `?${query}` : '' });
52
- }
53
- }
package/src/cache.ts DELETED
@@ -1,53 +0,0 @@
1
- export interface CacheEntryRef {
2
- readonly index: number;
3
- readonly key: string;
4
- }
5
-
6
- export interface CachePolicy {
7
- readonly max: number;
8
- }
9
-
10
- /**
11
- * computes which history entries to keep warm based on active index and recency.
12
- *
13
- * retains the active entry plus backward entries using an LRU policy. forward entries are dropped.
14
- */
15
- export const computeCachedKeys = (
16
- entries: readonly CacheEntryRef[],
17
- activeIndex: number,
18
- recency: readonly string[],
19
- policy: CachePolicy,
20
- ): Set<string> => {
21
- const cached = new Set<string>();
22
-
23
- const active = entries.find((entry) => entry.index === activeIndex);
24
- if (active === undefined) {
25
- throw new Error(`stacker: no history entry at active index ${activeIndex}`);
26
- }
27
- cached.add(active.key);
28
-
29
- const backward = new Map<string, CacheEntryRef>();
30
- for (const entry of entries) {
31
- if (entry.index < activeIndex) {
32
- backward.set(entry.key, entry);
33
- }
34
- }
35
-
36
- let kept = 0;
37
- const take = (key: string): void => {
38
- if (kept >= policy.max || cached.has(key) || !backward.has(key)) {
39
- return;
40
- }
41
- cached.add(key);
42
- kept += 1;
43
- };
44
-
45
- for (const key of recency) {
46
- take(key);
47
- }
48
- for (const entry of [...backward.values()].toSorted((a, b) => b.index - a.index)) {
49
- take(entry.key);
50
- }
51
-
52
- return cached;
53
- };