@ogygia/router 0.0.0 → 0.12.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/LICENSE +21 -0
- package/README.md +41 -1
- package/dist/LayoutChain.svelte +34 -0
- package/dist/LayoutChain.svelte.d.ts +19 -0
- package/dist/RawHtml.svelte +8 -0
- package/dist/RawHtml.svelte.d.ts +6 -0
- package/dist/client-api.d.ts +50 -0
- package/dist/client-api.js +67 -0
- package/dist/ctx.d.ts +51 -0
- package/dist/ctx.js +50 -0
- package/dist/define.d.ts +294 -0
- package/dist/define.js +159 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +7 -0
- package/dist/infer.d.ts +64 -0
- package/dist/infer.js +0 -0
- package/dist/match.d.ts +37 -0
- package/dist/match.js +125 -0
- package/dist/respond.d.ts +42 -0
- package/dist/respond.js +79 -0
- package/dist/router.d.ts +72 -0
- package/dist/router.js +404 -0
- package/dist/stream.d.ts +36 -0
- package/dist/stream.js +135 -0
- package/dist/view.d.ts +13 -0
- package/dist/view.js +0 -0
- package/dist/visitor.d.ts +8 -0
- package/dist/visitor.js +38 -0
- package/dist/vite.d.ts +2 -0
- package/dist/vite.js +18 -0
- package/package.json +68 -6
package/dist/match.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// src/match.ts
|
|
2
|
+
const REGEX_SPECIAL_G = /[.*+?^${}()|[\]\\]/g;
|
|
3
|
+
const escape_re = (s) => s.replace(REGEX_SPECIAL_G, "\\$&");
|
|
4
|
+
const REST = /^\[\.\.\.([a-zA-Z_$][\w$]*)\]$/;
|
|
5
|
+
const OPTIONAL = /^\[\[([a-zA-Z_$][\w$]*)\]\]$/;
|
|
6
|
+
/** strips valid `[param]` groups so any leftover bracket flags a malformed segment */
|
|
7
|
+
const STRIP_PARAMS = /\[[a-zA-Z_$][\w$]*\]/g;
|
|
8
|
+
/**
|
|
9
|
+
* Compile a pattern into a regex + its param specs + a specificity score. Throws on an obviously
|
|
10
|
+
* malformed pattern (a rest segment that isn't last) — a loud build-time-ish error beats a route
|
|
11
|
+
* that silently never matches.
|
|
12
|
+
*/
|
|
13
|
+
const INNER_PARAM = /\[([a-zA-Z_$][\w$]*)\]/g;
|
|
14
|
+
function compile(pattern) {
|
|
15
|
+
if (!pattern.startsWith("/")) throw new Error(`[@ogygia/router] route pattern must start with "/": ${JSON.stringify(pattern)}`);
|
|
16
|
+
const segs = pattern.split("/").filter((s) => s !== "");
|
|
17
|
+
const params = [];
|
|
18
|
+
const digits = [];
|
|
19
|
+
let rx = "";
|
|
20
|
+
segs.forEach((seg, i) => {
|
|
21
|
+
let m;
|
|
22
|
+
if (m = seg.match(REST)) {
|
|
23
|
+
if (i !== segs.length - 1) throw new Error(`[@ogygia/router] a [...rest] segment must be last: ${JSON.stringify(pattern)}`);
|
|
24
|
+
params.push({
|
|
25
|
+
name: m[1],
|
|
26
|
+
rest: true
|
|
27
|
+
});
|
|
28
|
+
rx += "(?:/(.*))?";
|
|
29
|
+
digits.push(0);
|
|
30
|
+
} else if (m = seg.match(OPTIONAL)) {
|
|
31
|
+
params.push({
|
|
32
|
+
name: m[1],
|
|
33
|
+
optional: true
|
|
34
|
+
});
|
|
35
|
+
rx += "(?:/([^/]+))?";
|
|
36
|
+
digits.push(1);
|
|
37
|
+
} else {
|
|
38
|
+
let inner = "/";
|
|
39
|
+
let has_static = false;
|
|
40
|
+
let has_param = false;
|
|
41
|
+
let last = 0;
|
|
42
|
+
INNER_PARAM.lastIndex = 0;
|
|
43
|
+
let g;
|
|
44
|
+
while (g = INNER_PARAM.exec(seg)) {
|
|
45
|
+
const pre = seg.slice(last, g.index);
|
|
46
|
+
if (pre) {
|
|
47
|
+
inner += escape_re(pre);
|
|
48
|
+
has_static = true;
|
|
49
|
+
}
|
|
50
|
+
inner += "([^/]+)";
|
|
51
|
+
params.push({ name: g[1] });
|
|
52
|
+
has_param = true;
|
|
53
|
+
last = INNER_PARAM.lastIndex;
|
|
54
|
+
}
|
|
55
|
+
const tail = seg.slice(last);
|
|
56
|
+
if (tail) {
|
|
57
|
+
inner += escape_re(tail);
|
|
58
|
+
has_static = true;
|
|
59
|
+
}
|
|
60
|
+
const leftover = seg.replace(STRIP_PARAMS, "");
|
|
61
|
+
if (leftover.includes("[") || leftover.includes("]") || !has_static && !has_param) throw new Error(`[@ogygia/router] malformed segment ${JSON.stringify(seg)} in ${pattern}`);
|
|
62
|
+
rx += inner;
|
|
63
|
+
digits.push(!has_param ? 4 : has_static ? 3 : 2);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
if (rx === "") rx = "/?";
|
|
67
|
+
const regex = new RegExp("^" + rx + "/?$");
|
|
68
|
+
const trailing_rest = params.length > 0 && params[params.length - 1].rest === true;
|
|
69
|
+
const eff = trailing_rest ? digits.slice(0, -1) : digits;
|
|
70
|
+
let score = 0;
|
|
71
|
+
for (const d of eff) score = score * 5 + d;
|
|
72
|
+
score = score * 64 + eff.length;
|
|
73
|
+
if (trailing_rest) score -= 1;
|
|
74
|
+
return {
|
|
75
|
+
pattern,
|
|
76
|
+
regex,
|
|
77
|
+
params,
|
|
78
|
+
score
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
/** Compile a whole table's keys and sort most-specific-first, so the first match wins. */
|
|
82
|
+
function compile_all(patterns) {
|
|
83
|
+
return patterns.map(compile).sort((a, b) => b.score - a.score);
|
|
84
|
+
}
|
|
85
|
+
/** Match one compiled pattern against a pathname. Returns params, or null if it doesn't match. */
|
|
86
|
+
function match_one(c, pathname) {
|
|
87
|
+
const m = c.regex.exec(pathname);
|
|
88
|
+
if (!m) return null;
|
|
89
|
+
const params = {};
|
|
90
|
+
c.params.forEach((spec, i) => {
|
|
91
|
+
const raw = m[i + 1];
|
|
92
|
+
if (spec.rest) params[spec.name] = raw == null ? "" : safe_decode(raw);
|
|
93
|
+
else if (spec.optional) params[spec.name] = raw == null ? void 0 : safe_decode(raw);
|
|
94
|
+
else params[spec.name] = safe_decode(raw);
|
|
95
|
+
});
|
|
96
|
+
return {
|
|
97
|
+
pattern: c.pattern,
|
|
98
|
+
params
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/** Fill a pattern's `[param]` / `[...rest]` tokens from a params record (URL-encoded). Shared by
|
|
102
|
+
* `href()` (router) and the typed `api()` client — one token grammar, one filler. */
|
|
103
|
+
const fill_token = /\[(\.\.\.)?\[?([a-zA-Z_$][\w$]*)\]?\]/g;
|
|
104
|
+
function fill(pattern, params) {
|
|
105
|
+
return pattern.replace(fill_token, (_m, _rest, name) => {
|
|
106
|
+
const val = params[name];
|
|
107
|
+
return val == null ? "" : encodeURIComponent(String(val));
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/** First (most-specific) match in a pre-sorted list, or null. */
|
|
111
|
+
function match_path(sorted, pathname) {
|
|
112
|
+
for (const c of sorted) {
|
|
113
|
+
const hit = match_one(c, pathname);
|
|
114
|
+
if (hit) return hit;
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
function safe_decode(s) {
|
|
119
|
+
try {
|
|
120
|
+
return decodeURIComponent(s);
|
|
121
|
+
} catch {
|
|
122
|
+
return s;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
export { compile, compile_all, fill, match_one, match_path };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Router v2 control-flow values: the throwable `redirect()` / `error()` (Kit's exact idiom — thrown
|
|
3
|
+
* from loads, actions, and handlers) and the returnable `fail()` (Kit's action-validation shape),
|
|
4
|
+
* plus the small Response helpers the dispatcher shares. See internal/notes/router-v2.md.
|
|
5
|
+
*/
|
|
6
|
+
declare const REDIRECT: unique symbol;
|
|
7
|
+
declare const HTTP_ERROR: unique symbol;
|
|
8
|
+
declare const ACTION_FAILURE: unique symbol;
|
|
9
|
+
export interface Redirect {
|
|
10
|
+
[REDIRECT]: true;
|
|
11
|
+
status: number;
|
|
12
|
+
location: string;
|
|
13
|
+
}
|
|
14
|
+
export interface HttpError {
|
|
15
|
+
[HTTP_ERROR]: true;
|
|
16
|
+
status: number;
|
|
17
|
+
message: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ActionFailure<T = Record<string, unknown>> {
|
|
20
|
+
[ACTION_FAILURE]: true;
|
|
21
|
+
status: number;
|
|
22
|
+
data: T;
|
|
23
|
+
}
|
|
24
|
+
/** Throw a redirect from a load / action / handler — Kit's `redirect(303, '/login')`, verbatim. */
|
|
25
|
+
export declare function redirect(status: number, location: string | URL): never;
|
|
26
|
+
/** Throw an HTTP error from a load / action / handler — Kit's `error(404, 'Not found')`, verbatim.
|
|
27
|
+
* On a page branch the nearest error boundary renders it; on an endpoint it becomes JSON. */
|
|
28
|
+
export declare function error(status: number, message?: string): never;
|
|
29
|
+
/** Return an action validation failure — Kit's `fail(400, { incorrect: true })`. The router re-renders
|
|
30
|
+
* the page with `form` = data and the given status. RETURNED, not thrown (Kit's contract). */
|
|
31
|
+
export declare function fail<T extends Record<string, unknown>>(status: number, data: T): ActionFailure<T>;
|
|
32
|
+
export declare const is_redirect: (x: unknown) => x is Redirect;
|
|
33
|
+
export declare const is_http_error: (x: unknown) => x is HttpError;
|
|
34
|
+
export declare const is_action_failure: (x: unknown) => x is ActionFailure;
|
|
35
|
+
export declare function json_response(data: unknown, init?: ResponseInit): Response;
|
|
36
|
+
export declare function redirect_response(status: number, location: string): Response;
|
|
37
|
+
/** An endpoint/miss return → a Response: Response passes through; null/undefined → 204; else JSON. */
|
|
38
|
+
export declare function finalize(out: unknown): Response;
|
|
39
|
+
export declare function not_found(): Response;
|
|
40
|
+
export declare function method_not_allowed(allow: string[]): Response;
|
|
41
|
+
export declare function options_response(allow: string[]): Response;
|
|
42
|
+
export {};
|
package/dist/respond.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// src/respond.ts
|
|
2
|
+
/**
|
|
3
|
+
* Router v2 control-flow values: the throwable `redirect()` / `error()` (Kit's exact idiom — thrown
|
|
4
|
+
* from loads, actions, and handlers) and the returnable `fail()` (Kit's action-validation shape),
|
|
5
|
+
* plus the small Response helpers the dispatcher shares. See internal/notes/router-v2.md.
|
|
6
|
+
*/
|
|
7
|
+
const REDIRECT = Symbol.for("ogygia.router.redirect");
|
|
8
|
+
const HTTP_ERROR = Symbol.for("ogygia.router.error");
|
|
9
|
+
const ACTION_FAILURE = Symbol.for("ogygia.router.fail");
|
|
10
|
+
/** Throw a redirect from a load / action / handler — Kit's `redirect(303, '/login')`, verbatim. */
|
|
11
|
+
function redirect(status, location) {
|
|
12
|
+
throw {
|
|
13
|
+
[REDIRECT]: true,
|
|
14
|
+
status,
|
|
15
|
+
location: String(location)
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
/** Throw an HTTP error from a load / action / handler — Kit's `error(404, 'Not found')`, verbatim.
|
|
19
|
+
* On a page branch the nearest error boundary renders it; on an endpoint it becomes JSON. */
|
|
20
|
+
function error(status, message) {
|
|
21
|
+
throw {
|
|
22
|
+
[HTTP_ERROR]: true,
|
|
23
|
+
status,
|
|
24
|
+
message: message ?? "Error"
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Return an action validation failure — Kit's `fail(400, { incorrect: true })`. The router re-renders
|
|
28
|
+
* the page with `form` = data and the given status. RETURNED, not thrown (Kit's contract). */
|
|
29
|
+
function fail(status, data) {
|
|
30
|
+
return {
|
|
31
|
+
[ACTION_FAILURE]: true,
|
|
32
|
+
status,
|
|
33
|
+
data
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const is_redirect = (x) => typeof x === "object" && x !== null && REDIRECT in x;
|
|
37
|
+
const is_http_error = (x) => typeof x === "object" && x !== null && HTTP_ERROR in x;
|
|
38
|
+
const is_action_failure = (x) => typeof x === "object" && x !== null && ACTION_FAILURE in x;
|
|
39
|
+
function json_response(data, init) {
|
|
40
|
+
return new Response(JSON.stringify(data), {
|
|
41
|
+
...init,
|
|
42
|
+
headers: {
|
|
43
|
+
"content-type": "application/json",
|
|
44
|
+
"cache-control": "no-store",
|
|
45
|
+
...init?.headers
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function redirect_response(status, location) {
|
|
50
|
+
return new Response(null, {
|
|
51
|
+
status,
|
|
52
|
+
headers: {
|
|
53
|
+
location,
|
|
54
|
+
"cache-control": "no-store"
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
/** An endpoint/miss return → a Response: Response passes through; null/undefined → 204; else JSON. */
|
|
59
|
+
function finalize(out) {
|
|
60
|
+
if (out instanceof Response) return out;
|
|
61
|
+
if (out == null) return new Response(null, { status: 204 });
|
|
62
|
+
return json_response(out);
|
|
63
|
+
}
|
|
64
|
+
function not_found() {
|
|
65
|
+
return new Response("Not found", { status: 404 });
|
|
66
|
+
}
|
|
67
|
+
function method_not_allowed(allow) {
|
|
68
|
+
return new Response("Method not allowed", {
|
|
69
|
+
status: 405,
|
|
70
|
+
headers: { allow: allow.join(", ") }
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function options_response(allow) {
|
|
74
|
+
return new Response(null, {
|
|
75
|
+
status: 204,
|
|
76
|
+
headers: { allow: allow.join(", ") }
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
export { error, fail, finalize, is_action_failure, is_http_error, is_redirect, json_response, method_not_allowed, not_found, options_response, redirect, redirect_response };
|
package/dist/router.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Ctx, Visitor } from "./ctx.js";
|
|
2
|
+
import { AnyComponent, KeyedTable, LoadInput, RouteTable, TableShape } from "./define.js";
|
|
3
|
+
import { InferMap } from "./infer.js";
|
|
4
|
+
import { HrefArgs } from "./view.js";
|
|
5
|
+
import { RouteConfig } from "@ogygia/core/plugin";
|
|
6
|
+
import { RequestEvent } from "@sveltejs/kit";
|
|
7
|
+
import { Component } from "svelte";
|
|
8
|
+
export interface RoutesOptions {
|
|
9
|
+
/** Mount prefix, stripped before matching. Required for a library that owns a subtree. */
|
|
10
|
+
base?: string;
|
|
11
|
+
/** Trailing-slash policy. 'ignore' (default) matches both; 'never'/'always' 308-canonicalize. */
|
|
12
|
+
slash?: "ignore" | "never" | "always";
|
|
13
|
+
/** Response for an unmatched path UNDER `base` (default: 404). Ignored without `base`. */
|
|
14
|
+
miss?: (c: Ctx) => unknown;
|
|
15
|
+
/** Root error boundary component (Kit's top `+error.svelte`) for thrown `error()` with no nearer
|
|
16
|
+
* layout boundary. */
|
|
17
|
+
error?: AnyComponent;
|
|
18
|
+
/** A table-wide load run before EVERY route (pages and endpoints) — Kit's root `+layout.server.ts`
|
|
19
|
+
* load without a component. The place for a guard with no shared chrome: it throws
|
|
20
|
+
* `redirect`/`error` to gate, and its returned data merges into every page's `data` (outermost). */
|
|
21
|
+
load?: LoadInput;
|
|
22
|
+
/** WHO is this request? Derived ONCE here, read everywhere as `c.visitor` — experiments stick
|
|
23
|
+
* on it, mounts sign it into claims, loads personalize with it. Signature-bound claims from
|
|
24
|
+
* an upstream shell (fragment federation) take precedence over this resolver. */
|
|
25
|
+
visitor?: (c: Ctx) => Visitor | undefined;
|
|
26
|
+
/** Flags to PRE-DECIDE at the table, so mounts carry their buckets even when no page on this
|
|
27
|
+
* server reads them (a shell that only ROUTES to teams still wants the visitor's world to
|
|
28
|
+
* travel). Any flag a page DOES read auto-carries without being listed here — this is just for
|
|
29
|
+
* the decide-but-don't-render case. `flags: [csr]`. */
|
|
30
|
+
flags?: ReadonlyArray<(c: Ctx) => unknown>;
|
|
31
|
+
/** Table-wide Kit `config` page option for every page (a layout's or a page's own key wins):
|
|
32
|
+
* plugins read their keys from it (`{ postrender: false }`). The handle consults this table for
|
|
33
|
+
* any request Kit's file router did not claim — keep `ogygia.handle()` ahead of the table in the
|
|
34
|
+
* `sequence()` so a stored page is served before the table runs. */
|
|
35
|
+
config?: RouteConfig;
|
|
36
|
+
}
|
|
37
|
+
/** The router value. `$infer` is a type-only phantom read as `typeof app.$infer`. */
|
|
38
|
+
export interface Router<T extends TableShape = RouteTable> {
|
|
39
|
+
readonly __ogrouter: true;
|
|
40
|
+
/** `(request) => Response | null` — null on no-match (a catchall 404s its own way). */
|
|
41
|
+
fetch(request: Request, event?: RequestEvent): Promise<Response | null>;
|
|
42
|
+
/** Kit handle: dispatches, else falls through to the rest of the app. */
|
|
43
|
+
handle(input: {
|
|
44
|
+
event: RequestEvent;
|
|
45
|
+
resolve: (e: RequestEvent) => Response | Promise<Response>;
|
|
46
|
+
}): Promise<Response>;
|
|
47
|
+
/** Rename-safe URL to a route in this table. */
|
|
48
|
+
href<P extends keyof T & string>(pattern: P, ...args: HrefArgs<P>): string;
|
|
49
|
+
/** The catchall crawl list (static page routes) — `export const entries = app.entries`. */
|
|
50
|
+
entries(): Promise<Array<{
|
|
51
|
+
path: string;
|
|
52
|
+
}>>;
|
|
53
|
+
/** Type-only phantom map: `export type App = typeof app.$infer`. */
|
|
54
|
+
readonly $infer: InferMap<T>;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Flag-gate a table entry — page or endpoint. OFF means the route DOES NOT EXIST for that
|
|
58
|
+
* request: 404 (the app's error page) under an owned `base`, fall-through to the rest of the app
|
|
59
|
+
* without one. The gate is any `(c) => boolean` — a boolean `flag()` slots in directly, so a
|
|
60
|
+
* staged rollout of a whole page, a beta route, or an endpoint kill switch is one wrapper:
|
|
61
|
+
*
|
|
62
|
+
* '/checkout-v2': when(checkoutV2, page(NewCheckout, { load })),
|
|
63
|
+
* '/api/export': when(exportsFlag, { GET: GET(export_csv) }),
|
|
64
|
+
* '/cms/[...rest]': when(cmsRollout, mount(cms)), // per-cohort fragment rollout
|
|
65
|
+
*
|
|
66
|
+
* Decided AFTER `decide({ source })` primes, so a vendor kill switch gates routes too; the
|
|
67
|
+
* decision self-registers for federation carry like any flag read. Type-transparent: `$infer`
|
|
68
|
+
* sees the entry exactly as if unwrapped.
|
|
69
|
+
*/
|
|
70
|
+
export declare function when<T extends object>(gate: (c: Ctx) => boolean, entry: T): T;
|
|
71
|
+
export declare function routes<const T extends KeyedTable<T>>(typed: T, opts?: RoutesOptions): Router<T>;
|
|
72
|
+
export type { Component };
|