@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/router.js
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import { compile_all, fill, match_path } from "./match.js";
|
|
2
|
+
import { make_ctx } from "./ctx.js";
|
|
3
|
+
import { compile_endpoint, is_page, to_load } from "./define.js";
|
|
4
|
+
import { error, finalize, is_action_failure, is_http_error, is_redirect, json_response, method_not_allowed, not_found, options_response, redirect_response } from "./respond.js";
|
|
5
|
+
import { bake_yield, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document } from "./stream.js";
|
|
6
|
+
import { document } from "@ogygia/core/server";
|
|
7
|
+
import { lateSlot, openLateScope, region, registerRouteConfig, takeLateRegions } from "@ogygia/core/plugin";
|
|
8
|
+
import { componentCssHead } from "@ogygia/core/plugin/css";
|
|
9
|
+
import { escapeText } from "@ogygia/core/plugin/utils";
|
|
10
|
+
import LayoutChain from "./LayoutChain.svelte";
|
|
11
|
+
import RawHtml from "./RawHtml.svelte";
|
|
12
|
+
// src/router.ts
|
|
13
|
+
/**
|
|
14
|
+
* Flag-gate a table entry — page or endpoint. OFF means the route DOES NOT EXIST for that
|
|
15
|
+
* request: 404 (the app's error page) under an owned `base`, fall-through to the rest of the app
|
|
16
|
+
* without one. The gate is any `(c) => boolean` — a boolean `flag()` slots in directly, so a
|
|
17
|
+
* staged rollout of a whole page, a beta route, or an endpoint kill switch is one wrapper:
|
|
18
|
+
*
|
|
19
|
+
* '/checkout-v2': when(checkoutV2, page(NewCheckout, { load })),
|
|
20
|
+
* '/api/export': when(exportsFlag, { GET: GET(export_csv) }),
|
|
21
|
+
* '/cms/[...rest]': when(cmsRollout, mount(cms)), // per-cohort fragment rollout
|
|
22
|
+
*
|
|
23
|
+
* Decided AFTER `decide({ source })` primes, so a vendor kill switch gates routes too; the
|
|
24
|
+
* decision self-registers for federation carry like any flag read. Type-transparent: `$infer`
|
|
25
|
+
* sees the entry exactly as if unwrapped.
|
|
26
|
+
*/
|
|
27
|
+
function when(gate, entry) {
|
|
28
|
+
return {
|
|
29
|
+
...entry,
|
|
30
|
+
__ogwhen: gate
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
const HEAD_AS_GET = (m) => m === "HEAD" ? "GET" : m;
|
|
34
|
+
const LAST_SLASH_RE = /\/$/;
|
|
35
|
+
function routes(typed, opts = {}) {
|
|
36
|
+
const table = typed;
|
|
37
|
+
const base = (opts.base ?? "").replace(LAST_SLASH_RE, "");
|
|
38
|
+
const slash = opts.slash ?? "ignore";
|
|
39
|
+
const root_load = to_load(opts.load);
|
|
40
|
+
const seen_layout = /* @__PURE__ */ new Map();
|
|
41
|
+
for (const key in table) {
|
|
42
|
+
const def = table[key];
|
|
43
|
+
if (is_page(def)) for (const l of def.layouts) {
|
|
44
|
+
const prev = seen_layout.get(l.name);
|
|
45
|
+
if (prev && prev !== l.component) throw new Error(`[@ogygia/router] two different layouts share the name ${JSON.stringify(l.name)} — names must be unique (they key App['(name)']).`);
|
|
46
|
+
seen_layout.set(l.name, l.component);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const leaves = Object.keys(table).map((pattern) => {
|
|
50
|
+
const raw = table[pattern];
|
|
51
|
+
const gate = raw.__ogwhen;
|
|
52
|
+
return {
|
|
53
|
+
pattern,
|
|
54
|
+
def: is_page(raw) ? raw : compile_endpoint(raw),
|
|
55
|
+
...gate ? { when: gate } : {}
|
|
56
|
+
};
|
|
57
|
+
});
|
|
58
|
+
const compiled = compile_all(leaves.map((l) => l.pattern));
|
|
59
|
+
const by_pattern = new Map(leaves.map((l) => [l.pattern, l]));
|
|
60
|
+
const NO_CONFIG = {};
|
|
61
|
+
const config_of = /* @__PURE__ */ new Map();
|
|
62
|
+
for (const leaf of leaves) {
|
|
63
|
+
if (!is_page(leaf.def)) continue;
|
|
64
|
+
let merged = { ...opts.config };
|
|
65
|
+
for (const l of leaf.def.layouts) merged = {
|
|
66
|
+
...merged,
|
|
67
|
+
...l.config
|
|
68
|
+
};
|
|
69
|
+
config_of.set(leaf.pattern, {
|
|
70
|
+
...merged,
|
|
71
|
+
...leaf.def.config
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
registerRouteConfig(base + "|" + leaves.map((l) => l.pattern).join(","), (pathname) => {
|
|
75
|
+
let path = pathname;
|
|
76
|
+
if (base) {
|
|
77
|
+
if (path === base) path = "/";
|
|
78
|
+
else if (path.startsWith(base + "/")) path = path.slice(base.length);
|
|
79
|
+
else return void 0;
|
|
80
|
+
}
|
|
81
|
+
path = canonical_slash(path, slash) ?? path;
|
|
82
|
+
const hit = match_path(compiled, path);
|
|
83
|
+
return hit ? config_of.get(hit.pattern) ?? NO_CONFIG : void 0;
|
|
84
|
+
});
|
|
85
|
+
const href_fn = (pattern, params) => base + fill(pattern, params ?? {});
|
|
86
|
+
async function dispatch(request, event) {
|
|
87
|
+
const url = new URL(request.url);
|
|
88
|
+
let path = url.pathname;
|
|
89
|
+
if (base) {
|
|
90
|
+
if (path === base) path = "/";
|
|
91
|
+
else if (path.startsWith(base + "/")) path = path.slice(base.length);
|
|
92
|
+
else return null;
|
|
93
|
+
}
|
|
94
|
+
const canon = canonical_slash(path, slash);
|
|
95
|
+
if (canon) return new Response(null, {
|
|
96
|
+
status: 308,
|
|
97
|
+
headers: { location: base + canon + url.search }
|
|
98
|
+
});
|
|
99
|
+
const hit = match_path(compiled, path);
|
|
100
|
+
const unmatched = async () => {
|
|
101
|
+
if (base && opts.miss) {
|
|
102
|
+
const ctx = make_ctx({}, url, request, event, href_fn, "", opts.visitor);
|
|
103
|
+
try {
|
|
104
|
+
return finalize(await opts.miss(ctx));
|
|
105
|
+
} catch (thrown) {
|
|
106
|
+
if (is_redirect(thrown)) return redirect_response(thrown.status, thrown.location);
|
|
107
|
+
if (is_http_error(thrown)) return json_response({
|
|
108
|
+
error: thrown.message,
|
|
109
|
+
status: thrown.status
|
|
110
|
+
}, { status: thrown.status });
|
|
111
|
+
throw thrown;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if (base && opts.error && (request.method === "GET" || request.method === "HEAD")) {
|
|
115
|
+
if ((request.headers.get("accept") ?? "").includes("text/html")) {
|
|
116
|
+
const ctx = make_ctx({}, url, request, event, href_fn, "", opts.visitor);
|
|
117
|
+
const of = region(LayoutChain, {
|
|
118
|
+
chain: [],
|
|
119
|
+
component: opts.error,
|
|
120
|
+
props: {
|
|
121
|
+
status: 404,
|
|
122
|
+
error: { message: "Not found" },
|
|
123
|
+
data: {},
|
|
124
|
+
params: {}
|
|
125
|
+
},
|
|
126
|
+
data: {}
|
|
127
|
+
});
|
|
128
|
+
return document(of, {
|
|
129
|
+
status: 404,
|
|
130
|
+
head: await componentCssHead([opts.error]),
|
|
131
|
+
pageState: {
|
|
132
|
+
url: ctx.url,
|
|
133
|
+
params: {},
|
|
134
|
+
route: { id: null },
|
|
135
|
+
status: 404,
|
|
136
|
+
data: {},
|
|
137
|
+
error: { message: "Not found" }
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (base) return not_found();
|
|
143
|
+
return null;
|
|
144
|
+
};
|
|
145
|
+
if (!hit) return unmatched();
|
|
146
|
+
const leaf = by_pattern.get(hit.pattern);
|
|
147
|
+
const ctx = make_ctx(hit.params, url, request, event, href_fn, hit.pattern, opts.visitor);
|
|
148
|
+
if (opts.flags) for (const f of opts.flags) f(ctx);
|
|
149
|
+
if (leaf.when && !leaf.when(ctx)) return unmatched();
|
|
150
|
+
const with_collected = (res) => {
|
|
151
|
+
if (ctx.collected_headers?.size) {
|
|
152
|
+
for (const [k, v] of ctx.collected_headers) if (!res.headers.has(k)) res.headers.set(k, v);
|
|
153
|
+
}
|
|
154
|
+
return res;
|
|
155
|
+
};
|
|
156
|
+
try {
|
|
157
|
+
if (root_load) {
|
|
158
|
+
const rl = await root_load(ctx);
|
|
159
|
+
if (rl instanceof Response) return with_collected(rl);
|
|
160
|
+
}
|
|
161
|
+
if (leaf.def.__ogkind === "endpoint") return with_collected(await run_endpoint(leaf.def, ctx, request.method));
|
|
162
|
+
return with_collected(await render_page(leaf.def, ctx, request.method, url));
|
|
163
|
+
} catch (thrown) {
|
|
164
|
+
return with_collected(await handle_thrown(thrown, leaf.def, ctx));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function render_page(node, ctx, method, url) {
|
|
168
|
+
const m = HEAD_AS_GET(method);
|
|
169
|
+
if (node.params_schema) {
|
|
170
|
+
const v = await validate(node.params_schema, ctx.params);
|
|
171
|
+
if (v.issues) return not_found();
|
|
172
|
+
ctx.params = v.value;
|
|
173
|
+
}
|
|
174
|
+
if (node.search_schema) {
|
|
175
|
+
const v = await validate(node.search_schema, ctx.search);
|
|
176
|
+
if (v.issues) return json_response({
|
|
177
|
+
error: "Invalid query",
|
|
178
|
+
issues: v.issues
|
|
179
|
+
}, { status: 400 });
|
|
180
|
+
ctx.search = v.value;
|
|
181
|
+
}
|
|
182
|
+
let form;
|
|
183
|
+
let status = 200;
|
|
184
|
+
if (m === "POST") {
|
|
185
|
+
const act = pick_action(node, url);
|
|
186
|
+
if (!act) return method_not_allowed(page_allow(node));
|
|
187
|
+
const out = await act(ctx);
|
|
188
|
+
if (out instanceof Response) return out;
|
|
189
|
+
if (is_action_failure(out)) {
|
|
190
|
+
form = out.data;
|
|
191
|
+
status = out.status;
|
|
192
|
+
} else form = out ?? void 0;
|
|
193
|
+
} else if (m !== "GET") {
|
|
194
|
+
if (method === "OPTIONS") return options_response(page_allow(node));
|
|
195
|
+
return method_not_allowed(page_allow(node));
|
|
196
|
+
}
|
|
197
|
+
const load_defs = [
|
|
198
|
+
root_load,
|
|
199
|
+
...node.layouts.map((l) => l.load),
|
|
200
|
+
node.load
|
|
201
|
+
];
|
|
202
|
+
const results = await Promise.all(load_defs.map((l) => l ? l(ctx) : void 0));
|
|
203
|
+
const data = {};
|
|
204
|
+
for (const r of results) {
|
|
205
|
+
if (r instanceof Response) return r;
|
|
206
|
+
if (r && typeof r === "object") Object.assign(data, r);
|
|
207
|
+
}
|
|
208
|
+
const chain = node.layouts.map((l) => l.component);
|
|
209
|
+
let gen_rest = null;
|
|
210
|
+
let gen_first_html = null;
|
|
211
|
+
if (is_stream_slot(node.component)) {
|
|
212
|
+
const it = node.component(ctx, data);
|
|
213
|
+
const first = await it.next();
|
|
214
|
+
if (first.done) error(500, "a streamed page must yield at least one region");
|
|
215
|
+
if (m === "GET" && method !== "HEAD") {
|
|
216
|
+
gen_first_html = await bake_yield(first.value);
|
|
217
|
+
gen_rest = it;
|
|
218
|
+
} else {
|
|
219
|
+
let last = first.value;
|
|
220
|
+
for (;;) {
|
|
221
|
+
const n = await it.next();
|
|
222
|
+
if (n.done) break;
|
|
223
|
+
last = n.value;
|
|
224
|
+
}
|
|
225
|
+
gen_first_html = await bake_yield(last);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const resolved = gen_first_html !== null ? {
|
|
229
|
+
__oghtml: true,
|
|
230
|
+
html: lateSlot("pg", gen_first_html)
|
|
231
|
+
} : typeof node.component === "object" && node.component !== null && "__ogpick" in node.component ? node.component.__ogpick(ctx, data) : node.component;
|
|
232
|
+
const html_view = typeof resolved === "object" && resolved !== null && "__oghtml" in resolved ? resolved : null;
|
|
233
|
+
const page_component = html_view ? RawHtml : resolved;
|
|
234
|
+
if (html_view?.status && html_view.status >= 400) status = html_view.status;
|
|
235
|
+
const of = region(LayoutChain, {
|
|
236
|
+
chain,
|
|
237
|
+
component: page_component,
|
|
238
|
+
props: html_view ? { html: html_view.html } : {
|
|
239
|
+
data,
|
|
240
|
+
form,
|
|
241
|
+
params: ctx.params
|
|
242
|
+
},
|
|
243
|
+
data,
|
|
244
|
+
fallback: node.fallback
|
|
245
|
+
});
|
|
246
|
+
const css_head = await componentCssHead(html_view ? chain : [...chain, page_component]) + (html_view ? (html_view.title ? `<title>${escapeText(html_view.title)}</title>` : "") + (html_view.css?.join("") ?? "") + (html_view.head ?? "") : "");
|
|
247
|
+
if (m === "GET") openLateScope();
|
|
248
|
+
const res = await document(of, {
|
|
249
|
+
status,
|
|
250
|
+
head: css_head,
|
|
251
|
+
pageState: {
|
|
252
|
+
url: ctx.url,
|
|
253
|
+
params: ctx.params,
|
|
254
|
+
route: { id: ctx.route.id || null },
|
|
255
|
+
status,
|
|
256
|
+
data,
|
|
257
|
+
form
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
if (method === "HEAD") return new Response(null, res);
|
|
261
|
+
const late = takeLateRegions();
|
|
262
|
+
const chunk_src = gen_rest && late?.length ? merge_chunks(page_slot_chunks(gen_rest), late_region_chunks(late)) : gen_rest ? page_slot_chunks(gen_rest) : late?.length ? late_region_chunks(late) : null;
|
|
263
|
+
if (chunk_src && m === "GET") return stream_document(await res.text(), res, chunk_src);
|
|
264
|
+
return res;
|
|
265
|
+
}
|
|
266
|
+
async function handle_thrown(thrown, def, ctx) {
|
|
267
|
+
if (is_redirect(thrown)) return redirect_response(thrown.status, thrown.location);
|
|
268
|
+
if (is_action_failure(thrown)) return json_response(thrown.data, { status: thrown.status });
|
|
269
|
+
if (!is_http_error(thrown)) throw thrown;
|
|
270
|
+
const { status, message } = thrown;
|
|
271
|
+
if (def.__ogkind === "endpoint") return json_response({
|
|
272
|
+
error: message,
|
|
273
|
+
status
|
|
274
|
+
}, { status });
|
|
275
|
+
const pnode = def;
|
|
276
|
+
const load_defs = [
|
|
277
|
+
root_load,
|
|
278
|
+
...pnode.layouts.map((l) => l.load),
|
|
279
|
+
pnode.load
|
|
280
|
+
];
|
|
281
|
+
const settled = await Promise.allSettled(load_defs.map(async (l) => l ? await l(ctx) : void 0));
|
|
282
|
+
let failing = settled.length;
|
|
283
|
+
for (let i = 0; i < settled.length; i++) if (settled[i].status === "rejected") {
|
|
284
|
+
failing = i;
|
|
285
|
+
break;
|
|
286
|
+
}
|
|
287
|
+
const renderable = failing === 0 ? 0 : Math.min(failing - 1, pnode.layouts.length);
|
|
288
|
+
const data = {};
|
|
289
|
+
for (const s of settled) if (s.status === "fulfilled" && s.value && typeof s.value === "object" && !(s.value instanceof Response)) Object.assign(data, s.value);
|
|
290
|
+
let boundary = -1;
|
|
291
|
+
for (let i = renderable - 1; i >= 0; i--) if (pnode.layouts[i].error) {
|
|
292
|
+
boundary = i;
|
|
293
|
+
break;
|
|
294
|
+
}
|
|
295
|
+
const err_component = boundary >= 0 ? pnode.layouts[boundary].error : opts.error;
|
|
296
|
+
if (!err_component) return json_response({
|
|
297
|
+
error: message,
|
|
298
|
+
status
|
|
299
|
+
}, { status });
|
|
300
|
+
const chrome = (boundary >= 0 ? pnode.layouts.slice(0, boundary + 1) : []).map((l) => l.component);
|
|
301
|
+
const of = region(LayoutChain, {
|
|
302
|
+
chain: chrome,
|
|
303
|
+
component: err_component,
|
|
304
|
+
props: {
|
|
305
|
+
status,
|
|
306
|
+
error: { message },
|
|
307
|
+
data,
|
|
308
|
+
params: ctx.params
|
|
309
|
+
},
|
|
310
|
+
data
|
|
311
|
+
});
|
|
312
|
+
const css_head = await componentCssHead([...chrome, err_component]);
|
|
313
|
+
return document(of, {
|
|
314
|
+
status,
|
|
315
|
+
head: css_head,
|
|
316
|
+
pageState: {
|
|
317
|
+
url: ctx.url,
|
|
318
|
+
params: ctx.params,
|
|
319
|
+
route: { id: ctx.route.id || null },
|
|
320
|
+
status,
|
|
321
|
+
data,
|
|
322
|
+
error: { message }
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
__ogrouter: true,
|
|
328
|
+
fetch: dispatch,
|
|
329
|
+
handle: async ({ event, resolve }) => {
|
|
330
|
+
return await dispatch(event.request, event) ?? resolve(event);
|
|
331
|
+
},
|
|
332
|
+
href: ((pattern, params) => href_fn(pattern, params)),
|
|
333
|
+
async entries() {
|
|
334
|
+
const out = [];
|
|
335
|
+
for (const leaf of leaves) {
|
|
336
|
+
if (!is_page(leaf.def)) continue;
|
|
337
|
+
if (!leaf.pattern.includes("[")) {
|
|
338
|
+
out.push({ path: base + leaf.pattern });
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
const list = leaf.def.entries ? await leaf.def.entries() : null;
|
|
342
|
+
if (list) for (const params of list) out.push({ path: base + fill(leaf.pattern, params) });
|
|
343
|
+
}
|
|
344
|
+
return out;
|
|
345
|
+
},
|
|
346
|
+
get $infer() {
|
|
347
|
+
throw new Error("router.$infer is a type-only phantom — read `typeof app.$infer`.");
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
async function run_endpoint(node, ctx, method) {
|
|
352
|
+
const m = HEAD_AS_GET(method);
|
|
353
|
+
const allow = [...node.methods.keys()];
|
|
354
|
+
if (method === "OPTIONS" && !node.methods.has("OPTIONS")) return options_response(allow);
|
|
355
|
+
const e = node.methods.get(m);
|
|
356
|
+
if (!e) return method_not_allowed(allow);
|
|
357
|
+
if (e.bodySchema) {
|
|
358
|
+
let body = void 0;
|
|
359
|
+
if ((ctx.request.headers.get("content-type") ?? "").includes("application/json")) try {
|
|
360
|
+
body = await ctx.request.clone().json();
|
|
361
|
+
} catch {
|
|
362
|
+
return json_response({ error: "Invalid JSON body" }, { status: 400 });
|
|
363
|
+
}
|
|
364
|
+
const v = await validate(e.bodySchema, body);
|
|
365
|
+
if (v.issues) return json_response({
|
|
366
|
+
error: "Invalid body",
|
|
367
|
+
issues: v.issues
|
|
368
|
+
}, { status: 400 });
|
|
369
|
+
ctx.input = v.value;
|
|
370
|
+
}
|
|
371
|
+
return finalize(await e.handler(ctx));
|
|
372
|
+
}
|
|
373
|
+
/** Run a Standard Schema; issues normalized to `{ message, path }[]`. */
|
|
374
|
+
async function validate(schema, input) {
|
|
375
|
+
const r = await schema["~standard"].validate(input);
|
|
376
|
+
if (r.issues) return { issues: r.issues.map((i) => ({
|
|
377
|
+
message: i.message,
|
|
378
|
+
path: i.path
|
|
379
|
+
})) };
|
|
380
|
+
return { value: r.value };
|
|
381
|
+
}
|
|
382
|
+
const TRAILING_SLASH = /\/+$/;
|
|
383
|
+
function canonical_slash(path, mode) {
|
|
384
|
+
if (mode === "ignore" || path === "/") return null;
|
|
385
|
+
const has = path.endsWith("/");
|
|
386
|
+
if (mode === "never" && has) return path.replace(TRAILING_SLASH, "") || "/";
|
|
387
|
+
if (mode === "always" && !has) return path + "/";
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
function pick_action(node, url) {
|
|
391
|
+
const actions = node.actions;
|
|
392
|
+
if (!actions) return void 0;
|
|
393
|
+
for (const key of url.searchParams.keys()) if (key.startsWith("/")) {
|
|
394
|
+
const named = actions[key.slice(1)];
|
|
395
|
+
if (named) return named;
|
|
396
|
+
}
|
|
397
|
+
return actions.default;
|
|
398
|
+
}
|
|
399
|
+
function page_allow(node) {
|
|
400
|
+
const a = ["GET", "HEAD"];
|
|
401
|
+
if (node.actions && Object.keys(node.actions).length) a.push("POST");
|
|
402
|
+
return a;
|
|
403
|
+
}
|
|
404
|
+
export { routes, when };
|
package/dist/stream.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/** The slot id for the page position (one streamed slot per page in v1). */
|
|
2
|
+
export declare const PAGE_SLOT_ID = "pg";
|
|
3
|
+
/** Bake ANY yielded value to html: a string passes through, an inline region carries its html,
|
|
4
|
+
* a component/held region AWAITS into its bake (island shells + prefixed CSS links included —
|
|
5
|
+
* the same path federated widgets take). */
|
|
6
|
+
export declare function bake_yield(v: unknown): Promise<string>;
|
|
7
|
+
/** Is this page slot an async-generator function? (Svelte components are plain functions —
|
|
8
|
+
* never async generators — so this discriminator needs no brand.) */
|
|
9
|
+
export declare function is_stream_slot(v: unknown): v is (...args: never[]) => AsyncGenerator<unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* Turn a fully-rendered document (first yield in place) + the generator's REMAINING yields into
|
|
12
|
+
* a streamed Response: flush everything up to `</body>` now, append one template chunk per
|
|
13
|
+
* later yield, then the tail. A generator throw after the flush becomes an inline error-card
|
|
14
|
+
* chunk (the page must never end broken) — the status is already on the wire, which is
|
|
15
|
+
* streaming's documented trade.
|
|
16
|
+
*/
|
|
17
|
+
/** One late chunk headed for one slot — the multi-slot unit `stream_document` drains. */
|
|
18
|
+
export interface LateChunk {
|
|
19
|
+
slot: string;
|
|
20
|
+
html: string;
|
|
21
|
+
}
|
|
22
|
+
/** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
|
|
23
|
+
export declare function page_slot_chunks(rest: AsyncGenerator<unknown>): AsyncGenerator<LateChunk>;
|
|
24
|
+
export declare function stream_document(full_html: string, res: Response, rest: AsyncGenerator<LateChunk>, error_slot?: string): Response;
|
|
25
|
+
/** The in-slot failure card (message escaped) — a stream must never end broken or empty. */
|
|
26
|
+
export declare function error_card_html(e: unknown): string;
|
|
27
|
+
/** Drain registered LATE REGIONS (`<Region of={promise}>` holes) in COMPLETION order — the slot
|
|
28
|
+
* that resolves first streams first. A rejection becomes that slot's error card; the others are
|
|
29
|
+
* unaffected (per-slot isolation, the same law as mounts). */
|
|
30
|
+
export declare function late_region_chunks(list: ReadonlyArray<{
|
|
31
|
+
id: string;
|
|
32
|
+
promise: Promise<unknown>;
|
|
33
|
+
}>): AsyncGenerator<LateChunk>;
|
|
34
|
+
/** Interleave chunk sources by READINESS (a page generator + the late-region pool run together;
|
|
35
|
+
* whichever has a chunk ready streams next). Ends when every source ends. */
|
|
36
|
+
export declare function merge_chunks(...sources: AsyncGenerator<LateChunk>[]): AsyncGenerator<LateChunk>;
|
package/dist/stream.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { LATE_BOOT_SCRIPT, lateChunk } from "@ogygia/core/plugin";
|
|
2
|
+
import { escapeText } from "@ogygia/core/plugin/utils";
|
|
3
|
+
// src/stream.ts
|
|
4
|
+
/**
|
|
5
|
+
* STREAMED PAGES — `page(async function* (c, data) { yield region(...); ... })`.
|
|
6
|
+
*
|
|
7
|
+
* "The next state of a slot is a region" is the house law (`query.live` yields regions over the
|
|
8
|
+
* push channel); this is the same vocabulary on the INITIAL response: the FIRST yield renders in
|
|
9
|
+
* the document and the page flushes immediately; every later yield rides down the SAME response
|
|
10
|
+
* as an inert `<template data-og-late>` chunk that swaps into the slot as it parses. One
|
|
11
|
+
* connection, closed when the generator ends — no SSE, no second round trip, and no Svelte
|
|
12
|
+
* streaming needed: each yield is an ordinary synchronous render, only the DOCUMENT is chunked.
|
|
13
|
+
*
|
|
14
|
+
* Islands inside late chunks need no orchestration: `<ogygia-region>` is a custom element, so
|
|
15
|
+
* the moment swapped content lands in the DOM it upgrades, connects, and wakes on its own
|
|
16
|
+
* schedule — the runtime never has to be told.
|
|
17
|
+
*
|
|
18
|
+
* Swapping is driven by ONE small classic inline script in the head (module scripts don't run
|
|
19
|
+
* until parsing ENDS, which for a streamed document is the very thing we're not waiting for).
|
|
20
|
+
* The slot, chunk and boot script are core's late wire (`ogygia/plugin`): core's `<Region
|
|
21
|
+
* of={promise}>` emits the same slots and its runtime applies the same chunks. SPA navigations
|
|
22
|
+
* fetch the COMPLETED stream, so there the runtime applies remaining templates after the body swap.
|
|
23
|
+
*
|
|
24
|
+
* Streaming's honest trades (documented): status/title/headers flush with the first yield — a
|
|
25
|
+
* late error can't change an already-sent 200, and Server-Timing set after the flush is lost.
|
|
26
|
+
*/
|
|
27
|
+
/** The slot id for the page position (one streamed slot per page in v1). */
|
|
28
|
+
const PAGE_SLOT_ID = "pg";
|
|
29
|
+
/** Bake ANY yielded value to html: a string passes through, an inline region carries its html,
|
|
30
|
+
* a component/held region AWAITS into its bake (island shells + prefixed CSS links included —
|
|
31
|
+
* the same path federated widgets take). */
|
|
32
|
+
async function bake_yield(v) {
|
|
33
|
+
if (typeof v === "string") return v;
|
|
34
|
+
if (v && typeof v === "object") {
|
|
35
|
+
const o = v;
|
|
36
|
+
if (typeof o.then === "function") return bake_yield(await v);
|
|
37
|
+
const html = o.html ?? o.props?.html;
|
|
38
|
+
if (html != null) return String(html);
|
|
39
|
+
if (o.kind != null) throw new Error("[@ogygia/router] a yielded region did not bake — mark its import (`with { region: 'raw' }` or a wake) so the component has an identity + client leg.");
|
|
40
|
+
}
|
|
41
|
+
throw new Error("[@ogygia/router] a streamed page must yield regions (region(C, props) / og_html_region(html)) or html strings.");
|
|
42
|
+
}
|
|
43
|
+
/** Is this page slot an async-generator function? (Svelte components are plain functions —
|
|
44
|
+
* never async generators — so this discriminator needs no brand.) */
|
|
45
|
+
function is_stream_slot(v) {
|
|
46
|
+
return Object.prototype.toString.call(v) === "[object AsyncGeneratorFunction]";
|
|
47
|
+
}
|
|
48
|
+
const HEAD_CLOSE_RE = /<\/head>/i;
|
|
49
|
+
const NO_TRANSFORM_RE = /no-transform/i;
|
|
50
|
+
/** Adapt a page GENERATOR's remaining yields into page-slot chunks (bake included). */
|
|
51
|
+
async function* page_slot_chunks(rest) {
|
|
52
|
+
for (;;) {
|
|
53
|
+
const n = await rest.next();
|
|
54
|
+
if (n.done) return;
|
|
55
|
+
yield {
|
|
56
|
+
slot: "pg",
|
|
57
|
+
html: await bake_yield(n.value)
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function stream_document(full_html, res, rest, error_slot = "pg") {
|
|
62
|
+
const with_boot = full_html.replace(HEAD_CLOSE_RE, LATE_BOOT_SCRIPT + "</head>");
|
|
63
|
+
const cut = with_boot.lastIndexOf("</body>");
|
|
64
|
+
const head_part = cut === -1 ? with_boot : with_boot.slice(0, cut);
|
|
65
|
+
const tail_part = cut === -1 ? "" : with_boot.slice(cut);
|
|
66
|
+
const enc = new TextEncoder();
|
|
67
|
+
const body = new ReadableStream({ async start(controller) {
|
|
68
|
+
controller.enqueue(enc.encode(head_part));
|
|
69
|
+
try {
|
|
70
|
+
for (;;) {
|
|
71
|
+
const n = await rest.next();
|
|
72
|
+
if (n.done) break;
|
|
73
|
+
controller.enqueue(enc.encode(lateChunk(n.value.slot, n.value.html)));
|
|
74
|
+
}
|
|
75
|
+
} catch (e) {
|
|
76
|
+
controller.enqueue(enc.encode(lateChunk(error_slot, error_card_html(e))));
|
|
77
|
+
}
|
|
78
|
+
controller.enqueue(enc.encode(tail_part));
|
|
79
|
+
controller.close();
|
|
80
|
+
} });
|
|
81
|
+
const headers = new Headers(res.headers);
|
|
82
|
+
headers.delete("content-length");
|
|
83
|
+
const cc = headers.get("cache-control");
|
|
84
|
+
if (!cc) headers.set("cache-control", "no-transform");
|
|
85
|
+
else if (!NO_TRANSFORM_RE.test(cc)) headers.set("cache-control", `${cc}, no-transform`);
|
|
86
|
+
return new Response(body, {
|
|
87
|
+
status: res.status,
|
|
88
|
+
headers
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** The in-slot failure card (message escaped) — a stream must never end broken or empty. */
|
|
92
|
+
function error_card_html(e) {
|
|
93
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
94
|
+
return `<div data-og-late-error style="border:1px dashed #dc2626;border-radius:8px;padding:1rem;color:#dc2626">This section failed to load. ${escapeText(msg)}</div>`;
|
|
95
|
+
}
|
|
96
|
+
/** Drain registered LATE REGIONS (`<Region of={promise}>` holes) in COMPLETION order — the slot
|
|
97
|
+
* that resolves first streams first. A rejection becomes that slot's error card; the others are
|
|
98
|
+
* unaffected (per-slot isolation, the same law as mounts). */
|
|
99
|
+
async function* late_region_chunks(list) {
|
|
100
|
+
const pending = new Map(list.map(({ id, promise }) => [id, promise.then(async (v) => ({
|
|
101
|
+
id,
|
|
102
|
+
html: await bake_yield(v)
|
|
103
|
+
}), (e) => ({
|
|
104
|
+
id,
|
|
105
|
+
html: error_card_html(e)
|
|
106
|
+
}))]));
|
|
107
|
+
while (pending.size) {
|
|
108
|
+
const { id, html } = await Promise.race(pending.values());
|
|
109
|
+
pending.delete(id);
|
|
110
|
+
yield {
|
|
111
|
+
slot: id,
|
|
112
|
+
html
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** Interleave chunk sources by READINESS (a page generator + the late-region pool run together;
|
|
117
|
+
* whichever has a chunk ready streams next). Ends when every source ends. */
|
|
118
|
+
async function* merge_chunks(...sources) {
|
|
119
|
+
const nexts = new Map(sources.map((s, i) => [i, s.next().then((r) => ({
|
|
120
|
+
i,
|
|
121
|
+
r
|
|
122
|
+
}))]));
|
|
123
|
+
while (nexts.size) {
|
|
124
|
+
const { i, r } = await Promise.race(nexts.values());
|
|
125
|
+
if (r.done) nexts.delete(i);
|
|
126
|
+
else {
|
|
127
|
+
nexts.set(i, sources[i].next().then((res) => ({
|
|
128
|
+
i,
|
|
129
|
+
r: res
|
|
130
|
+
})));
|
|
131
|
+
yield r.value;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export { PAGE_SLOT_ID, bake_yield, error_card_html, is_stream_slot, late_region_chunks, merge_chunks, page_slot_chunks, stream_document };
|
package/dist/view.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { StandardIssue, StandardResult, StandardSchemaV1, StandardSchemaV1 as StandardSchemaV1$1 } from "@ogygia/core/plugin/utils";
|
|
2
|
+
export type InferOutput<S> = S extends StandardSchemaV1$1<infer O> ? O : never;
|
|
3
|
+
/** Route params derived from the pattern string via template literals — `/docs/[slug]` → { slug: string },
|
|
4
|
+
* `/[[lang]]` → { lang?: string }, `/[...rest]` → { rest: string }, `/[id].json` → { id: string }. No codegen. */
|
|
5
|
+
export type Simplify<T> = { [K in keyof T]: T[K]; } & {};
|
|
6
|
+
type SegParam<S extends string> = S extends `[[${infer O}]]` ? { [K in O]?: string; } : S extends `[...${infer R}]` ? { [K in R]: string; } : S extends `${string}[${infer N}]${string}` ? { [K in N]: string; } : {};
|
|
7
|
+
type ParamsAcc<P extends string> = P extends `${infer A}/${infer B}` ? SegParam<A> & ParamsAcc<B> : SegParam<P>;
|
|
8
|
+
export type Params<P extends string> = Simplify<ParamsAcc<P>>;
|
|
9
|
+
/** The params object `href` accepts for a pattern — every param, as a string or number. */
|
|
10
|
+
export type HrefParams<P extends string> = { [K in keyof Params<P>]: string | number; };
|
|
11
|
+
/** href args: params are REQUIRED when the pattern has any, omittable when it has none. */
|
|
12
|
+
export type HrefArgs<P extends string> = {} extends Params<P> ? [params?: HrefParams<P>] : [params: HrefParams<P>];
|
|
13
|
+
export type { StandardIssue, StandardResult, StandardSchemaV1 };
|
package/dist/view.js
ADDED
|
File without changes
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Ctx, Visitor } from "./ctx.js";
|
|
2
|
+
export interface AnonymousVisitorOptions {
|
|
3
|
+
/** Cookie name (default `og-vid` — the same one experiment()'s fallback chain reads). */
|
|
4
|
+
cookie?: string;
|
|
5
|
+
/** Cookie lifetime in days (default 365). */
|
|
6
|
+
days?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function anonymousVisitor(opts?: AnonymousVisitorOptions): (c: Ctx) => Visitor | undefined;
|
package/dist/visitor.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
// src/visitor.ts
|
|
3
|
+
/**
|
|
4
|
+
* Anonymous visitor identity — sticky experiments/flags/rollouts for LOGGED-OUT traffic.
|
|
5
|
+
* Without an identity, splits degrade to control (nothing to hash on); this resolver mints a
|
|
6
|
+
* random id into a cookie on first sight and returns it as `{ sub }` forever after, so a
|
|
7
|
+
* rollout percentage holds for anonymous visitors too.
|
|
8
|
+
*
|
|
9
|
+
* routes(table, { visitor: anonymousVisitor() }) // anonymous-only
|
|
10
|
+
* routes(table, { visitor: (c) => session(c) ?? anon(c) }) // session first
|
|
11
|
+
*
|
|
12
|
+
* The id is random (not a fingerprint), first-party, and carries nothing — rotate it by
|
|
13
|
+
* clearing the cookie. GDPR-wise it is a functional identifier; consult your own counsel.
|
|
14
|
+
*/
|
|
15
|
+
function anonymousVisitor(opts = {}) {
|
|
16
|
+
const name = opts.cookie ?? "og-vid";
|
|
17
|
+
const max_age = (opts.days ?? 365) * 86400;
|
|
18
|
+
return (c) => {
|
|
19
|
+
const existing = c.cookies?.get(name);
|
|
20
|
+
if (existing) return {
|
|
21
|
+
sub: existing,
|
|
22
|
+
anonymous: true
|
|
23
|
+
};
|
|
24
|
+
const id = randomUUID();
|
|
25
|
+
if (c.cookies?.set) c.cookies.set(name, id, {
|
|
26
|
+
path: "/",
|
|
27
|
+
maxAge: max_age,
|
|
28
|
+
httpOnly: true,
|
|
29
|
+
sameSite: "lax"
|
|
30
|
+
});
|
|
31
|
+
else c.setHeaders?.({ "set-cookie": `${name}=${id}; Path=/; Max-Age=${max_age}; HttpOnly; SameSite=Lax` });
|
|
32
|
+
return {
|
|
33
|
+
sub: id,
|
|
34
|
+
anonymous: true
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
export { anonymousVisitor };
|
package/dist/vite.d.ts
ADDED
package/dist/vite.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { definePlugin } from "@ogygia/core/vite";
|
|
2
|
+
// src/vite.ts
|
|
3
|
+
/**
|
|
4
|
+
* `router()` — the server router, listed beside `ogygia()` in vite.config. A `routes()` table
|
|
5
|
+
* renders pages outside Kit's routes, so nothing file-derived links their components' CSS: listing the
|
|
6
|
+
* plugin tells the build that every module importing `@ogygia/router` is a page module, and every
|
|
7
|
+
* component it can reach gets its whole-tree CSS linked when it renders. It also makes the package the
|
|
8
|
+
* app's own code to the build (server-inlined: it ships `.svelte`).
|
|
9
|
+
*/
|
|
10
|
+
function router() {
|
|
11
|
+
return definePlugin({
|
|
12
|
+
name: "@ogygia/router",
|
|
13
|
+
build(b) {
|
|
14
|
+
b.pageModules({ importers: ["@ogygia/router"] });
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
export { router };
|