@opentf/afw 0.39.0 → 0.40.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/core/fn-codec.js +9 -0
- package/jsx-runtime.d.ts +46 -2
- package/macros.d.ts +13 -0
- package/package.json +1 -1
- package/runtime/dom.d.ts +2 -0
- package/runtime/dom.js +57 -8
- package/runtime/error-boundary.js +11 -1
- package/runtime/hmr.js +70 -10
- package/runtime/hydrate.d.ts +4 -0
- package/runtime/hydrate.js +44 -0
- package/runtime/index.d.ts +1 -0
- package/runtime/index.js +1 -0
- package/runtime/invalidate.d.ts +7 -4
- package/runtime/invalidate.js +150 -38
- package/runtime/mutate.d.ts +16 -0
- package/runtime/mutate.js +79 -0
- package/runtime/portal.js +3 -1
- package/runtime/query-cache.js +265 -0
- package/runtime/resource.d.ts +24 -0
- package/runtime/resource.js +203 -44
- package/runtime/revalidate.js +39 -0
- package/runtime/route-data.d.ts +9 -3
- package/runtime/route-data.js +28 -7
- package/runtime/route-match.js +11 -4
- package/runtime/router.js +17 -4
- package/runtime/server-function.js +78 -8
- package/server/index.d.ts +17 -2
- package/server/server-functions.js +101 -4
- package/server/ssg-runtime.js +32 -0
|
@@ -2,12 +2,53 @@
|
|
|
2
2
|
// `*.server` module with stubs made here: `serverFunction("/todos/__fn/<id>", "query")`
|
|
3
3
|
// is an async function with the server function's signature that calls its endpoint.
|
|
4
4
|
|
|
5
|
-
import { CONTENT_TYPE, decode, encode } from "../core/fn-codec.js";
|
|
6
|
-
import { trackServerCall } from "./invalidate.js";
|
|
5
|
+
import { CONTENT_TYPE, LIVE_HEADER, MAX_REFRESH, REFRESH_HEADER, decode, encode } from "../core/fn-codec.js";
|
|
6
|
+
import { liveCalls, trackServerCall } from "./invalidate.js";
|
|
7
|
+
import { applyRefresh } from "./mutate.js";
|
|
8
|
+
import { callKey, fetchShared } from "./query-cache.js";
|
|
7
9
|
|
|
8
10
|
// Queries go by GET while the encoded arguments fit comfortably in a URL.
|
|
9
11
|
const MAX_GET_ARGS = 2000;
|
|
10
12
|
|
|
13
|
+
// A query whose request never reached the server (`fetch` itself rejected: offline, a
|
|
14
|
+
// dropped connection) is retried after these delays. An HTTP error answer is the
|
|
15
|
+
// server's, and actions are never retried: their request may have been applied.
|
|
16
|
+
let retryDelays = [300, 1000];
|
|
17
|
+
|
|
18
|
+
/** Replace the query retry delays (tests only). */
|
|
19
|
+
export function __setRetryDelays(delays) {
|
|
20
|
+
retryDelays = delays;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Wait `ms`, or reject as soon as `signal` aborts. */
|
|
24
|
+
function wait(ms, signal) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
27
|
+
const timer = setTimeout(() => {
|
|
28
|
+
signal?.removeEventListener("abort", stop);
|
|
29
|
+
resolve();
|
|
30
|
+
}, ms);
|
|
31
|
+
function stop() {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
reject(signal.reason);
|
|
34
|
+
}
|
|
35
|
+
signal?.addEventListener("abort", stop, { once: true });
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `fetch`, retried on network failure for queries. */
|
|
40
|
+
async function request(url, init, retry) {
|
|
41
|
+
for (let attempt = 0; ; attempt++) {
|
|
42
|
+
try {
|
|
43
|
+
return await fetch(url, init);
|
|
44
|
+
} catch (error) {
|
|
45
|
+
const aborted = init.signal?.aborted || error?.name === "AbortError";
|
|
46
|
+
if (!retry || aborted || attempt >= retryDelays.length) throw error;
|
|
47
|
+
await wait(retryDelays[attempt], init.signal);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
11
52
|
/** A failed server function call: `status`, and `issues` when the input was invalid. */
|
|
12
53
|
export class ServerFunctionError extends Error {
|
|
13
54
|
constructor(message, { status, issues, redirected = false } = {}) {
|
|
@@ -23,20 +64,49 @@ export class ServerFunctionError extends Error {
|
|
|
23
64
|
* A stub for the server function at `endpoint`. `kind` is `"query"` (GET, or POST for
|
|
24
65
|
* large arguments) or `"action"` (POST). The stub takes the input and an optional
|
|
25
66
|
* `{ signal }` to abort the call.
|
|
67
|
+
*
|
|
68
|
+
* Query calls go through the query cache: identical calls in flight share one request,
|
|
69
|
+
* and a call made by a starting resource may answer from a fresh entry (`staleTime`).
|
|
70
|
+
* Actions always make their own request.
|
|
26
71
|
*/
|
|
27
72
|
export function serverFunction(endpoint, kind) {
|
|
28
|
-
|
|
29
|
-
|
|
73
|
+
function call(input, { signal } = {}) {
|
|
74
|
+
if (kind !== "query") {
|
|
75
|
+
trackServerCall(endpoint); // a resource starting this call depends on it (invalidate)
|
|
76
|
+
return act(input, signal);
|
|
77
|
+
}
|
|
78
|
+
let key;
|
|
79
|
+
try {
|
|
80
|
+
key = callKey(endpoint, input);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
return Promise.reject(error); // an input the codec refuses (a function, a symbol)
|
|
83
|
+
}
|
|
84
|
+
const staleTime = trackServerCall(endpoint, key) ?? 0;
|
|
85
|
+
return fetchShared(key, (shared) => send(input, shared).then((r) => r.value), { signal, staleTime, call: [endpoint, input] });
|
|
86
|
+
}
|
|
87
|
+
// An action sends the calls the page shows, so its `refresh()` can answer them in the
|
|
88
|
+
// response; the fresh data is in the cache before the call resolves.
|
|
89
|
+
async function act(input, signal) {
|
|
90
|
+
const live = liveCalls(MAX_REFRESH);
|
|
91
|
+
const { value, refreshed } = live.length
|
|
92
|
+
? await send({ input, live }, signal, { [LIVE_HEADER]: "1" })
|
|
93
|
+
: await send(input, signal);
|
|
94
|
+
if (!refreshed) return value;
|
|
95
|
+
await applyRefresh(value.refresh);
|
|
96
|
+
return value.result;
|
|
97
|
+
}
|
|
98
|
+
async function send(input, signal, extra) {
|
|
30
99
|
const args = encode(input);
|
|
31
|
-
const init = { signal, credentials: "same-origin", redirect: "manual", headers: { accept: CONTENT_TYPE } };
|
|
100
|
+
const init = { signal, credentials: "same-origin", redirect: "manual", headers: { accept: CONTENT_TYPE, ...extra } };
|
|
101
|
+
const retry = kind === "query";
|
|
32
102
|
const response = kind === "query" && args.length <= MAX_GET_ARGS
|
|
33
|
-
? await
|
|
34
|
-
: await
|
|
103
|
+
? await request(`${endpoint}?a=${encodeURIComponent(args)}`, init, retry)
|
|
104
|
+
: await request(endpoint, { ...init, method: "POST", headers: { ...init.headers, "content-type": CONTENT_TYPE }, body: args }, retry);
|
|
35
105
|
// A redirect (an auth guard sending to a login page, say) is not data: the caller decides.
|
|
36
106
|
if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
|
|
37
107
|
throw new ServerFunctionError("The server redirected the call", { status: response.status || 302, redirected: true });
|
|
38
108
|
}
|
|
39
|
-
if (response.ok) return decode(await response.text());
|
|
109
|
+
if (response.ok) return { value: decode(await response.text()), refreshed: response.headers.get(REFRESH_HEADER) === "1" };
|
|
40
110
|
let body = null;
|
|
41
111
|
try {
|
|
42
112
|
body = await response.json();
|
package/server/index.d.ts
CHANGED
|
@@ -174,6 +174,10 @@ export function attr(name: string, value: unknown): string;
|
|
|
174
174
|
export function ssgText(v: unknown): string;
|
|
175
175
|
export function ssgList<T>(arr: T[], fn: (item: T, index: number) => string): string;
|
|
176
176
|
export function ssgComponent(tag: string, props?: Record<string, unknown>, children?: unknown): string;
|
|
177
|
+
/** Render `children()` with `context` provided as `value` (a server-rendered `<ContextProvider>`). */
|
|
178
|
+
export function ssgProvide(context: unknown, value: unknown, children: () => string): string;
|
|
179
|
+
/** `$context(context)` on the server: the nearest provided value, else the context's default. */
|
|
180
|
+
export function ssgContext<T>(context: { fallback: { value: T } }): { value: T };
|
|
177
181
|
|
|
178
182
|
// ── Server functions (server-functions.js, docs/SERVER_FUNCTIONS.md) ───────────
|
|
179
183
|
/** A Standard Schema (https://standardschema.dev): zod, valibot, arktype… */
|
|
@@ -199,10 +203,21 @@ export interface ServerFunctionContext {
|
|
|
199
203
|
locals: Record<string, unknown>;
|
|
200
204
|
env?: unknown;
|
|
201
205
|
ctx?: unknown;
|
|
206
|
+
/**
|
|
207
|
+
* In an action called from the browser: re-run these queries after the action and send
|
|
208
|
+
* their fresh data with its response (single-flight updates). A query alone refreshes
|
|
209
|
+
* every input the page shows; a value after it, that one input:
|
|
210
|
+
* `refresh(listTodos, getTodo, { id })`. Queries outside the action's folder (or its
|
|
211
|
+
* parents) are refetched by the browser instead. A no-op elsewhere.
|
|
212
|
+
*/
|
|
213
|
+
refresh: (...targets: unknown[]) => void;
|
|
202
214
|
}
|
|
203
215
|
|
|
204
|
-
/**
|
|
205
|
-
|
|
216
|
+
/**
|
|
217
|
+
* A server function: called with its input, and a context from server code. In the
|
|
218
|
+
* browser the stub takes `{ signal }` to abort the call (and `resource()` passes one).
|
|
219
|
+
*/
|
|
220
|
+
export type ServerFunction<Input, Output> = (input: Input, context?: Partial<ServerFunctionContext> & { signal?: AbortSignal }) => Promise<Awaited<Output>>;
|
|
206
221
|
|
|
207
222
|
/** A read: idempotent, callable with GET or POST. */
|
|
208
223
|
export function query<Output, Input = void>(fn: (input: Input, context: ServerFunctionContext) => Output): ServerFunction<Input, Output>;
|
|
@@ -8,12 +8,29 @@
|
|
|
8
8
|
// The build gives each function an endpoint under its folder (`/todos/__fn/<id>`), so
|
|
9
9
|
// that folder's `_middleware` guards it like a page. `createServerFunctions` turns the
|
|
10
10
|
// build's `{ endpoint: fn }` map into a handler for those requests.
|
|
11
|
+
//
|
|
12
|
+
// Single-flight updates: an action names the queries it changed with `refresh()` from
|
|
13
|
+
// its context, and their fresh results go back with its own response:
|
|
14
|
+
//
|
|
15
|
+
// export const addTodo = action(schema, async (input, { refresh }) => {
|
|
16
|
+
// await db.insert(input);
|
|
17
|
+
// refresh(listTodos); // every input of listTodos the page shows
|
|
18
|
+
// refresh(getTodo, { id: 1 }); // or one input
|
|
19
|
+
// });
|
|
20
|
+
//
|
|
21
|
+
// The browser sends the inputs of the queries it shows (`x-afw-live`, at most
|
|
22
|
+
// MAX_REFRESH); the server re-runs the named ones after the action and returns them.
|
|
23
|
+
// Only queries in the action's folder or a parent folder run there, since their
|
|
24
|
+
// middleware already ran for this request; others go back as stale and the browser
|
|
25
|
+
// refetches them through their own middleware.
|
|
11
26
|
|
|
12
|
-
import { CONTENT_TYPE, MAX_DEPTH, SerializeError, decode, encode } from "../core/fn-codec.js";
|
|
27
|
+
import { CONTENT_TYPE, LIVE_HEADER, MAX_DEPTH, MAX_REFRESH, REFRESH_HEADER, SerializeError, decode, encode } from "../core/fn-codec.js";
|
|
13
28
|
import { isNotFound } from "./loader.js";
|
|
14
29
|
|
|
15
30
|
const MARK = Symbol.for("afw.serverFunction");
|
|
16
31
|
|
|
32
|
+
const noRefresh = () => {};
|
|
33
|
+
|
|
17
34
|
/** Thrown to the caller when the input does not match the function's schema. */
|
|
18
35
|
export class ValidationError extends Error {
|
|
19
36
|
constructor(issues) {
|
|
@@ -41,7 +58,9 @@ function define(kind, args) {
|
|
|
41
58
|
if (typeof handler !== "function") throw new TypeError(`${kind}(): the last argument must be a function`);
|
|
42
59
|
// Called directly from server code (a loader, an API route, another function): run it
|
|
43
60
|
// with the given context, input validated the same way as over HTTP.
|
|
44
|
-
|
|
61
|
+
// `refresh` is a no-op outside an HTTP action call, so a handler can always call it.
|
|
62
|
+
const fn = async (input, context = {}) =>
|
|
63
|
+
handler(await validate(schema, input), typeof context.refresh === "function" ? context : { ...context, refresh: noRefresh });
|
|
45
64
|
Object.defineProperty(fn, MARK, { value: { kind, schema, handler } });
|
|
46
65
|
return fn;
|
|
47
66
|
}
|
|
@@ -88,10 +107,58 @@ function crossSite(request, url) {
|
|
|
88
107
|
export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 1024, maxDepth = MAX_DEPTH } = {}) {
|
|
89
108
|
const limits = { maxLength: maxBodyBytes, maxDepth };
|
|
90
109
|
const table = new Map();
|
|
110
|
+
const paths = new Map(); // fn → endpoint, for `refresh(listTodos)`
|
|
91
111
|
for (const [path, fn] of Object.entries(endpoints)) {
|
|
92
112
|
const kind = serverFunctionKind(fn);
|
|
93
113
|
if (!kind) throw new TypeError(`${path}: not a query() or action()`);
|
|
94
114
|
table.set(path, { kind, fn });
|
|
115
|
+
paths.set(fn, path);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** `refresh()`'s arguments as targets: a query, optionally followed by one input. */
|
|
119
|
+
function targetsOf(args, into) {
|
|
120
|
+
for (let i = 0; i < args.length; i++) {
|
|
121
|
+
const path = paths.get(args[i]);
|
|
122
|
+
if (!path || table.get(path).kind !== "query") {
|
|
123
|
+
throw new TypeError("refresh() takes queries exported from a .server module, each optionally followed by its input");
|
|
124
|
+
}
|
|
125
|
+
if (i + 1 < args.length && typeof args[i + 1] !== "function") into.push({ path, inputs: [args[++i]] });
|
|
126
|
+
else into.push({ path, inputs: null });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Re-run the queries an action refreshed: `{ fresh: [[endpoint, input, data]],
|
|
132
|
+
* stale: [[endpoint, input?]], endpoints }`. `live` holds the inputs the page shows;
|
|
133
|
+
* `endpoints` are the queries refreshed without an input (all their calls changed).
|
|
134
|
+
*/
|
|
135
|
+
async function runRefresh(action, targets, live, ctx) {
|
|
136
|
+
const folder = folderOf(action);
|
|
137
|
+
const fresh = [];
|
|
138
|
+
const stale = [];
|
|
139
|
+
const endpoints = new Set();
|
|
140
|
+
const runs = [];
|
|
141
|
+
for (const { path, inputs } of targets) {
|
|
142
|
+
// A query refreshed without an input covers all of its calls; with one, only that.
|
|
143
|
+
if (!inputs) endpoints.add(path);
|
|
144
|
+
if (!inScope(folder, folderOf(path))) {
|
|
145
|
+
// Its own middleware must run: the browser refetches it.
|
|
146
|
+
if (inputs) for (const input of inputs) stale.push([path, input]);
|
|
147
|
+
else stale.push([path]);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
for (const input of inputs ?? live.filter(([p]) => p === path).map(([, i]) => i)) {
|
|
151
|
+
if (runs.length >= MAX_REFRESH) stale.push([path, input]);
|
|
152
|
+
else runs.push({ path, input });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
const settled = await Promise.allSettled(runs.map(({ path, input }) => table.get(path).fn(input, { ...ctx, refresh: noRefresh })));
|
|
156
|
+
settled.forEach((outcome, i) => {
|
|
157
|
+
const { path, input } = runs[i];
|
|
158
|
+
if (outcome.status === "fulfilled") fresh.push([path, input, outcome.value]);
|
|
159
|
+
else stale.push([path, input]); // the browser's own call reports the error
|
|
160
|
+
});
|
|
161
|
+
return { fresh, stale, endpoints: [...endpoints] };
|
|
95
162
|
}
|
|
96
163
|
|
|
97
164
|
async function handle(request, context = {}) {
|
|
@@ -104,6 +171,7 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
|
|
|
104
171
|
if (crossSite(request, url)) return json(403, { error: { message: "Cross-site request refused" } });
|
|
105
172
|
|
|
106
173
|
let input;
|
|
174
|
+
let live = [];
|
|
107
175
|
try {
|
|
108
176
|
if (method === "GET") {
|
|
109
177
|
input = decode(url.searchParams.get("a") ?? "", limits);
|
|
@@ -112,6 +180,10 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
|
|
|
112
180
|
// Forms and plain-text posts can be sent cross-site without a preflight; JSON cannot.
|
|
113
181
|
if (!type.startsWith(CONTENT_TYPE)) return json(415, { error: { message: `Expected ${CONTENT_TYPE}` } });
|
|
114
182
|
input = decode(await request.text(), limits);
|
|
183
|
+
if (entry.kind === "action" && request.headers.get(LIVE_HEADER) === "1") {
|
|
184
|
+
if (!isEnvelope(input)) return json(400, { error: { message: "Malformed request body" } });
|
|
185
|
+
({ input, live } = input);
|
|
186
|
+
}
|
|
115
187
|
}
|
|
116
188
|
} catch (error) {
|
|
117
189
|
if (error instanceof SerializeError && error.code === "INPUT_TOO_LARGE") {
|
|
@@ -121,10 +193,17 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
|
|
|
121
193
|
}
|
|
122
194
|
|
|
123
195
|
const ctx = { request, url, locals: context.locals ?? {}, env: context.env, ctx: context.ctx };
|
|
196
|
+
const targets = [];
|
|
197
|
+
if (entry.kind === "action") ctx.refresh = (...args) => targetsOf(args, targets);
|
|
124
198
|
try {
|
|
125
199
|
const result = await entry.fn(input, ctx);
|
|
126
|
-
|
|
127
|
-
|
|
200
|
+
const headers = { "content-type": CONTENT_TYPE, "cache-control": "no-store" };
|
|
201
|
+
if (targets.length === 0) {
|
|
202
|
+
// A result the codec refuses (a class instance, a function) is a server bug: 500.
|
|
203
|
+
return new Response(encode(result), { status: 200, headers });
|
|
204
|
+
}
|
|
205
|
+
const refresh = await runRefresh(url.pathname, targets, live, ctx);
|
|
206
|
+
return new Response(encode({ result, refresh }), { status: 200, headers: { ...headers, [REFRESH_HEADER]: "1" } });
|
|
128
207
|
} catch (error) {
|
|
129
208
|
if (error instanceof Response) return error; // a redirect or custom status from the function
|
|
130
209
|
if (error instanceof ValidationError) return json(400, { error: { message: error.message, issues: error.issues } });
|
|
@@ -136,3 +215,21 @@ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 10
|
|
|
136
215
|
|
|
137
216
|
return { size: table.size, handle };
|
|
138
217
|
}
|
|
218
|
+
|
|
219
|
+
/** The folder of an endpoint: `/todos/__fn/x` → `/todos`, `/__fn/x` → `""`. */
|
|
220
|
+
function folderOf(endpoint) {
|
|
221
|
+
const i = endpoint.lastIndexOf("/__fn/");
|
|
222
|
+
return i <= 0 ? "" : endpoint.slice(0, i);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Is `query` in `action`'s folder or above it (so its middleware ran for the action)? */
|
|
226
|
+
function inScope(action, query) {
|
|
227
|
+
return query === "" || action === query || action.startsWith(`${query}/`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** An action body with the page's shown queries: `{ input, live: [[endpoint, input]] }`. */
|
|
231
|
+
function isEnvelope(body) {
|
|
232
|
+
if (!body || typeof body !== "object" || !("input" in body) || !Array.isArray(body.live)) return false;
|
|
233
|
+
if (body.live.length > MAX_REFRESH) return false;
|
|
234
|
+
return body.live.every((call) => Array.isArray(call) && call.length === 2 && typeof call[0] === "string");
|
|
235
|
+
}
|
package/server/ssg-runtime.js
CHANGED
|
@@ -94,6 +94,10 @@ function jsonSafeProps(props) {
|
|
|
94
94
|
} catch {
|
|
95
95
|
return null; // cyclic / non-serializable → client falls back to attributes/defaults
|
|
96
96
|
}
|
|
97
|
+
// Function props (callbacks, render props) are named instead: the client component
|
|
98
|
+
// waits for its parent to set them before it adopts (`awaitHydrationProps`).
|
|
99
|
+
const fns = Object.keys(props).filter((key) => typeof props[key] === "function");
|
|
100
|
+
if (fns.length) safe = { ...(safe && typeof safe === "object" ? safe : {}), __afwFn: fns };
|
|
97
101
|
if (!safe || typeof safe !== "object" || Object.keys(safe).length === 0) return null;
|
|
98
102
|
return safe;
|
|
99
103
|
}
|
|
@@ -267,6 +271,8 @@ export function ssgList(arr, fn) {
|
|
|
267
271
|
*/
|
|
268
272
|
export function ssgComponent(tag, props, children) {
|
|
269
273
|
const render = registry[tag];
|
|
274
|
+
// A `<ContextProvider>`'s children arrive as a thunk: render them with its value in scope.
|
|
275
|
+
if (typeof children === "function") children = ssgProvide(props?.context, props?.value, children);
|
|
270
276
|
let inner;
|
|
271
277
|
try {
|
|
272
278
|
inner = render ? render(props || {}, children ?? "") : (children ?? "");
|
|
@@ -294,4 +300,30 @@ export function ssgComponent(tag, props, children) {
|
|
|
294
300
|
return `<${tag}${attrs}>${inner}</${tag}>`;
|
|
295
301
|
}
|
|
296
302
|
|
|
303
|
+
/*
|
|
304
|
+
* Context on the server. A page renders synchronously to a string, so the providers
|
|
305
|
+
* enclosing the component being rendered are a stack: `<ContextProvider>` pushes while
|
|
306
|
+
* its children render, and `$context` reads the nearest entry for its context.
|
|
307
|
+
*/
|
|
308
|
+
const providers = [];
|
|
309
|
+
|
|
310
|
+
/** Render `children()` with `context` provided as `value`. */
|
|
311
|
+
export function ssgProvide(context, value, children) {
|
|
312
|
+
if (!context) return children();
|
|
313
|
+
providers.push([context, value]);
|
|
314
|
+
try {
|
|
315
|
+
return children();
|
|
316
|
+
} finally {
|
|
317
|
+
providers.pop();
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** `$context(context)` on the server: the nearest provided value, else the default. */
|
|
322
|
+
export function ssgContext(context) {
|
|
323
|
+
for (let i = providers.length - 1; i >= 0; i--) {
|
|
324
|
+
if (providers[i][0] === context) return { value: providers[i][1] };
|
|
325
|
+
}
|
|
326
|
+
return context.fallback;
|
|
327
|
+
}
|
|
328
|
+
|
|
297
329
|
export { VOID };
|