@opentf/afw 0.36.0 → 0.38.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.
@@ -0,0 +1,276 @@
1
+ // <Pending> — one loading state for every resource beneath it.
2
+ //
3
+ // <Pending fallback={<Skeleton/>} refreshing={<TopProgress/>} delay={200}>
4
+ // <UserList/>
5
+ // <Stats/>
6
+ // </Pending>
7
+ //
8
+ // Resources register with their nearest boundary (pending-scope.js). The boundary
9
+ // shows `fallback` until each has settled once, then its children. A later refetch
10
+ // keeps the children and shows `refreshing` beside them (or the fallback again with
11
+ // `refetch="fallback"`). A first-load failure shows `error(error, retry)` when given,
12
+ // and otherwise goes to the nearest <ErrorBoundary> (or the route's error.jsx).
13
+ //
14
+ // The children are built and connected the whole time, so their fetches start at
15
+ // once; a shadow root decides what is displayed — a `<slot>` for the children, or a
16
+ // named slot for the fallback. Both stay in the light DOM, so page CSS applies. The
17
+ // server renders the same shadow root declaratively, showing the fallback.
18
+
19
+ import { effect, signal, untracked } from "../core/signals.js";
20
+ import { isHydratable, toNodes } from "./dom.js";
21
+ import { handleError } from "./error-boundary.js";
22
+ import { HydrationMismatch, isHydrating } from "./hydrate.js";
23
+
24
+ const TAG = "afw-internal-pending";
25
+
26
+ function slotNamed(name) {
27
+ const slot = document.createElement("slot");
28
+ if (name) slot.name = name;
29
+ return slot;
30
+ }
31
+
32
+ export class PendingElement extends HTMLElement {
33
+ #tracked = signal([]);
34
+ /** A first-load failure this boundary shows itself (`error` prop): `{ error, retries }`. */
35
+ #failure = signal(null);
36
+ #error = null;
37
+ #held = null;
38
+ #fallback = null;
39
+ #refreshing = null;
40
+ #refetchMode = "keep";
41
+ #delay = 0;
42
+ #root = null;
43
+ #slots = null;
44
+ #dispose = null;
45
+ #timer = null;
46
+ /** What the shadow root displays: null (nothing), "fallback", "refreshing", "error" or "content". */
47
+ #shown = null;
48
+ /** Has the content been displayed once (later waits are refetches)? */
49
+ #revealed = false;
50
+ /** Server-rendered: wait for the children's hydration before deciding anything. */
51
+ #server = false;
52
+ #built = false;
53
+
54
+ set fallback(value) {
55
+ this.#fallback = value;
56
+ this.#place("fallback", value);
57
+ }
58
+ get fallback() {
59
+ return this.#fallback;
60
+ }
61
+ set refreshing(value) {
62
+ this.#refreshing = value;
63
+ this.#place("refreshing", value);
64
+ }
65
+ get refreshing() {
66
+ return this.#refreshing;
67
+ }
68
+ /** `(error, retry) => view`: show a failed first load here instead of passing it up. */
69
+ set error(fn) {
70
+ this.#error = typeof fn === "function" ? fn : null;
71
+ }
72
+ get error() {
73
+ return this.#error;
74
+ }
75
+ /** `"keep"` (default): content stays during a refetch. `"fallback"`: show the fallback again. */
76
+ set refetch(value) {
77
+ this.#refetchMode = value === "fallback" ? "fallback" : "keep";
78
+ }
79
+ get refetch() {
80
+ return this.#refetchMode;
81
+ }
82
+ /** Milliseconds to wait before showing the fallback or `refreshing`. */
83
+ set delay(value) {
84
+ this.#delay = Math.max(0, Number(value) || 0);
85
+ }
86
+ get delay() {
87
+ return this.#delay;
88
+ }
89
+
90
+ /**
91
+ * A resource (or lazy component) this boundary waits on. Read untracked: these run
92
+ * from inside other effects — a component connecting while a conditional region
93
+ * inserts it — which must not start depending on this boundary's list (the write
94
+ * that follows would re-run them, forever).
95
+ */
96
+ __track(handle) {
97
+ untracked(() => (this.#tracked.value = [...this.#tracked.value, handle]));
98
+ }
99
+ __untrack(handle) {
100
+ untracked(() => (this.#tracked.value = this.#tracked.value.filter((h) => h !== handle)));
101
+ }
102
+ /** The compiler finished building (or adopting) this boundary's children. */
103
+ __built() {
104
+ this.#built = true;
105
+ this.#start();
106
+ }
107
+ /**
108
+ * A tracked resource failed its first load. With an `error` prop, show it here (one
109
+ * view for every failure until retry); otherwise hand it to the nearest boundary.
110
+ */
111
+ __fail(error, handle) {
112
+ // Built but not yet in the document (a page still being assembled): no boundary
113
+ // above can be found yet, so hold the failure until it connects.
114
+ if (!this.isConnected) {
115
+ (this.#held ??= []).push([error, handle]);
116
+ return;
117
+ }
118
+ if (!this.#error) {
119
+ handleError(this, error, { phase: "resource", retry: () => handle.refetch() });
120
+ return;
121
+ }
122
+ const current = untracked(() => this.#failure.value);
123
+ if (current) {
124
+ current.retries.add(handle);
125
+ return;
126
+ }
127
+ const retries = new Set([handle]);
128
+ this.#failure.value = { error, retries };
129
+ let view = null;
130
+ try {
131
+ view = this.#error(error, () => this.#retry());
132
+ } catch (e) {
133
+ handleError(this, e, { phase: "fallback" });
134
+ }
135
+ this.#place("error", view);
136
+ }
137
+
138
+ /** Clear the error view and refetch what failed; the fallback shows while it reloads. */
139
+ #retry() {
140
+ const failure = untracked(() => this.#failure.value);
141
+ if (!failure) return;
142
+ this.#failure.value = null;
143
+ this.#place("error", null);
144
+ for (const handle of failure.retries) handle.refetch();
145
+ }
146
+
147
+ connectedCallback() {
148
+ if (!this.#root) {
149
+ // A server-rendered boundary already has its (declarative) shadow root, showing
150
+ // the fallback; keep displaying it until the resources say otherwise.
151
+ const server = this.shadowRoot;
152
+ if (server && server.querySelector('slot[name="fallback"]')) {
153
+ this.#shown = "fallback";
154
+ this.#server = true;
155
+ }
156
+ this.#root = server ?? this.attachShadow({ mode: "open" });
157
+ const style = document.createElement("style");
158
+ style.textContent = ":host{display:contents}";
159
+ this.#slots = { style, fallback: slotNamed("fallback"), refreshing: slotNamed("refreshing"), error: slotNamed("error"), content: slotNamed("") };
160
+ this.#render(this.#shown);
161
+ }
162
+ const held = this.#held;
163
+ this.#held = null;
164
+ if (held) for (const [error, handle] of held) this.__fail(error, handle);
165
+ this.#start();
166
+ }
167
+
168
+ // Start on a microtask: the child components connect after this element, and their
169
+ // resources register as they do. A server-rendered boundary also waits for the page's
170
+ // hydration code to adopt its children (`__built`), since the page's own resources
171
+ // register as that code reads them. Until then the current display stays.
172
+ #start() {
173
+ if (this.#server && !this.#built) return;
174
+ queueMicrotask(() => {
175
+ if (!this.isConnected || this.#dispose) return;
176
+ this.#dispose = effect(() => {
177
+ if (this.#failure.value) {
178
+ untracked(() => this.#update("error"));
179
+ return;
180
+ }
181
+ let waiting = false;
182
+ let busy = false;
183
+ for (const handle of this.#tracked.value) {
184
+ if (!handle.loading()) continue;
185
+ busy = true;
186
+ if (!handle.settled()) waiting = true;
187
+ }
188
+ const target = waiting || (busy && this.#refetchMode === "fallback")
189
+ ? "fallback"
190
+ : busy ? "refreshing" : "content";
191
+ untracked(() => this.#update(target));
192
+ });
193
+ });
194
+ }
195
+
196
+ disconnectedCallback() {
197
+ this.#dispose?.();
198
+ this.#dispose = null;
199
+ clearTimeout(this.#timer);
200
+ this.#timer = null;
201
+ }
202
+
203
+ #update(target) {
204
+ clearTimeout(this.#timer);
205
+ this.#timer = null;
206
+ if (target === "content" || target === "error" || target === this.#shown || this.#delay === 0 || this.#shown === "fallback") {
207
+ this.#show(target);
208
+ return;
209
+ }
210
+ // Wait `delay` before showing a loading state: a fast response never flashes one.
211
+ // Meanwhile a first load shows nothing and a refetch keeps the content.
212
+ this.#show(this.#revealed ? "content" : null);
213
+ this.#timer = setTimeout(() => {
214
+ this.#timer = null;
215
+ this.#show(target);
216
+ }, this.#delay);
217
+ }
218
+
219
+ #show(state) {
220
+ if (state === "content") this.#revealed = true;
221
+ // `data-pending`: a refetch is in progress and its loading state is showing.
222
+ this.toggleAttribute("data-pending", this.#revealed && (state === "refreshing" || state === "fallback"));
223
+ if (state === this.#shown) return;
224
+ this.#shown = state;
225
+ this.#render(state);
226
+ }
227
+
228
+ #render(state) {
229
+ const { style, fallback, refreshing, error, content } = this.#slots;
230
+ if (state === "error") this.#root.replaceChildren(style, error);
231
+ else if (state === "fallback") this.#root.replaceChildren(style, fallback);
232
+ else if (state === "refreshing") this.#root.replaceChildren(style, refreshing, content);
233
+ else if (state === "content") this.#root.replaceChildren(style, content);
234
+ else this.#root.replaceChildren(style);
235
+ }
236
+
237
+ /** Put `value` in the light DOM, wrapped for the named slot (replacing any previous one). */
238
+ #place(name, value) {
239
+ let wrapper = null;
240
+ for (const child of this.children) {
241
+ if (child.slot === name) {
242
+ wrapper = child;
243
+ break;
244
+ }
245
+ }
246
+ // Hydrating: adopt the fallback the server rendered instead of rebuilding it.
247
+ if (wrapper && isHydratable(value) && isHydrating() && !wrapper.__afwAdopted) {
248
+ try {
249
+ value.adopt({ node: wrapper.firstChild }, [...wrapper.childNodes]);
250
+ wrapper.__afwAdopted = true;
251
+ return;
252
+ } catch (error) {
253
+ if (!(error instanceof HydrationMismatch)) throw error;
254
+ }
255
+ }
256
+ const nodes = toNodes(value);
257
+ if (!nodes.length) {
258
+ wrapper?.remove();
259
+ return;
260
+ }
261
+ if (!wrapper) {
262
+ wrapper = document.createElement("span");
263
+ wrapper.slot = name;
264
+ wrapper.style.display = "contents";
265
+ this.prepend(wrapper);
266
+ }
267
+ wrapper.replaceChildren(...nodes);
268
+ }
269
+ }
270
+
271
+ // Exported so `import { Pending } from "@opentf/afw"` resolves; the import side
272
+ // effect registers the element (JSX uses the `afw-internal-pending` tag).
273
+ export const Pending = PendingElement;
274
+ if (typeof customElements !== "undefined" && !customElements.get(TAG)) {
275
+ customElements.define(TAG, PendingElement);
276
+ }
@@ -9,6 +9,12 @@ export interface ResourceOptions<T> {
9
9
  initial?: T;
10
10
  /** Server functions whose `invalidate()` refetches this resource, beyond those its fetcher calls as it starts. */
11
11
  invalidatedBy?: Array<(...args: any[]) => unknown>;
12
+ /**
13
+ * `"inline"` keeps failures on `error` only. By default, a resource a `<Pending>`
14
+ * waits on sends a first-load failure to the nearest `<ErrorBoundary>` and reports
15
+ * a failed refetch.
16
+ */
17
+ errors?: "inline";
12
18
  }
13
19
  export function resource<T>(fetcher: (value: true, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
14
20
  export function resource<S, T>(source: () => S, fetcher: (value: NonNullable<Exclude<S, false>>, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
@@ -21,8 +21,11 @@
21
21
  // the client's first paint renders before its own fetch resolves, keeping
22
22
  // hydration adoption aligned.
23
23
 
24
+ import { getCurrentInstance } from "../core/context.js";
25
+ import { reportError } from "../core/errors.js";
24
26
  import { batch, effect, signal, untracked } from "../core/signals.js";
25
27
  import { endpointOf, registerResource, unregisterResource, withTracking } from "./invalidate.js";
28
+ import { buildingPending, closestPending } from "./pending-scope.js";
26
29
 
27
30
  // Test override: the DOM suites run in esdev's `--dom` realm (a `document`
28
31
  // always exists), so server behavior is opted into explicitly.
@@ -45,10 +48,11 @@ const isServer = () => serverOverride ?? typeof document === "undefined";
45
48
  * @param {Function} source reactive source read inside the tracking effect; its
46
49
  * value is passed to the fetcher.
47
50
  * @param {Function} fetcher `(sourceValue, { signal }) => data | Promise<data>`.
48
- * @param {{ initial?: unknown, invalidatedBy?: Function[] }} [options] `initial`
49
- * seeds `data` before the first resolution. `invalidatedBy` names server
50
- * functions whose `invalidate()` refetches this resource, beyond those its
51
- * fetcher calls as it starts (which are recorded automatically).
51
+ * @param {{ initial?: unknown, invalidatedBy?: Function[], errors?: "inline" }} [options]
52
+ * `initial` seeds `data` before the first resolution. `invalidatedBy` names
53
+ * server functions whose `invalidate()` refetches this resource, beyond those
54
+ * its fetcher calls as it starts (which are recorded automatically).
55
+ * `errors: "inline"` keeps failures on `error` only, even under `<Pending>`.
52
56
  * @returns {{ data: unknown, loading: boolean, error: unknown,
53
57
  * refetch: () => Promise<unknown> | undefined }} reactive getters —
54
58
  * read them inside bindings/effects to subscribe.
@@ -63,6 +67,10 @@ export function resource(source, fetcher, options = {}) {
63
67
  const data = signal(options.initial);
64
68
  const error = signal(undefined);
65
69
  const loading = signal(true); // a fetch is intended; the server leaves it true
70
+ // Has a run succeeded at least once? A `<Pending>` shows its fallback while a
71
+ // resource it waits on is loading and has never loaded, so retrying a failed first
72
+ // load shows the fallback again.
73
+ const settled = signal(false);
66
74
  let token = 0;
67
75
  let controller = null;
68
76
  // This resource in the `invalidate()` registry (runtime/invalidate.js).
@@ -92,22 +100,60 @@ export function resource(source, fetcher, options = {}) {
92
100
  batch(() => {
93
101
  data.value = v;
94
102
  loading.value = false;
103
+ settled.value = true;
95
104
  });
96
105
  return v;
97
106
  },
98
107
  (e) => {
99
108
  if (t !== token) return;
100
109
  // Keep the last good `data` (stale-while-error); only `error` flips.
110
+ const first = !settled.value;
101
111
  batch(() => {
102
112
  error.value = e;
103
113
  loading.value = false;
104
114
  });
115
+ failed(e, first);
105
116
  },
106
117
  );
107
118
  }
108
119
 
120
+ // --- `<Pending>` boundaries (pending.js) ------------------------------------
121
+ const inline = options.errors === "inline";
122
+ const boundaries = new Set();
123
+ let disposed = false;
124
+ // What a boundary sees of this resource.
125
+ const handle = {
126
+ loading: () => loading.value,
127
+ settled: () => settled.value,
128
+ refetch: () => (disposed ? undefined : refetch()),
129
+ };
130
+ function track(boundary) {
131
+ if (!boundary || boundaries.has(boundary)) return;
132
+ boundaries.add(boundary);
133
+ boundary.__track(handle);
134
+ }
135
+ // A first-load failure under a boundary goes to the nearest <ErrorBoundary> (through
136
+ // the boundary, so its retry refetches). A failed refetch keeps the stale data and is
137
+ // reported. `errors: "inline"` and resources outside any boundary only set `error`.
138
+ function failed(e, first) {
139
+ if (inline || boundaries.size === 0) return;
140
+ if (first) for (const boundary of boundaries) boundary.__fail(e, handle);
141
+ else reportError(e, { phase: "resource" });
142
+ }
143
+
109
144
  if (!isServer()) {
110
- effect(() => {
145
+ // In a component, the boundary around its host. A page or module resource
146
+ // registers where it is read instead (`reading`), so a page resource read only
147
+ // inside a section's <Pending> holds that section, not the page.
148
+ const host = getCurrentInstance();
149
+ if (host) track(closestPending(host));
150
+ // Runs its cleanup only when the owning scope is disposed (no tracked reads).
151
+ const disposeTracking = effect(() => () => {
152
+ disposed = true;
153
+ for (const boundary of boundaries) boundary.__untrack(handle);
154
+ boundaries.clear();
155
+ });
156
+ const disposeFetching = effect(() => {
111
157
  const value = src(); // the effect's ONLY tracked read
112
158
  if (value == null || value === false) {
113
159
  // Paused: cancel anything in flight and settle as "not loading".
@@ -129,6 +175,10 @@ export function resource(source, fetcher, options = {}) {
129
175
  unregisterResource(entry);
130
176
  };
131
177
  });
178
+ // A component body runs outside any scope; its host tears down `_cleanups` on
179
+ // disconnect. Stop with it, so an unmounted component's fetch is aborted and a
180
+ // boundary stops waiting on it.
181
+ if (host && Array.isArray(host._cleanups)) host._cleanups.push(disposeTracking, disposeFetching);
132
182
  }
133
183
 
134
184
  function refetch() {
@@ -137,14 +187,24 @@ export function resource(source, fetcher, options = {}) {
137
187
  return run(value);
138
188
  }
139
189
 
190
+ // A read while a boundary's children are being built makes that boundary wait on
191
+ // this resource too (a page resource passed down as props).
192
+ const reading = () => {
193
+ const boundary = buildingPending();
194
+ if (boundary) track(boundary);
195
+ };
196
+
140
197
  return {
141
198
  get data() {
199
+ reading();
142
200
  return data.value;
143
201
  },
144
202
  get loading() {
203
+ reading();
145
204
  return loading.value;
146
205
  },
147
206
  get error() {
207
+ reading();
148
208
  return error.value;
149
209
  },
150
210
  /** Re-run the fetcher with the current source value (no-op while paused). */
@@ -56,7 +56,17 @@ export async function fetchRouteData(pathname, search = "") {
56
56
  return new RouteRedirect(pathname + search, { reload: true });
57
57
  }
58
58
  if (res.status === 404) return undefined;
59
- if (!res.ok) throw new Error(`route data request for ${pathname} failed (${res.status})`);
59
+ if (!res.ok) {
60
+ const error = Object.assign(new Error(`route data request for ${pathname} failed (${res.status})`), { status: res.status });
61
+ // The endpoint names the layout whose loader failed (see the server's loader registry).
62
+ try {
63
+ const body = await res.json();
64
+ if (typeof body?.layout === "string") error.afwLayoutRoute = body.layout;
65
+ } catch {
66
+ // a response without the JSON error body
67
+ }
68
+ throw error;
69
+ }
60
70
  return res.json();
61
71
  }
62
72
 
@@ -66,6 +76,28 @@ export async function fetchRouteData(pathname, search = "") {
66
76
  let _read = false;
67
77
  let _value;
68
78
 
79
+ const ROUTE_ERROR = "__afwRouteError";
80
+
81
+ /**
82
+ * The inline-data payload marking a page the server rendered with its `error.jsx`
83
+ * (a failed loader): `{ "__afwRouteError": { status, message } }`, script-safe.
84
+ */
85
+ export function routeErrorPayload(error) {
86
+ const marker = { [ROUTE_ERROR]: { status: error.status ?? 500, message: String(error.message ?? "") } };
87
+ // A failed layout loader: the error view replaces that layout, not just the page.
88
+ if (error.afwLayoutRoute) marker[ROUTE_ERROR].layout = error.afwLayoutRoute;
89
+ return JSON.stringify(marker).replace(/</g, "\\u003c");
90
+ }
91
+
92
+ /** The error a {@link routeErrorPayload} carries, as an `Error` with `status`, or null. */
93
+ export function routeErrorFrom(data) {
94
+ const marker = data && typeof data === "object" ? data[ROUTE_ERROR] : null;
95
+ if (!marker) return null;
96
+ const error = Object.assign(new Error(marker.message), { status: marker.status });
97
+ if (marker.layout) error.afwLayoutRoute = marker.layout;
98
+ return error;
99
+ }
100
+
69
101
  /** The loader data inlined by the server for the current document, or `undefined`. */
70
102
  export function readInlineRouteData() {
71
103
  if (!_read) {
@@ -0,0 +1,3 @@
1
+ /** Install (or, with `null`, remove) the handler for errors no `<ErrorBoundary>` caught. */
2
+ export function setRouteErrorHandler(fn: ((el: Element, error: unknown, context: {}) => void) | null): void;
3
+ export function routeErrorHandler(): ((el: Element, error: unknown, context: {}) => void) | null;
@@ -0,0 +1,16 @@
1
+ // Where an error with no enclosing <ErrorBoundary> goes: the router installs a
2
+ // handler that shows the page's nearest `error.jsx`. Kept apart from
3
+ // error-boundary.js, which defines a Custom Element and so cannot load on the
4
+ // server, where router.js also runs.
5
+
6
+ let handler = null;
7
+
8
+ /** Install (or, with `null`, remove) the handler for errors no boundary caught. */
9
+ export function setRouteErrorHandler(fn) {
10
+ handler = fn;
11
+ }
12
+
13
+ /** The installed handler, or null. */
14
+ export function routeErrorHandler() {
15
+ return handler;
16
+ }
@@ -1,6 +1,11 @@
1
1
  // Route-pattern matching shared by the page router, API routes, route loaders and
2
2
  // middleware scopes, so `[param]` / `[...rest]` folders behave identically in each.
3
3
  //
4
+ // A route is its *folder path*, which decides layouts, loaders and error files:
5
+ // `/(app)/dashboard`. Its *URL* drops route-group segments — folders in parentheses —
6
+ // so that page answers `/dashboard` (`urlOf`). `[[param]]` and `[[...rest]]` are
7
+ // optional segments: the URL matches with or without them.
8
+ //
4
9
  // Precedence is by specificity, segment by segment: a static segment beats a
5
10
  // `[param]`, which beats a `[...rest]`. So `/blog/new` wins over `/blog/[slug]` and
6
11
  // `/api/[id]` wins over `/api/[...rest]`, whatever order the files were discovered in
@@ -25,11 +30,39 @@ export function stripAppDir(filePath, appDir) {
25
30
  export const normalizePath = (p) => (p || "/").replace(/(.)\/+$/, "$1");
26
31
 
27
32
  const PARAM_SPLIT = /(\[\.\.\.[^\]]+\]|\[[^\]]+\])/;
33
+ const OPTIONAL = /^\[\[(\.\.\.)?([^\]]+)\]\]$/;
34
+
35
+ /** Is `segment` a route group, `(name)`: a folder that is not part of the URL? */
36
+ export const isGroupSegment = (segment) => /^\(.+\)$/.test(segment);
37
+
38
+ /** Does the folder route contain a route group? */
39
+ export const hasGroup = (route) => (route ?? "").split("/").some(isGroupSegment);
40
+
41
+ /** The URL pattern of a folder route: its group segments dropped (`/(app)/x` → `/x`). */
42
+ export function urlOf(route) {
43
+ const url = (route ?? "/").split("/").filter((s) => s && !isGroupSegment(s)).join("/");
44
+ return `/${url}`;
45
+ }
46
+
47
+ /**
48
+ * Folder routes that answer the same URL — two route groups holding the same path
49
+ * (`/(a)/about` and `/(b)/about`). Returns `[url, first, second]` triples.
50
+ */
51
+ export function urlCollisions(routes) {
52
+ const seen = new Map();
53
+ const out = [];
54
+ for (const route of routes) {
55
+ const url = urlOf(route);
56
+ if (seen.has(url) && seen.get(url) !== route) out.push([url, seen.get(url), route]);
57
+ else seen.set(url, route);
58
+ }
59
+ return out;
60
+ }
28
61
 
29
- /** Regex source for a route with `[param]` / `[...rest]` segments. Named groups
62
+ /** Regex source for one URL segment with `[param]` / `[...rest]` parts. Named groups
30
63
  * become params; literal parts are regex-escaped (`v1.0` must not match `v1X0`). */
31
- function patternSource(route) {
32
- return route
64
+ function segmentSource(segment) {
65
+ return segment
33
66
  .split(PARAM_SPLIT)
34
67
  .map((part) => {
35
68
  if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
@@ -39,6 +72,19 @@ function patternSource(route) {
39
72
  .join("");
40
73
  }
41
74
 
75
+ /** Regex source for a route's URL; an optional segment carries its own leading slash. */
76
+ function patternSource(route) {
77
+ return urlOf(route)
78
+ .split("/")
79
+ .filter(Boolean)
80
+ .map((segment) => {
81
+ const optional = segment.match(OPTIONAL);
82
+ if (optional) return `(?:/(?<${optional[2]}>${optional[1] ? ".+" : "[^/]+"}))?`;
83
+ return `/${segmentSource(segment)}`;
84
+ })
85
+ .join("");
86
+ }
87
+
42
88
  /** A full-path matcher for `route`; the optional trailing slash is tolerated. */
43
89
  export function compileRoute(route) {
44
90
  return new RegExp(`^${patternSource(route)}/?$`);
@@ -50,21 +96,41 @@ export function compileRoute(route) {
50
96
  * every path.
51
97
  */
52
98
  export function compileScope(scope) {
53
- if (scope === "/") return /^\//;
54
- return new RegExp(`^${patternSource(scope)}(?:/.*)?$`);
99
+ const source = patternSource(scope);
100
+ if (source === "") return /^\//;
101
+ return new RegExp(`^${source}(?:/.*)?$`);
102
+ }
103
+
104
+ /**
105
+ * The matcher for a middleware folder. A folder inside a route group cannot be a URL
106
+ * prefix — `/(app)` is `/`, which would cover every page — so it covers exactly what
107
+ * the group holds: `group.scopes` (the folders of its pages and API routes, each with
108
+ * everything nested under it) and `group.paths` (exact URLs, its server functions).
109
+ * Without that list it falls back to the URL prefix. Returns `{ test(path) }`.
110
+ */
111
+ export function scopeMatcher(scope, group = null) {
112
+ if (!hasGroup(scope) || !group) return compileScope(scope);
113
+ const scopes = (group.scopes ?? []).map(compileScope);
114
+ const paths = new Set(group.paths ?? []);
115
+ return { test: (path) => paths.has(path) || scopes.some((m) => m.test(path)) };
55
116
  }
56
117
 
57
- // Segment kinds, most specific first.
58
- const segmentKind = (seg) => (seg.startsWith("[...") ? 2 : seg.startsWith("[") ? 1 : 0);
118
+ // Segment kinds, most specific first: static, `[param]`, `[[param]]`, `[...rest]`, `[[...rest]]`.
119
+ const segmentKind = (seg) => {
120
+ const optional = seg.match(OPTIONAL);
121
+ if (optional) return optional[1] ? 4 : 2;
122
+ return seg.startsWith("[...") ? 3 : seg.startsWith("[") ? 1 : 0;
123
+ };
59
124
 
60
125
  /**
61
- * Sort comparator: more specific routes first. Compares segment kinds left to
62
- * right (static < `[param]` < `[...rest]`); with equal kinds the route with more
63
- * segments is more specific; the final tie-break is lexical, for a deterministic order.
126
+ * Sort comparator: more specific routes first, by URL (groups dropped). Compares
127
+ * segment kinds left to right (static < `[param]` < `[[param]]` < `[...rest]` <
128
+ * `[[...rest]]`); with equal kinds the route with more segments is more specific; the
129
+ * final tie-break is lexical, for a deterministic order.
64
130
  */
65
131
  export function compareRoutes(a, b) {
66
- const sa = a.split("/").filter(Boolean);
67
- const sb = b.split("/").filter(Boolean);
132
+ const sa = urlOf(a).split("/").filter(Boolean);
133
+ const sb = urlOf(b).split("/").filter(Boolean);
68
134
  for (let i = 0; i < Math.min(sa.length, sb.length); i++) {
69
135
  const d = segmentKind(sa[i]) - segmentKind(sb[i]);
70
136
  if (d !== 0) return d;
@@ -81,6 +147,7 @@ export function compareRoutes(a, b) {
81
147
  export function decodeParams(route, groups, { strict = false } = {}) {
82
148
  const params = { ...(groups || {}) };
83
149
  for (const k in params) {
150
+ if (params[k] === undefined) continue; // an optional segment that is absent
84
151
  const decode = (s) => {
85
152
  try {
86
153
  return decodeURIComponent(s);