@rsc-kit/core 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.
- package/dist/changed.js +1 -1
- package/dist/changed.js.map +1 -1
- package/dist/conformance.d.ts +2 -2
- package/dist/conformance.js +4 -4
- package/dist/conformance.js.map +1 -1
- package/dist/devLock.d.ts +22 -5
- package/dist/devLock.js +22 -7
- package/dist/devLock.js.map +1 -1
- package/dist/host.d.ts +1 -1
- package/dist/host.js +59 -2
- package/dist/host.js.map +1 -1
- package/dist/hostCalls.d.ts +1 -1
- package/dist/hostCalls.js +1 -1
- package/dist/hostCalls.js.map +1 -1
- package/dist/hostRouting.d.ts +28 -0
- package/dist/hostRouting.js +65 -0
- package/dist/hostRouting.js.map +1 -1
- package/dist/js/Link.js +11 -3
- package/dist/js/Link.js.map +1 -1
- package/dist/js/navigate.d.ts +6 -0
- package/dist/js/navigate.js +28 -0
- package/dist/js/navigate.js.map +1 -1
- package/dist/manifest.d.ts +2 -0
- package/dist/manifest.js.map +1 -1
- package/dist/purge.d.ts +16 -14
- package/dist/purge.js +27 -25
- package/dist/purge.js.map +1 -1
- package/dist/routes.d.ts +6 -0
- package/dist/routes.js +12 -0
- package/dist/routes.js.map +1 -1
- package/dist/vite.d.ts +52 -0
- package/dist/vite.js +194 -15
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/purge.d.ts
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* the names that changed - after the answer has gone, through `after()`, so a
|
|
9
9
|
* slow CDN never holds up the action that made the change.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
* hook is `
|
|
11
|
+
* One is installed for you: with `CDN_PURGE_URL` set, the
|
|
12
|
+
* hook is `cdnPurge()` unless the app installed another.
|
|
13
13
|
*
|
|
14
14
|
* A Laravel or Go backend changes its names itself (`Rsc::changed()`,
|
|
15
15
|
* `reg.Changed()`), and the engine never hears of it, so each backend
|
|
@@ -23,14 +23,15 @@ export interface Purge {
|
|
|
23
23
|
}
|
|
24
24
|
/** Sends a purge to a CDN. A rejection is logged; it never fails the change. */
|
|
25
25
|
export type Purger = (purge: Purge) => Promise<void> | void;
|
|
26
|
-
/** Install the app's purge. `null` takes it out, and
|
|
26
|
+
/** Install the app's purge. `null` takes it out, and the default with it. */
|
|
27
27
|
export declare function installPurge(purger: Purger | null): void;
|
|
28
|
-
/** The purge in use: the app's, else
|
|
28
|
+
/** The purge in use: the app's, else cdnPurge() when `CDN_PURGE_URL` is set, else none. */
|
|
29
29
|
export declare function installedPurge(): Purger | null;
|
|
30
30
|
/**
|
|
31
|
-
* Where an edge in front of the app takes its purges: `
|
|
32
|
-
*
|
|
33
|
-
*
|
|
31
|
+
* Where an edge in front of the app takes its purges: `CDN_PURGE_URL`, the
|
|
32
|
+
* one name. It belongs to neither side: a platform sets it with nothing of
|
|
33
|
+
* this engine's in its code, and this reads it with nothing of a platform's.
|
|
34
|
+
* `RSC_PURGE_URL` and `HOMEPORT_PURGE_URL` were read before, and are not.
|
|
34
35
|
*/
|
|
35
36
|
export declare function purgeUrl(): string | undefined;
|
|
36
37
|
/**
|
|
@@ -45,21 +46,22 @@ export declare function purgeLater(tags: readonly string[]): void;
|
|
|
45
46
|
* at its `max-age` in `CDN-Cache-Control`. A failure is logged.
|
|
46
47
|
*/
|
|
47
48
|
export declare function purge(what: Purge): Promise<void>;
|
|
48
|
-
/**
|
|
49
|
-
export declare const
|
|
50
|
-
export interface
|
|
51
|
-
/** Where to post. Default `
|
|
49
|
+
/** At most this many tags and paths, together, per call. */
|
|
50
|
+
export declare const CDN_PURGE_LIMIT = 100;
|
|
51
|
+
export interface CdnPurgeOptions {
|
|
52
|
+
/** Where to post. Default `CDN_PURGE_URL`. */
|
|
52
53
|
url?: string;
|
|
53
54
|
/** For tests. */
|
|
54
55
|
fetch?: typeof fetch;
|
|
55
56
|
}
|
|
56
57
|
/**
|
|
57
|
-
*
|
|
58
|
-
*
|
|
58
|
+
* The purge an edge in front takes: `POST {tags, paths, all}` as JSON to
|
|
59
|
+
* `CDN_PURGE_URL`, no token - the url is one reachable only from inside the
|
|
60
|
+
* app's own network.
|
|
59
61
|
* Split into calls of 100 tags and paths together. A tag or path too long for
|
|
60
62
|
* it is left out: one would cost the whole call, and the edge keeps no page
|
|
61
63
|
* with a tag it could not purge. Only a 202 is accepted. A 429 is tried once
|
|
62
64
|
* more after its `Retry-After` (at most five seconds); anything else is that
|
|
63
65
|
* call lost. The rest are still sent, then the purge rejects.
|
|
64
66
|
*/
|
|
65
|
-
export declare function
|
|
67
|
+
export declare function cdnPurge(options?: CdnPurgeOptions): Purger;
|
package/dist/purge.js
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
* the names that changed - after the answer has gone, through `after()`, so a
|
|
9
9
|
* slow CDN never holds up the action that made the change.
|
|
10
10
|
*
|
|
11
|
-
*
|
|
12
|
-
* hook is `
|
|
11
|
+
* One is installed for you: with `CDN_PURGE_URL` set, the
|
|
12
|
+
* hook is `cdnPurge()` unless the app installed another.
|
|
13
13
|
*
|
|
14
14
|
* A Laravel or Go backend changes its names itself (`Rsc::changed()`,
|
|
15
15
|
* `reg.Changed()`), and the engine never hears of it, so each backend
|
|
@@ -25,26 +25,27 @@ function hooks() {
|
|
|
25
25
|
// of the package, and the engine's copy is the one that calls it.
|
|
26
26
|
const PURGER = Symbol.for("rsc-kit.purger");
|
|
27
27
|
const globals = globalThis;
|
|
28
|
-
/** Install the app's purge. `null` takes it out, and
|
|
28
|
+
/** Install the app's purge. `null` takes it out, and the default with it. */
|
|
29
29
|
export function installPurge(purger) {
|
|
30
30
|
globals[PURGER] = purger;
|
|
31
31
|
}
|
|
32
|
-
/** The purge in use: the app's, else
|
|
32
|
+
/** The purge in use: the app's, else cdnPurge() when `CDN_PURGE_URL` is set, else none. */
|
|
33
33
|
export function installedPurge() {
|
|
34
34
|
const installed = globals[PURGER];
|
|
35
35
|
if (installed !== undefined)
|
|
36
36
|
return installed;
|
|
37
37
|
const url = purgeUrl();
|
|
38
|
-
return url ?
|
|
38
|
+
return url ? cdnPurge({ url }) : null;
|
|
39
39
|
}
|
|
40
40
|
/**
|
|
41
|
-
* Where an edge in front of the app takes its purges: `
|
|
42
|
-
*
|
|
43
|
-
*
|
|
41
|
+
* Where an edge in front of the app takes its purges: `CDN_PURGE_URL`, the
|
|
42
|
+
* one name. It belongs to neither side: a platform sets it with nothing of
|
|
43
|
+
* this engine's in its code, and this reads it with nothing of a platform's.
|
|
44
|
+
* `RSC_PURGE_URL` and `HOMEPORT_PURGE_URL` were read before, and are not.
|
|
44
45
|
*/
|
|
45
46
|
export function purgeUrl() {
|
|
46
47
|
const env = globalThis.process?.env;
|
|
47
|
-
return env?.
|
|
48
|
+
return env?.CDN_PURGE_URL || undefined;
|
|
48
49
|
}
|
|
49
50
|
// The names an action changed go out as one purge when its answer has gone:
|
|
50
51
|
// three changed() calls send one request, not three. Gathered per request,
|
|
@@ -95,38 +96,39 @@ export async function purge(what) {
|
|
|
95
96
|
(error instanceof Error ? error.message : String(error)));
|
|
96
97
|
}
|
|
97
98
|
}
|
|
98
|
-
/**
|
|
99
|
-
export const
|
|
100
|
-
/** The longest tag and path
|
|
101
|
-
const
|
|
102
|
-
const
|
|
99
|
+
/** At most this many tags and paths, together, per call. */
|
|
100
|
+
export const CDN_PURGE_LIMIT = 100;
|
|
101
|
+
/** The longest tag and path sent, in bytes. */
|
|
102
|
+
const PURGE_TAG_BYTES = 1024;
|
|
103
|
+
const PURGE_PATH_BYTES = 2048;
|
|
103
104
|
const bytes = new TextEncoder();
|
|
104
105
|
/** How long one call may take, so a purge url that hangs leaves nothing pending. */
|
|
105
|
-
const
|
|
106
|
+
const PURGE_TIMEOUT_MS = 5_000;
|
|
106
107
|
/**
|
|
107
|
-
*
|
|
108
|
-
*
|
|
108
|
+
* The purge an edge in front takes: `POST {tags, paths, all}` as JSON to
|
|
109
|
+
* `CDN_PURGE_URL`, no token - the url is one reachable only from inside the
|
|
110
|
+
* app's own network.
|
|
109
111
|
* Split into calls of 100 tags and paths together. A tag or path too long for
|
|
110
112
|
* it is left out: one would cost the whole call, and the edge keeps no page
|
|
111
113
|
* with a tag it could not purge. Only a 202 is accepted. A 429 is tried once
|
|
112
114
|
* more after its `Retry-After` (at most five seconds); anything else is that
|
|
113
115
|
* call lost. The rest are still sent, then the purge rejects.
|
|
114
116
|
*/
|
|
115
|
-
export function
|
|
117
|
+
export function cdnPurge(options = {}) {
|
|
116
118
|
return async (what) => {
|
|
117
119
|
const url = options.url ?? purgeUrl();
|
|
118
120
|
if (!url)
|
|
119
|
-
throw new Error("
|
|
121
|
+
throw new Error("cdnPurge() has no url: CDN_PURGE_URL is not set.");
|
|
120
122
|
const send = options.fetch ?? fetch;
|
|
121
|
-
const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <=
|
|
122
|
-
const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <=
|
|
123
|
+
const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= PURGE_TAG_BYTES);
|
|
124
|
+
const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= PURGE_PATH_BYTES);
|
|
123
125
|
const bodies = [];
|
|
124
126
|
if (what.all)
|
|
125
127
|
bodies.push({ all: true });
|
|
126
128
|
while (tags.length > 0 || paths.length > 0) {
|
|
127
129
|
const body = {};
|
|
128
|
-
const someTags = tags.splice(0,
|
|
129
|
-
const somePaths = paths.splice(0,
|
|
130
|
+
const someTags = tags.splice(0, CDN_PURGE_LIMIT);
|
|
131
|
+
const somePaths = paths.splice(0, CDN_PURGE_LIMIT - someTags.length);
|
|
130
132
|
if (someTags.length > 0)
|
|
131
133
|
body.tags = someTags;
|
|
132
134
|
if (somePaths.length > 0)
|
|
@@ -151,7 +153,7 @@ async function post(send, url, body, retried = false) {
|
|
|
151
153
|
method: "POST",
|
|
152
154
|
headers: { "Content-Type": "application/json" },
|
|
153
155
|
body: JSON.stringify(body),
|
|
154
|
-
signal: AbortSignal.timeout(
|
|
156
|
+
signal: AbortSignal.timeout(PURGE_TIMEOUT_MS),
|
|
155
157
|
});
|
|
156
158
|
await response.body?.cancel();
|
|
157
159
|
if (response.status === 202)
|
|
@@ -161,6 +163,6 @@ async function post(send, url, body, retried = false) {
|
|
|
161
163
|
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
162
164
|
return post(send, url, body, true);
|
|
163
165
|
}
|
|
164
|
-
throw new Error(`
|
|
166
|
+
throw new Error(`The purge url answered ${response.status} to a purge of ${JSON.stringify(body)}.`);
|
|
165
167
|
}
|
|
166
168
|
//# sourceMappingURL=purge.js.map
|
package/dist/purge.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"purge.js","sourceRoot":"","sources":["../src/purge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAQH,SAAS,KAAK;IACZ,OAAO,CACH,UAAsC,CAAC,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,CAA4B,IAAI;QAClG,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;QAClD,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI;KACvB,CACF,CAAC;AACJ,CAAC;AAYD,4EAA4E;AAC5E,kEAAkE;AAClE,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;AAC5C,MAAM,OAAO,GAAG,UAAkE,CAAC;AAEnF,oFAAoF;AACpF,MAAM,UAAU,YAAY,CAAC,MAAqB;IAChD,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAC3B,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,cAAc;IAC5B,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAElC,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAE9C,MAAM,GAA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B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC","sourcesContent":["/**\n * Telling a CDN that kept pages changed.\n *\n * A `revalidate` page goes out with `Cache-Tag`, and a CDN that purges by tag\n * can drop it the moment one of those tags changes, rather than waiting out\n * its `max-age` in `CDN-Cache-Control`. What calls the purge is the app's: every CDN has its own API, so\n * the engine has one hook, `installPurge()`, and `changed(tag)` calls it with\n * the names that changed - after the answer has gone, through `after()`, so a\n * slow CDN never holds up the action that made the change.\n *\n * Homeport is the one installed for you: with `RSC_PURGE_URL` set (or Homeport's `HOMEPORT_PURGE_URL`), the\n * hook is `homeportPurge()` unless the app installed another.\n *\n * A Laravel or Go backend changes its names itself (`Rsc::changed()`,\n * `reg.Changed()`), and the engine never hears of it, so each backend\n * purges for its own changes. This hook covers `changed()` called here.\n */\n\n// Not imported: @rsc-kit/core/changed reaches this file and a client component\n// may import that, so request.ts - server-only - is found through the global\n// it sets when the server loads it. Without it, there is no request to wait\n// for, and a purge goes out at once.\ntype AfterHooks = { after: (work: () => unknown) => void; requestKey: () => object | null };\n\nfunction hooks(): AfterHooks {\n return (\n ((globalThis as Record<symbol, unknown>)[Symbol.for(\"rsc-kit.after\")] as AfterHooks | undefined) ?? {\n after: (work) => void Promise.resolve().then(work),\n requestKey: () => null,\n }\n );\n}\n\n/** What a purge drops: pages carrying any of these tags, pages at these paths, or everything. */\nexport interface Purge {\n tags?: readonly string[];\n paths?: readonly string[];\n all?: boolean;\n}\n\n/** Sends a purge to a CDN. A rejection is logged; it never fails the change. */\nexport type Purger = (purge: Purge) => Promise<void> | void;\n\n// On the global, like the cache store: an app installs through its own copy\n// of the package, and the engine's copy is the one that calls it.\nconst PURGER = Symbol.for(\"rsc-kit.purger\");\nconst globals = globalThis as unknown as Record<symbol, Purger | null | undefined>;\n\n/** Install the app's purge. `null` takes it out, and Homeport's default with it. */\nexport function installPurge(purger: Purger | null): void {\n globals[PURGER] = purger;\n}\n\n/** The purge in use: the app's, else Homeport's when its url is set, else none. */\nexport function installedPurge(): Purger | null {\n const installed = globals[PURGER];\n\n if (installed !== undefined) return installed;\n\n const url = purgeUrl();\n\n return url ? homeportPurge({ url }) : null;\n}\n\n/**\n * Where an edge in front of the app takes its purges: `RSC_PURGE_URL`, or\n * `HOMEPORT_PURGE_URL`, the name Homeport sets on the apps it runs - read so\n * those keep purging, not as the name to set.\n */\nexport function purgeUrl(): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n return env?.RSC_PURGE_URL || env?.HOMEPORT_PURGE_URL || undefined;\n}\n\n// The names an action changed go out as one purge when its answer has gone:\n// three changed() calls send one request, not three. Gathered per request,\n// so a request whose after() work never ran cannot hold back another's.\nconst pendingFor = new WeakMap<object, Set<string>>();\n\n/**\n * @internal For changed(): purge these tags once the answer has gone, or at\n * once outside a request. Does nothing when no purge is installed.\n */\nexport function purgeLater(tags: readonly string[]): void {\n if (tags.length === 0 || !installedPurge()) return;\n\n const { after, requestKey } = hooks();\n const key = requestKey();\n\n if (!key) {\n after(() => purge({ tags }));\n\n return;\n }\n\n let pending = pendingFor.get(key);\n\n if (pending) {\n for (const tag of tags) pending.add(tag);\n\n return;\n }\n\n pending = new Set(tags);\n pendingFor.set(key, pending);\n\n const gathered = pending;\n\n after(() => {\n pendingFor.delete(key);\n\n return purge({ tags: [...gathered] });\n });\n}\n\n/**\n * Send a purge now, through the installed purge. For an app's own use - a\n * deploy step, a webhook - as well as changed()'s. Never throws: the change\n * it follows is already made, and a CDN that missed it still drops the copy\n * at its `max-age` in `CDN-Cache-Control`. A failure is logged.\n */\nexport async function purge(what: Purge): Promise<void> {\n const purger = installedPurge();\n\n if (!purger) return;\n\n try {\n await purger(what);\n } catch (error) {\n console.warn(\n \"[rsc-kit] purging the CDN failed; its copy is dropped at CDN-Cache-Control's max-age instead: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/** Homeport takes at most this many tags and paths, together, per call. */\nexport const HOMEPORT_PURGE_LIMIT = 100;\n\n/** The longest tag and path Homeport takes, in bytes. */\nconst HOMEPORT_TAG_BYTES = 1024;\nconst HOMEPORT_PATH_BYTES = 2048;\n\nconst bytes = new TextEncoder();\n\n/** How long one call may take, so a purge url that hangs leaves nothing pending. */\nconst HOMEPORT_TIMEOUT_MS = 5_000;\n\nexport interface HomeportPurgeOptions {\n /** Where to post. Default `RSC_PURGE_URL`, or the `HOMEPORT_PURGE_URL` Homeport sets. */\n url?: string;\n /** For tests. */\n fetch?: typeof fetch;\n}\n\n/**\n * Homeport's purge: `POST {tags, paths, all}` to the url Homeport gives the\n * app, no token - it is reachable only from inside the app's own network.\n * Split into calls of 100 tags and paths together. A tag or path too long for\n * it is left out: one would cost the whole call, and the edge keeps no page\n * with a tag it could not purge. Only a 202 is accepted. A 429 is tried once\n * more after its `Retry-After` (at most five seconds); anything else is that\n * call lost. The rest are still sent, then the purge rejects.\n */\nexport function homeportPurge(options: HomeportPurgeOptions = {}): Purger {\n return async (what) => {\n const url = options.url ?? purgeUrl();\n\n if (!url) throw new Error(\"homeportPurge() has no url: RSC_PURGE_URL is not set.\");\n\n const send = options.fetch ?? fetch;\n const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= HOMEPORT_TAG_BYTES);\n const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= HOMEPORT_PATH_BYTES);\n const bodies: Purge[] = [];\n\n if (what.all) bodies.push({ all: true });\n\n while (tags.length > 0 || paths.length > 0) {\n const body: Purge = {};\n const someTags = tags.splice(0, HOMEPORT_PURGE_LIMIT);\n const somePaths = paths.splice(0, HOMEPORT_PURGE_LIMIT - someTags.length);\n\n if (someTags.length > 0) body.tags = someTags;\n if (somePaths.length > 0) body.paths = somePaths;\n bodies.push(body);\n }\n\n const failed: string[] = [];\n\n for (const body of bodies) {\n try {\n await post(send, url, body);\n } catch (error) {\n failed.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (failed.length > 0) throw new Error(failed.join(\" \"));\n };\n}\n\nasync function post(send: typeof fetch, url: string, body: Purge, retried = false): Promise<void> {\n const response = await send(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(HOMEPORT_TIMEOUT_MS),\n });\n\n await response.body?.cancel();\n\n if (response.status === 202) return;\n\n if (response.status === 429 && !retried) {\n const seconds = Math.min(Number(response.headers.get(\"Retry-After\")) || 1, 5);\n\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000));\n\n return post(send, url, body, true);\n }\n\n throw new Error(`Homeport answered ${response.status} to a purge of ${JSON.stringify(body)}.`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"purge.js","sourceRoot":"","sources":["../src/purge.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAQH,SAAS,KAAK;IACZ,OAAO,CACH,UAAsC,CAAC,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,CAA4B,IAAI;QAClG,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;QAClD,UAAU,EAAE,GAAG,EAAE,CAAC,IAAI;KACvB,CACF,CAAC;AACJ,CAAC;AAYD,4EAA4E;AAC5E,kEAAkE;AAClE,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;AAC5C,MAAM,OAAO,GAAG,UAAkE,CAAC;AAEnF,6EAA6E;AAC7E,MAAM,UAAU,YAAY,CAAC,MAAqB;IAChD,OAAO,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;AAC3B,CAAC;AAED,2FAA2F;AAC3F,MAAM,UAAU,cAAc;IAC5B,MAAM,SAAS,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAElC,IAAI,SAAS,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAE9C,MAAM,GAAG,GAAG,QAAQ,EAAE,CAAC;IAE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AAC","sourcesContent":["/**\n * Telling a CDN that kept pages changed.\n *\n * A `revalidate` page goes out with `Cache-Tag`, and a CDN that purges by tag\n * can drop it the moment one of those tags changes, rather than waiting out\n * its `max-age` in `CDN-Cache-Control`. What calls the purge is the app's: every CDN has its own API, so\n * the engine has one hook, `installPurge()`, and `changed(tag)` calls it with\n * the names that changed - after the answer has gone, through `after()`, so a\n * slow CDN never holds up the action that made the change.\n *\n * One is installed for you: with `CDN_PURGE_URL` set, the\n * hook is `cdnPurge()` unless the app installed another.\n *\n * A Laravel or Go backend changes its names itself (`Rsc::changed()`,\n * `reg.Changed()`), and the engine never hears of it, so each backend\n * purges for its own changes. This hook covers `changed()` called here.\n */\n\n// Not imported: @rsc-kit/core/changed reaches this file and a client component\n// may import that, so request.ts - server-only - is found through the global\n// it sets when the server loads it. Without it, there is no request to wait\n// for, and a purge goes out at once.\ntype AfterHooks = { after: (work: () => unknown) => void; requestKey: () => object | null };\n\nfunction hooks(): AfterHooks {\n return (\n ((globalThis as Record<symbol, unknown>)[Symbol.for(\"rsc-kit.after\")] as AfterHooks | undefined) ?? {\n after: (work) => void Promise.resolve().then(work),\n requestKey: () => null,\n }\n );\n}\n\n/** What a purge drops: pages carrying any of these tags, pages at these paths, or everything. */\nexport interface Purge {\n tags?: readonly string[];\n paths?: readonly string[];\n all?: boolean;\n}\n\n/** Sends a purge to a CDN. A rejection is logged; it never fails the change. */\nexport type Purger = (purge: Purge) => Promise<void> | void;\n\n// On the global, like the cache store: an app installs through its own copy\n// of the package, and the engine's copy is the one that calls it.\nconst PURGER = Symbol.for(\"rsc-kit.purger\");\nconst globals = globalThis as unknown as Record<symbol, Purger | null | undefined>;\n\n/** Install the app's purge. `null` takes it out, and the default with it. */\nexport function installPurge(purger: Purger | null): void {\n globals[PURGER] = purger;\n}\n\n/** The purge in use: the app's, else cdnPurge() when `CDN_PURGE_URL` is set, else none. */\nexport function installedPurge(): Purger | null {\n const installed = globals[PURGER];\n\n if (installed !== undefined) return installed;\n\n const url = purgeUrl();\n\n return url ? cdnPurge({ url }) : null;\n}\n\n/**\n * Where an edge in front of the app takes its purges: `CDN_PURGE_URL`, the\n * one name. It belongs to neither side: a platform sets it with nothing of\n * this engine's in its code, and this reads it with nothing of a platform's.\n * `RSC_PURGE_URL` and `HOMEPORT_PURGE_URL` were read before, and are not.\n */\nexport function purgeUrl(): string | undefined {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;\n\n return env?.CDN_PURGE_URL || undefined;\n}\n\n// The names an action changed go out as one purge when its answer has gone:\n// three changed() calls send one request, not three. Gathered per request,\n// so a request whose after() work never ran cannot hold back another's.\nconst pendingFor = new WeakMap<object, Set<string>>();\n\n/**\n * @internal For changed(): purge these tags once the answer has gone, or at\n * once outside a request. Does nothing when no purge is installed.\n */\nexport function purgeLater(tags: readonly string[]): void {\n if (tags.length === 0 || !installedPurge()) return;\n\n const { after, requestKey } = hooks();\n const key = requestKey();\n\n if (!key) {\n after(() => purge({ tags }));\n\n return;\n }\n\n let pending = pendingFor.get(key);\n\n if (pending) {\n for (const tag of tags) pending.add(tag);\n\n return;\n }\n\n pending = new Set(tags);\n pendingFor.set(key, pending);\n\n const gathered = pending;\n\n after(() => {\n pendingFor.delete(key);\n\n return purge({ tags: [...gathered] });\n });\n}\n\n/**\n * Send a purge now, through the installed purge. For an app's own use - a\n * deploy step, a webhook - as well as changed()'s. Never throws: the change\n * it follows is already made, and a CDN that missed it still drops the copy\n * at its `max-age` in `CDN-Cache-Control`. A failure is logged.\n */\nexport async function purge(what: Purge): Promise<void> {\n const purger = installedPurge();\n\n if (!purger) return;\n\n try {\n await purger(what);\n } catch (error) {\n console.warn(\n \"[rsc-kit] purging the CDN failed; its copy is dropped at CDN-Cache-Control's max-age instead: \" +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\n/** At most this many tags and paths, together, per call. */\nexport const CDN_PURGE_LIMIT = 100;\n\n/** The longest tag and path sent, in bytes. */\nconst PURGE_TAG_BYTES = 1024;\nconst PURGE_PATH_BYTES = 2048;\n\nconst bytes = new TextEncoder();\n\n/** How long one call may take, so a purge url that hangs leaves nothing pending. */\nconst PURGE_TIMEOUT_MS = 5_000;\n\nexport interface CdnPurgeOptions {\n /** Where to post. Default `CDN_PURGE_URL`. */\n url?: string;\n /** For tests. */\n fetch?: typeof fetch;\n}\n\n/**\n * The purge an edge in front takes: `POST {tags, paths, all}` as JSON to\n * `CDN_PURGE_URL`, no token - the url is one reachable only from inside the\n * app's own network.\n * Split into calls of 100 tags and paths together. A tag or path too long for\n * it is left out: one would cost the whole call, and the edge keeps no page\n * with a tag it could not purge. Only a 202 is accepted. A 429 is tried once\n * more after its `Retry-After` (at most five seconds); anything else is that\n * call lost. The rest are still sent, then the purge rejects.\n */\nexport function cdnPurge(options: CdnPurgeOptions = {}): Purger {\n return async (what) => {\n const url = options.url ?? purgeUrl();\n\n if (!url) throw new Error(\"cdnPurge() has no url: CDN_PURGE_URL is not set.\");\n\n const send = options.fetch ?? fetch;\n const tags = (what.tags ?? []).filter((tag) => bytes.encode(tag).length <= PURGE_TAG_BYTES);\n const paths = (what.paths ?? []).filter((path) => bytes.encode(path).length <= PURGE_PATH_BYTES);\n const bodies: Purge[] = [];\n\n if (what.all) bodies.push({ all: true });\n\n while (tags.length > 0 || paths.length > 0) {\n const body: Purge = {};\n const someTags = tags.splice(0, CDN_PURGE_LIMIT);\n const somePaths = paths.splice(0, CDN_PURGE_LIMIT - someTags.length);\n\n if (someTags.length > 0) body.tags = someTags;\n if (somePaths.length > 0) body.paths = somePaths;\n bodies.push(body);\n }\n\n const failed: string[] = [];\n\n for (const body of bodies) {\n try {\n await post(send, url, body);\n } catch (error) {\n failed.push(error instanceof Error ? error.message : String(error));\n }\n }\n\n if (failed.length > 0) throw new Error(failed.join(\" \"));\n };\n}\n\nasync function post(send: typeof fetch, url: string, body: Purge, retried = false): Promise<void> {\n const response = await send(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(PURGE_TIMEOUT_MS),\n });\n\n await response.body?.cancel();\n\n if (response.status === 202) return;\n\n if (response.status === 429 && !retried) {\n const seconds = Math.min(Number(response.headers.get(\"Retry-After\")) || 1, 5);\n\n await new Promise((resolve) => setTimeout(resolve, seconds * 1000));\n\n return post(send, url, body, true);\n }\n\n throw new Error(`The purge url answered ${response.status} to a purge of ${JSON.stringify(body)}.`);\n}\n"]}
|
package/dist/routes.d.ts
CHANGED
|
@@ -207,6 +207,12 @@ export declare function withSearch(path: string, search: object | undefined): st
|
|
|
207
207
|
* `prefetch`, `redirect` and anything else that wants the finished string.
|
|
208
208
|
*/
|
|
209
209
|
export declare function href<H extends Route>(path: H, ...rest: {} extends SearchFor<H> ? [search?: SearchFor<H>] : [search: SearchFor<H>]): Route;
|
|
210
|
+
/**
|
|
211
|
+
* Internal: where Link, visit() and the router send a root-relative href once
|
|
212
|
+
* rscKit({ subdomains }) names directories served on their own host - see
|
|
213
|
+
* subdomainHref. `current` is the browser's host, where it is known.
|
|
214
|
+
*/
|
|
215
|
+
export declare function placeHref(href: string, current?: string | null): string;
|
|
210
216
|
/** A top-level folder a url can begin with: `merchant` for app/merchant. */
|
|
211
217
|
type TopFolder<P> = P extends `/${infer F}/${string}` ? F extends `[${string}` ? never : F : P extends `/${infer F}` ? F extends `[${string}` | "" ? never : F : never;
|
|
212
218
|
/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */
|
package/dist/routes.js
CHANGED
|
@@ -24,6 +24,7 @@
|
|
|
24
24
|
// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly
|
|
25
25
|
// as permissive as it was before. That fallback is the reason this can ship
|
|
26
26
|
// without a flag.
|
|
27
|
+
import { subdomainHref } from "./hostRouting.js";
|
|
27
28
|
/**
|
|
28
29
|
* An api url, checked against the routes the build found.
|
|
29
30
|
*
|
|
@@ -80,6 +81,17 @@ export function withSearch(path, search) {
|
|
|
80
81
|
export function href(path, ...rest) {
|
|
81
82
|
return withSearch(path, rest[0]);
|
|
82
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* Internal: where Link, visit() and the router send a root-relative href once
|
|
86
|
+
* rscKit({ subdomains }) names directories served on their own host - see
|
|
87
|
+
* subdomainHref. `current` is the browser's host, where it is known.
|
|
88
|
+
*/
|
|
89
|
+
export function placeHref(href, current) {
|
|
90
|
+
const labels = typeof __RSC_SUBDOMAINS__ === "object" && __RSC_SUBDOMAINS__ ? __RSC_SUBDOMAINS__ : [];
|
|
91
|
+
if (labels.length === 0)
|
|
92
|
+
return href;
|
|
93
|
+
return subdomainHref(href, labels, typeof __RSC_SITE_HOST__ === "string" ? __RSC_SITE_HOST__ : null, current);
|
|
94
|
+
}
|
|
83
95
|
export function hostUrl(name, path) {
|
|
84
96
|
const site = typeof __RSC_SITE_HOST__ === "string" ? __RSC_SITE_HOST__ : null;
|
|
85
97
|
if (path === undefined)
|
package/dist/routes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,kBAAkB;AAsJlB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,MAAM,CAAC,IAAc;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAwLD,uGAAuG;AACvG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,MAAM,MAAM,GAAG,IAAI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I,GAAG,IAAI,EAAW,CAAC;IAErD,OAAO,IAAI,IAAI,GAAG,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAW,CAAC;AACzH,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n\n// ── Another host ─────────────────────────────────────────────────────────────\n//\n// A page under app/merchant is reached as merchant.example.com/orders as well\n// as example.com/merchant/orders, and a page under app/[domain] only from the\n// tenant's own host. A typed `href` names the folder path, which is the second\n// of those - and the first is a host Link cannot know you meant. So the host is\n// said where it is meant, and the path is typed for it.\n\n/** The site's host, from rscKit({ hosts }) or a literal metadataBase, baked in by the build. */\ndeclare const __RSC_SITE_HOST__: string | null | undefined;\n\n/** A top-level folder a url can begin with: `merchant` for app/merchant. */\ntype TopFolder<P> = P extends `/${infer F}/${string}`\n ? F extends `[${string}` ? never : F\n : P extends `/${infer F}`\n ? F extends `[${string}` | \"\" ? never : F\n : never;\n\n/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */\ntype Under<P, F extends string> = P extends `/${F}`\n ? \"/\"\n : P extends `/${F}/${infer R}`\n ? `/${R}`\n : never;\n\n/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */\ntype TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}`\n ? R extends \"\" ? \"/\" : R\n : never;\n\ntype WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;\n\n/**\n * What `hostUrl`'s first argument autocompletes to: every top-level folder.\n * Any other string is taken too - a tenant's subdomain, a custom domain.\n */\nexport type HostName = Unregistered extends true ? string : HostFolder | `/${HostFolder}` | (string & {});\n\n/** The top-level folders of the route tree: `merchant` for app/merchant. */\nexport type HostFolder = TopFolder<RoutePattern>;\n\n/**\n * The paths a host answers: for a folder's subdomain the pages under that\n * folder; for anything else the tenant tree's, or any path when there is none.\n */\nexport type HostPath<H extends string> = Unregistered extends true\n ? string\n : H extends HostFolder | `/${HostFolder}`\n ? WithQuery<Filled<Under<RoutePattern, H extends `/${infer F}` ? F : H>>>\n : [TenantPaths<RoutePattern>] extends [never]\n ? `/${string}`\n : WithQuery<Filled<TenantPaths<RoutePattern>>>;\n\n/**\n * A url on another host of the site, for `<Link href>`, `visit()` and\n * `redirect()`:\n *\n * hostUrl('merchant', '/orders') // //merchant.example.com/orders\n * hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant\n * hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain\n * hostUrl('/pricing') // //example.com/pricing - the site itself\n *\n * The folder may be written as its path too: `hostUrl('/merchant', '/orders')`.\n *\n * The site's host is the one rscKit({ hosts }) names first. Where none is\n * named, a folder's url is its path - `/merchant/orders` - as every page is\n * then reached by path; a tenant or a domain still names its host.\n *\n * The same string on the server and in the browser, so a link hydrates as\n * it rendered. On the host it names already, Link navigates without a reload.\n */\nexport function hostUrl(path: Route): Route;\nexport function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;\nexport function hostUrl(name: string, path?: string): Route {\n const site = typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null;\n\n if (path === undefined) return (site ? `//${site}${name}` : name) as Route;\n\n // '/merchant' is the folder too: the first argument's suggestions include\n // the site's paths, for the one-argument form, and that is the one picked.\n const host = name.startsWith(\"/\") ? name.slice(1) : name;\n\n if (host.includes(\".\")) return `//${host}${path}` as Route;\n if (site) return `//${host}.${site}${path}` as Route;\n\n return `/${host}${path === \"/\" ? \"\" : path.startsWith(\"/?\") || path.startsWith(\"/#\") ? path.slice(1) : path}` as Route;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,4EAA4E;AAC5E,kBAAkB;AAElB,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAsJjD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,MAAM,CAAC,IAAc;IACnC,OAAO,IAAI,CAAC;AACd,CAAC;AAwLD,uGAAuG;AACvG,MAAM,UAAU,YAAY,CAAC,MAAc;IACzC,MAAM,MAAM,GAAG,IAAI,eAAe,EAAE,CAAC;IAErC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;QAClD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QAEpD,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,KAAK,MAAM,IAAI,IAAI,KAAK;gBAAE,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;QAC7D,CAAC;aAAM,CAAC;YACN,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAA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I,GAAG,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAW,CAAC;AACzH,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\nimport { subdomainHref } from \"./hostRouting.js\";\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n\n// ── Another host ─────────────────────────────────────────────────────────────\n//\n// A page under app/merchant is reached as merchant.example.com/orders as well\n// as example.com/merchant/orders, and a page under app/[domain] only from the\n// tenant's own host. A typed `href` names the folder path, which is the second\n// of those - and the first is a host Link cannot know you meant. So the host is\n// said where it is meant, and the path is typed for it.\n\n/** The site's host, from rscKit({ hosts }) or a literal metadataBase, baked in by the build. */\ndeclare const __RSC_SITE_HOST__: string | null | undefined;\n/** rscKit({ subdomains }), baked in by the build. */\ndeclare const __RSC_SUBDOMAINS__: readonly string[] | undefined;\n\n/**\n * Internal: where Link, visit() and the router send a root-relative href once\n * rscKit({ subdomains }) names directories served on their own host - see\n * subdomainHref. `current` is the browser's host, where it is known.\n */\nexport function placeHref(href: string, current?: string | null): string {\n const labels = typeof __RSC_SUBDOMAINS__ === \"object\" && __RSC_SUBDOMAINS__ ? __RSC_SUBDOMAINS__ : [];\n\n if (labels.length === 0) return href;\n\n return subdomainHref(href, labels, typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null, current);\n}\n\n/** A top-level folder a url can begin with: `merchant` for app/merchant. */\ntype TopFolder<P> = P extends `/${infer F}/${string}`\n ? F extends `[${string}` ? never : F\n : P extends `/${infer F}`\n ? F extends `[${string}` | \"\" ? never : F\n : never;\n\n/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */\ntype Under<P, F extends string> = P extends `/${F}`\n ? \"/\"\n : P extends `/${F}/${infer R}`\n ? `/${R}`\n : never;\n\n/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */\ntype TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}`\n ? R extends \"\" ? \"/\" : R\n : never;\n\ntype WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;\n\n/**\n * What `hostUrl`'s first argument autocompletes to: every top-level folder.\n * Any other string is taken too - a tenant's subdomain, a custom domain.\n */\nexport type HostName = Unregistered extends true ? string : HostFolder | `/${HostFolder}` | (string & {});\n\n/** The top-level folders of the route tree: `merchant` for app/merchant. */\nexport type HostFolder = TopFolder<RoutePattern>;\n\n/**\n * The paths a host answers: for a folder's subdomain the pages under that\n * folder; for anything else the tenant tree's, or any path when there is none.\n */\nexport type HostPath<H extends string> = Unregistered extends true\n ? string\n : H extends HostFolder | `/${HostFolder}`\n ? WithQuery<Filled<Under<RoutePattern, H extends `/${infer F}` ? F : H>>>\n : [TenantPaths<RoutePattern>] extends [never]\n ? `/${string}`\n : WithQuery<Filled<TenantPaths<RoutePattern>>>;\n\n/**\n * A url on another host of the site, for `<Link href>`, `visit()` and\n * `redirect()`:\n *\n * hostUrl('merchant', '/orders') // //merchant.example.com/orders\n * hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant\n * hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain\n * hostUrl('/pricing') // //example.com/pricing - the site itself\n *\n * The folder may be written as its path too: `hostUrl('/merchant', '/orders')`.\n *\n * The site's host is the one rscKit({ hosts }) names first. Where none is\n * named, a folder's url is its path - `/merchant/orders` - as every page is\n * then reached by path; a tenant or a domain still names its host.\n *\n * The same string on the server and in the browser, so a link hydrates as\n * it rendered. On the host it names already, Link navigates without a reload.\n */\nexport function hostUrl(path: Route): Route;\nexport function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;\nexport function hostUrl(name: string, path?: string): Route {\n const site = typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null;\n\n if (path === undefined) return (site ? `//${site}${name}` : name) as Route;\n\n // '/merchant' is the folder too: the first argument's suggestions include\n // the site's paths, for the one-argument form, and that is the one picked.\n const host = name.startsWith(\"/\") ? name.slice(1) : name;\n\n if (host.includes(\".\")) return `//${host}${path}` as Route;\n if (site) return `//${host}.${site}${path}` as Route;\n\n return `/${host}${path === \"/\" ? \"\" : path.startsWith(\"/?\") || path.startsWith(\"/#\") ? path.slice(1) : path}` as Route;\n}\n"]}
|
package/dist/vite.d.ts
CHANGED
|
@@ -240,8 +240,26 @@ export interface RscKitOptions {
|
|
|
240
240
|
* under it, never `/authors` - and every method goes, a POST as a GET. A
|
|
241
241
|
* team called `auth` is then unreachable, which is the price of the name.
|
|
242
242
|
* Without a backend where this runs, such a url is this app's not-found page.
|
|
243
|
+
*
|
|
244
|
+
* A whole segment in brackets is any one segment: `/login/[provider]` is
|
|
245
|
+
* `/login/google` and what is under it, and not `/login` itself. Not the
|
|
246
|
+
* first segment, and a page it would cover stops dev and the build.
|
|
243
247
|
*/
|
|
244
248
|
backendPaths?: string[];
|
|
249
|
+
/**
|
|
250
|
+
* Top-level directories served on their own subdomain, and only there:
|
|
251
|
+
* `['merchant']` puts `app/merchant/orders/page.tsx` on
|
|
252
|
+
* `merchant.example.com/orders`.
|
|
253
|
+
*
|
|
254
|
+
* A subdomain is routed without being named here - `merchant.example.com`
|
|
255
|
+
* reaches app/merchant either way. Naming it makes that url the page's
|
|
256
|
+
* only one: `example.com/merchant/orders` answers 301 to it, a `Link`,
|
|
257
|
+
* `visit()` or `redirect()` to `/merchant/orders` goes there, a root path
|
|
258
|
+
* written on the subdomain goes back to the site, and the build's route
|
|
259
|
+
* table says so for a backend that names routes (Laravel's `route()`).
|
|
260
|
+
* Needs the site's host (`hosts`), and a directory of that name.
|
|
261
|
+
*/
|
|
262
|
+
subdomains?: string[];
|
|
245
263
|
/**
|
|
246
264
|
* This package's directory, holding the client runtime the browser entry
|
|
247
265
|
* imports. Vite stages configs through node_modules/.vite-temp, so
|
|
@@ -376,6 +394,40 @@ export declare function normaliseBackendPaths(paths: readonly string[] | undefin
|
|
|
376
394
|
* prefetch, wherever the router meets one: a click, a redirect, a hover.
|
|
377
395
|
*/
|
|
378
396
|
export declare function backendPatterns(paths: readonly string[]): string[];
|
|
397
|
+
/**
|
|
398
|
+
* The ones that are plain prefixes, which is what a proxy in front reads from
|
|
399
|
+
* routes.json and the build report: "a path equal to one or under it". One
|
|
400
|
+
* with a dynamic segment is left out of that list rather than changing what
|
|
401
|
+
* the list means - the proxy hands the url on like any other, and the
|
|
402
|
+
* renderer, which reads them all, forwards it.
|
|
403
|
+
*/
|
|
404
|
+
export declare function backendPrefixes(paths: readonly string[]): string[];
|
|
405
|
+
/** A backend path as the source of a RegExp: the prefix, at a segment boundary. */
|
|
406
|
+
export declare function backendPathSource(path: string): string;
|
|
407
|
+
/**
|
|
408
|
+
* A page a dynamic backend path would take.
|
|
409
|
+
*
|
|
410
|
+
* A named prefix wins over every page, without asking one - that is what it
|
|
411
|
+
* is for, and why it costs a request nothing. With a dynamic segment the
|
|
412
|
+
* prefix can cover a page nobody meant it to: '/login/[provider]' is
|
|
413
|
+
* /login/forgot too. Said once, where the app starts, rather than checked on
|
|
414
|
+
* every request: the page would simply never render.
|
|
415
|
+
*/
|
|
416
|
+
/** rscKit({ subdomains }), checked: labels a host can have, without a slash, once each. */
|
|
417
|
+
export declare function normaliseSubdomains(labels: unknown): string[];
|
|
418
|
+
/**
|
|
419
|
+
* Why rscKit({ subdomains }) cannot be honoured, or null: a subdomain needs a
|
|
420
|
+
* site to be a subdomain of, and a directory to serve. Without either it
|
|
421
|
+
* would redirect visitors to a host that answers nothing.
|
|
422
|
+
*/
|
|
423
|
+
export declare function subdomainProblem(routes: {
|
|
424
|
+
component: string;
|
|
425
|
+
segments: RouteSegment[];
|
|
426
|
+
}[], labels: readonly string[], hasSiteHost: boolean): string | null;
|
|
427
|
+
export declare function pageUnderBackendPath(routes: {
|
|
428
|
+
component: string;
|
|
429
|
+
segments: RouteSegment[];
|
|
430
|
+
}[], paths: readonly string[]): string | null;
|
|
379
431
|
/**
|
|
380
432
|
* The service worker, written into the client output at build time.
|
|
381
433
|
*
|