@rsc-kit/core 0.43.1 → 0.45.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.
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { useCallback, useLayoutEffect, useRef, useState, useTransition } from "react";
3
- import { ServerValidationError } from "./errors.js";
3
+ import { ServerValidationError, closeAnswer, isRedirected, openAnswer, redirectedBack } from "./errors.js";
4
4
  /**
5
5
  * Call an action from a button rather than a form.
6
6
  *
@@ -22,7 +22,8 @@ import { ServerValidationError } from "./errors.js";
22
22
  * though the write had worked.
23
23
  *
24
24
  * An action that redirected settles nothing: no callback runs and no state is
25
- * set, because the page is on its way somewhere else.
25
+ * set, because the page is on its way somewhere else. A redirect back to the
26
+ * page it was called from - Laravel's back() - is a success like any other.
26
27
  */
27
28
  export function useAction(action, options = {}) {
28
29
  const [isPending, startTransition] = useTransition();
@@ -38,9 +39,19 @@ export function useAction(action, options = {}) {
38
39
  const run = useCallback(async (args) => {
39
40
  const { action, options } = latest.current;
40
41
  options.optimistic?.(...args);
42
+ const from = window.location.pathname + window.location.search;
41
43
  let next;
42
44
  try {
43
- next = (await action(...args));
45
+ // Open only for the call itself: React reaches the transport
46
+ // synchronously, so nothing else can take it - see openAnswer().
47
+ const answer = openAnswer();
48
+ const pending = action(...args);
49
+ closeAnswer();
50
+ const value = await pending;
51
+ // A stub's value is its data, and so is anything that is not an
52
+ // object - a void stub resolves with null. Refusals reject, below.
53
+ const data = answer.plain || typeof value !== "object" || value === null;
54
+ next = (data && !isRedirected(value) ? { data: value } : value);
44
55
  }
45
56
  catch (error) {
46
57
  // A generated stub rejects when its input is refused, and a form or a
@@ -50,7 +61,9 @@ export function useAction(action, options = {}) {
50
61
  ? { validationErrors: error.errors }
51
62
  : { serverError: error instanceof Error ? error.message : String(error) };
52
63
  }
53
- if (next.redirected !== undefined)
64
+ // Gone elsewhere, nothing to settle - but back() to this page is the
65
+ // action succeeding, and the page it re-rendered is still this one.
66
+ if (next.redirected !== undefined && !redirectedBack(next.redirected, from))
54
67
  return next;
55
68
  setResult(next);
56
69
  setSettled(next.serverError !== undefined || next.validationErrors ? "hasErrored" : "hasSucceeded");
@@ -1 +1 @@
1
- {"version":3,"file":"useAction.js","sourceRoot":"","sources":["../../src/js/useAction.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAEtF,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAmCpD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,SAAS,CAAsB,MAAS,EAAE,OAAO,GAAwB,EAAE;IAGzF,MAAM,CAAC,SAAS,EAAE,eAAe,CAAC,GAAG,aAAa,EAAE,CAAC;IACrD,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAS,EAAE,CAAC,CAAC;IACjD,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAuC,IAAI,CAAC,CAAC;IAEnF,0EAA0E;IAC1E,2EAA2E;IAC3E,6DAA6D;IAC7D,MAAM,MAAM,GAAG,MAAM,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;IAE3C,eAAe,CAAC,GAAG,EAAE;QACnB,MAAM,CAAC,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;IACvC,CAAC,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,WAAW,CAAC,KAAK,EAAE,IAAmB,EAAmB,EAAE;QACrE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC;QAE3C,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAE9B,IAAI,IAAY,CAAC;QAEjB,IAAI,CAAC;YACH,IAAI,GAAG,CAAC,MAAM,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AAmB,EAAmB,EAAE,CAC1C,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QACtB,eAAe,CAAC,KAAK,IAAI,EAAE;YACzB,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,EACJ,CAAC,GAAG,CAAC,CACN,CAAC;IAEF,MAAM,OAAO,GAAG,WAAW,CACzB,CAAC,GAAG,IAAmB,EAAQ,EAAE;QAC/B,KAAK,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7B,CAAC,EACD,CAAC,YAAY,CAAC,CACf,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,SAAS,CAAC,EAAE,CAAC,CAAC;QACd,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,MAAM,GAAoB,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC;IAE9E,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AACrE,CAAC;AAED,eAAe,SAAS,CAAC","sourcesContent":["\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState, useTransition } from \"react\";\nimport type { ActionResult } from \"../action.js\";\nimport { ServerValidationError } from \"./errors.js\";\n\n// Any built action: createActionClient's handler(), with or without a schema.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyAction = (...args: any[]) => Promise<ActionResult<any, any>>;\n\ntype DataOf<A extends AnyAction> = Awaited<ReturnType<A>> extends ActionResult<infer D, any> ? D : never;\n\ntype RefusalOf<A extends AnyAction> = Awaited<ReturnType<A>> extends ActionResult<any, infer R> ? R : never;\n\n/** The whole result, refusal type included - see `.refusal(schema)`. */\ntype ResultOf<A extends AnyAction> = ActionResult<DataOf<A>, RefusalOf<A>>;\n\nexport type UseActionStatus = \"idle\" | \"executing\" | \"hasSucceeded\" | \"hasErrored\";\n\nexport interface UseActionOptions<A extends AnyAction> {\n /**\n * Called inside the action's transition, before the action runs, with what\n * it was called with - where React's `useOptimistic` setter goes. React\n * puts the optimistic state back when the transition ends, so a failed\n * action takes its change back on its own.\n */\n optimistic?: (...args: Parameters<A>) => void;\n /** The action answered with data: no serverError, no validationErrors. */\n onSuccess?: (data: DataOf<A>) => void;\n /**\n * The action refused or failed. With a serverError, that message; with\n * validationErrors, the first one - so a button with no field beside it\n * still has something to show.\n */\n onError?: (message: string, result: ResultOf<A>) => void;\n /** After either, for state that tracks the call rather than its outcome. */\n onSettled?: (result: ResultOf<A>) => void;\n}\n\n/**\n * Call an action from a button rather than a form.\n *\n * const { execute, isPending } = useAction(archivePost, {\n * optimistic: (input) => hide(input.id),\n * onError: (message) => toast.error(message),\n * })\n *\n * <button disabled={isPending} onClick={() => execute({ id })}>Archive</button>\n *\n * The action's own types carry through: `execute` takes what the action's\n * schema takes, and `onSuccess` is handed what its handler returns. A form does\n * not need this - <Form> reads the same result on its own.\n *\n * Neither `execute` nor `executeAsync` throws. An action built on the action\n * client returns its failures, and anything thrown on the way - the network,\n * a server that answered with a page - becomes a serverError: left thrown,\n * the transition never settled and an optimistic change stayed on screen as\n * though the write had worked.\n *\n * An action that redirected settles nothing: no callback runs and no state is\n * set, because the page is on its way somewhere else.\n */\nexport function useAction<A extends AnyAction>(action: A, options: UseActionOptions<A> = {}) {\n type Result = ResultOf<A>;\n\n const [isPending, startTransition] = useTransition();\n const [result, setResult] = useState<Result>({});\n const [settled, setSettled] = useState<\"hasSucceeded\" | \"hasErrored\" | null>(null);\n\n // Read when the action runs, not when execute was made: execute keeps one\n // identity across renders, so an onClick built on it is not rebuilt, and a\n // callback closing over newer state is still the one called.\n const latest = useRef({ action, options });\n\n useLayoutEffect(() => {\n latest.current = { action, options };\n });\n\n const run = useCallback(async (args: Parameters<A>): Promise<Result> => {\n const { action, options } = latest.current;\n\n options.optimistic?.(...args);\n\n let next: Result;\n\n try {\n next = (await action(...args)) as Result;\n } catch (error) {\n // A generated stub rejects when its input is refused, and a form or a\n // button reads that as it reads the result of an action built on the client.\n next =\n error instanceof ServerValidationError\n ? { validationErrors: error.errors }\n : { serverError: error instanceof Error ? error.message : String(error) };\n }\n\n if (next.redirected !== undefined) return next;\n\n setResult(next);\n setSettled(next.serverError !== undefined || next.validationErrors ? \"hasErrored\" : \"hasSucceeded\");\n\n if (next.serverError !== undefined) {\n options.onError?.(next.serverError, next);\n } else if (next.validationErrors) {\n options.onError?.(Object.values(next.validationErrors).flat()[0] ?? \"Invalid input.\", next);\n } else {\n options.onSuccess?.(next.data as DataOf<A>);\n }\n\n options.onSettled?.(next);\n\n return next;\n }, []);\n\n const executeAsync = useCallback(\n (...args: Parameters<A>): Promise<Result> =>\n new Promise((resolve) => {\n startTransition(async () => {\n resolve(await run(args));\n });\n }),\n [run],\n );\n\n const execute = useCallback(\n (...args: Parameters<A>): void => {\n void executeAsync(...args);\n },\n [executeAsync],\n );\n\n const reset = useCallback(() => {\n setResult({});\n setSettled(null);\n }, []);\n\n const status: UseActionStatus = isPending ? \"executing\" : (settled ?? \"idle\");\n\n return { execute, executeAsync, isPending, status, result, reset };\n}\n\nexport default useAction;\n"]}
1
+ {"version":3,"file":"useAction.js","sourceRoot":"","sources":["../../src/js/useAction.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAEtF,OAAO,EAAmB,qBAAqB,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAkD5H;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,SAAS,CAAsB,MAAS,EAAE,OAAO,GAAwB,EAAE;IAGzF,MAAM,C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1B,OAAO,IAAI,CAAC;IACd,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,YAAY,GAAG,WAAW,CAC9B,CAAC,GAAG,IAAe,EAAmB,EAAE,CACtC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QACtB,eAAe,CAAC,KAAK,IAAI,EAAE;YACzB,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,EACJ,CAAC,GAAG,CAAC,CACN,CAAC;IAEF,MAAM,OAAO,GAAG,WAAW,CACzB,CAAC,GAAG,IAAe,EAAQ,EAAE;QAC3B,KAAK,YAAY,CAAC,GAAG,IAAI,CAAC,CAAC;IAC7B,CAAC,EACD,CAAC,YAAY,CAAC,CACf,CAAC;IAEF,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,SAAS,CAAC,EAAE,CAAC,CAAC;QACd,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,MAAM,GAAoB,SAAS,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,IAAI,MAAM,CAAC,CAAC;IAE9E,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC;AACrE,CAAC;AAED,eAAe,SAAS,CAAC","sourcesContent":["\"use client\";\n\nimport { useCallback, useLayoutEffect, useRef, useState, useTransition } from \"react\";\nimport type { ActionResult } from \"../action.js\";\nimport { type Redirected, ServerValidationError, closeAnswer, isRedirected, openAnswer, redirectedBack } from \"./errors.js\";\n\n// Any action: createActionClient's handler(), with or without a schema, or a\n// plain \"use server\" function - the stub the build writes for a backend\n// action is one, and resolves with its value rather than an ActionResult.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyAction = (...args: any[]) => Promise<any>;\n\ntype Resolved<A extends AnyAction> = Awaited<ReturnType<A>>;\n\n// What it can be called with. A backend stub has two signatures - its own\n// parameters, then the form that posts to it, last so a bind keeps the form's\n// fields - and Parameters<> reads only the last: execute() on a stub that\n// takes an optional object asked for a FormData. Matched against two, a\n// function with one signature fills both from it.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype ArgsOf<A extends AnyAction> = A extends { (...args: infer First): any; (...args: infer Form): any }\n ? First | Form\n : Parameters<A>;\n\ntype DataOf<A extends AnyAction> =\n Resolved<A> extends ActionResult<infer D, any> ? D : Exclude<Resolved<A>, Redirected>;\n\ntype RefusalOf<A extends AnyAction> = Resolved<A> extends ActionResult<any, infer R> ? R : never;\n\n/** The whole result, refusal type included - see `.refusal(schema)`. */\ntype ResultOf<A extends AnyAction> = ActionResult<DataOf<A>, RefusalOf<A>>;\n\nexport type UseActionStatus = \"idle\" | \"executing\" | \"hasSucceeded\" | \"hasErrored\";\n\nexport interface UseActionOptions<A extends AnyAction> {\n /**\n * Called inside the action's transition, before the action runs, with what\n * it was called with - where React's `useOptimistic` setter goes. React\n * puts the optimistic state back when the transition ends, so a failed\n * action takes its change back on its own.\n */\n optimistic?: (...args: ArgsOf<A>) => void;\n /** The action answered with data: no serverError, no validationErrors. */\n onSuccess?: (data: DataOf<A>) => void;\n /**\n * The action refused or failed. With a serverError, that message; with\n * validationErrors, the first one - so a button with no field beside it\n * still has something to show.\n */\n onError?: (message: string, result: ResultOf<A>) => void;\n /** After either, for state that tracks the call rather than its outcome. */\n onSettled?: (result: ResultOf<A>) => void;\n}\n\n/**\n * Call an action from a button rather than a form.\n *\n * const { execute, isPending } = useAction(archivePost, {\n * optimistic: (input) => hide(input.id),\n * onError: (message) => toast.error(message),\n * })\n *\n * <button disabled={isPending} onClick={() => execute({ id })}>Archive</button>\n *\n * The action's own types carry through: `execute` takes what the action's\n * schema takes, and `onSuccess` is handed what its handler returns. A form does\n * not need this - <Form> reads the same result on its own.\n *\n * Neither `execute` nor `executeAsync` throws. An action built on the action\n * client returns its failures, and anything thrown on the way - the network,\n * a server that answered with a page - becomes a serverError: left thrown,\n * the transition never settled and an optimistic change stayed on screen as\n * though the write had worked.\n *\n * An action that redirected settles nothing: no callback runs and no state is\n * set, because the page is on its way somewhere else. A redirect back to the\n * page it was called from - Laravel's back() - is a success like any other.\n */\nexport function useAction<A extends AnyAction>(action: A, options: UseActionOptions<A> = {}) {\n type Result = ResultOf<A>;\n\n const [isPending, startTransition] = useTransition();\n const [result, setResult] = useState<Result>({});\n const [settled, setSettled] = useState<\"hasSucceeded\" | \"hasErrored\" | null>(null);\n\n // Read when the action runs, not when execute was made: execute keeps one\n // identity across renders, so an onClick built on it is not rebuilt, and a\n // callback closing over newer state is still the one called.\n const latest = useRef({ action, options });\n\n useLayoutEffect(() => {\n latest.current = { action, options };\n });\n\n const run = useCallback(async (args: ArgsOf<A>): Promise<Result> => {\n const { action, options } = latest.current;\n\n options.optimistic?.(...args);\n\n const from = window.location.pathname + window.location.search;\n let next: Result;\n\n try {\n // Open only for the call itself: React reaches the transport\n // synchronously, so nothing else can take it - see openAnswer().\n const answer = openAnswer();\n const pending = action(...args);\n\n closeAnswer();\n\n const value = await pending;\n\n // A stub's value is its data, and so is anything that is not an\n // object - a void stub resolves with null. Refusals reject, below.\n const data = answer.plain || typeof value !== \"object\" || value === null;\n\n next = (data && !isRedirected(value) ? { data: value } : value) as Result;\n } catch (error) {\n // A generated stub rejects when its input is refused, and a form or a\n // button reads that as it reads the result of an action built on the client.\n next =\n error instanceof ServerValidationError\n ? { validationErrors: error.errors }\n : { serverError: error instanceof Error ? error.message : String(error) };\n }\n\n // Gone elsewhere, nothing to settle - but back() to this page is the\n // action succeeding, and the page it re-rendered is still this one.\n if (next.redirected !== undefined && !redirectedBack(next.redirected, from)) return next;\n\n setResult(next);\n setSettled(next.serverError !== undefined || next.validationErrors ? \"hasErrored\" : \"hasSucceeded\");\n\n if (next.serverError !== undefined) {\n options.onError?.(next.serverError, next);\n } else if (next.validationErrors) {\n options.onError?.(Object.values(next.validationErrors).flat()[0] ?? \"Invalid input.\", next);\n } else {\n options.onSuccess?.(next.data as DataOf<A>);\n }\n\n options.onSettled?.(next);\n\n return next;\n }, []);\n\n const executeAsync = useCallback(\n (...args: ArgsOf<A>): Promise<Result> =>\n new Promise((resolve) => {\n startTransition(async () => {\n resolve(await run(args));\n });\n }),\n [run],\n );\n\n const execute = useCallback(\n (...args: ArgsOf<A>): void => {\n void executeAsync(...args);\n },\n [executeAsync],\n );\n\n const reset = useCallback(() => {\n setResult({});\n setSettled(null);\n }, []);\n\n const status: UseActionStatus = isPending ? \"executing\" : (settled ?? \"idle\");\n\n return { execute, executeAsync, isPending, status, result, reset };\n}\n\nexport default useAction;\n"]}
@@ -82,6 +82,12 @@ export interface ManifestRoute {
82
82
  * before. A page with it is not frozen at build; see pageCache.ts.
83
83
  */
84
84
  revalidate?: number;
85
+ /**
86
+ * `export const name = 'verification.verify'` in the page: the name a host
87
+ * that names its routes gives this one. Absent when the page declares
88
+ * none, and the host names it as it would anyway - Laravel by its path.
89
+ */
90
+ routeName?: string;
85
91
  }
86
92
  export interface ManifestIntercept {
87
93
  component: string;
@@ -126,6 +132,8 @@ export interface ManifestApiRoute {
126
132
  * a 403. For an api other sites call with a key of their own.
127
133
  */
128
134
  crossOrigin?: true;
135
+ /** `export const name` in the route.ts: see ManifestRoute.routeName. */
136
+ routeName?: string;
129
137
  }
130
138
  export interface RouteManifest {
131
139
  version: number;
@@ -1 +1 @@
1
- {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContentSecurityPolicy } from \"./csp.js\";\n// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n /**\n * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n /**\n * `export const crossOrigin = true`: another site's POST, PUT, PATCH or\n * DELETE reaches the handler - without the visitor's cookies - rather than\n * a 403. For an api other sites call with a key of their own.\n */\n crossOrigin?: true;\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n /**\n * Whether any page or section declares `refreshOn`, so the server signs\n * names - and must refuse to serve, in production, without a key every\n * instance shares.\n */\n refreshOn?: boolean;\n /**\n * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\n /**\n * rscKit({ contentSecurityPolicy }), checked: the author's directives, to\n * which the host adds each document's hashes, and a nonce when it streams.\n */\n contentSecurityPolicy?: ContentSecurityPolicy;\n /**\n * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal\n * to one, or under it, to the backend and everything else here. `[]` when\n * none; absent from a build before 0.30.53.\n */\n backendPaths?: string[];\n /** rscKit({ subdomains }): top-level directories served on their own subdomain. Absent when none. */\n subdomains?: string[];\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
1
+ {"version":3,"file":"manifest.js","sourceRoot":"","sources":["../src/manifest.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContentSecurityPolicy } from \"./csp.js\";\n// The shape of routes.json — what the build discovered, for a host to read.\n//\n// The build already walks app/ to generate its entries, and every host needs\n// the same facts: which url a component answers, what layouts wrap it, which\n// slots and sections belong to it. Laravel used to scan the tree a second time\n// to work that out; a JS host would have had to write a third walk. This is the\n// one answer, and these are its types.\n//\n// Urls are segments rather than a pattern string, because the pattern is the\n// host's dialect: Laravel writes {slug}, Hono writes :slug, and neither is the\n// build's business.\n\nexport interface RouteSegment {\n /**\n * `host`: a `[name]` directory at the top of app/. Bound from the request's\n * host, never from a path segment - so `example.com/nope` is a 404 rather\n * than a tenant called \"nope\". See hostRouting.\n */\n type: \"static\" | \"param\" | \"catchAll\" | \"host\";\n value: string;\n}\n\nexport interface ManifestRoute {\n component: string;\n segments: RouteSegment[];\n layouts: string[];\n loadings: string[];\n /**\n * `error.tsx` files above this route, outermost first.\n *\n * The nearest one to a failure catches it, the same way the nearest\n * `loading.tsx` is the fallback. Optional: a manifest from a build before\n * error boundaries existed has none.\n */\n errors?: string[];\n /**\n * `not-found.tsx` files above this route, outermost first.\n *\n * A `notFound()` from this route's page or guard is answered by the nearest\n * one, rendered inside the layouts above it; the way `error.tsx` is the\n * nearest above a failure. A url no route owns has no route to ask, and is\n * answered by the one at the root. Optional: a manifest from a build before\n * this has none, and the root one answers everything.\n */\n notFounds?: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * Run before anything at or below them renders, on every path. A check is\n * not UI, and making it a layout meant the client could decline it: layouts\n * are skipped on a partial navigation, and what gets skipped is named in a\n * header nothing can verify.\n */\n middleware: string[];\n slots: Record<string, string>;\n sections: string[];\n /**\n * The host's route-config file beside this page, if it named one, and the\n * ancestor ones that also apply — outermost first, this page's excluded.\n *\n * Relative to the project root: an absolute path is true only on the machine\n * that produced it, and building in a container is ordinary.\n */\n config: string | null;\n ancestorConfigs: string[];\n /**\n * Host middleware names for this route, outermost first.\n *\n * Declared in a route.ts beside or above the page. The engine does not know\n * what they mean — they are the host's own vocabulary — it only runs them\n * past the host before anything at or below this route renders.\n *\n * Empty on a route that named none, and on every route in an app that never\n * wrote a route.ts, which is why this needs no flag.\n *\n * Optional because registration boots from the PREVIOUS build's manifest: a\n * shape change takes two builds to settle, and a required field would make\n * the first of those a hard failure rather than a route with no guards.\n */\n hostMiddleware?: string[];\n /**\n * Whether the page exports generateStaticParams.\n *\n * Recorded here so a host can plan a build — which routes to ask for urls,\n * which to leave on demand — without loading the server bundle first. The\n * function itself is reached through the bundle's getStaticParams(), because\n * only the bundle can run it.\n */\n staticParams: boolean;\n /**\n * Seconds a shared cache may keep this page: the smallest\n * `export const revalidate` across its layouts and the page itself, as Next\n * takes it. Absent when none says, or one says 0 - rendered per request, as\n * before. A page with it is not frozen at build; see pageCache.ts.\n */\n revalidate?: number;\n /**\n * `export const name = 'verification.verify'` in the page: the name a host\n * that names its routes gives this one. Absent when the page declares\n * none, and the host names it as it would anyway - Laravel by its path.\n */\n routeName?: string;\n}\n\nexport interface ManifestIntercept {\n component: string;\n slot: string;\n segments: RouteSegment[];\n /** (.) same level, (..) one up, (...) from the root. */\n marker: string;\n}\n\n/**\n * A `route.ts` — an api endpoint rather than a page.\n *\n * Separate from `routes` because it is matched before them and answered\n * without rendering anything: no layouts, no payload, no client. A url cannot\n * be both, and the build refuses one that is.\n */\nexport interface ManifestApiRoute {\n /** The module name, as the engine's registry keys it. */\n name: string;\n /**\n * The file that answers, relative to the source directory - `app/api/x/route.ts`,\n * or `app/sitemap.ts` for a route the build synthesised from a metadata file\n * - so a line about the route can say where to look.\n */\n source?: string;\n segments: RouteSegment[];\n /** Which methods the file exports, so a 405 can name the rest. */\n methods: string[];\n /**\n * `middleware.ts` files above this route, outermost first.\n *\n * The same chain a page in that directory runs. A route.ts sits among the\n * pages it belongs with, so a guard on the directory covers it too —\n * anything else would mean adding an endpoint under a guarded path silently\n * opened a hole in it.\n */\n middleware: string[];\n /** Host middleware above this route (`export const middleware = [...]`), outermost first. */\n hostMiddleware?: string[];\n /**\n * `export const crossOrigin = true`: another site's POST, PUT, PATCH or\n * DELETE reaches the handler - without the visitor's cookies - rather than\n * a 403. For an api other sites call with a key of their own.\n */\n crossOrigin?: true;\n /** `export const name` in the route.ts: see ManifestRoute.routeName. */\n routeName?: string;\n}\n\nexport interface RouteManifest {\n version: number;\n build: {\n output: string;\n exportPath: string;\n payloadName: string;\n /**\n * The site's own hosts, bare and lower-case. A request from any other\n * host is matched with that host's segment in front of its path - see\n * hostRouting. Absent or empty: every request is the site's own.\n */\n hosts?: string[];\n /**\n * Whether every response says what built it: `X-Powered-By: rsc-kit` and\n * a generator meta tag in the document. The name only, never the version.\n * `X-RSC-Kit` (how a response was served) is sent regardless.\n */\n identify?: boolean;\n /**\n * Whether any page or section declares `refreshOn`, so the server signs\n * names - and must refuse to serve, in production, without a key every\n * instance shares.\n */\n refreshOn?: boolean;\n /**\n * rscKit({ headers }): set on every response, and handed to an edge with\n * every page it serves from its cache. Fixed for the build.\n */\n headers?: Record<string, string>;\n /**\n * rscKit({ contentSecurityPolicy }), checked: the author's directives, to\n * which the host adds each document's hashes, and a nonce when it streams.\n */\n contentSecurityPolicy?: ContentSecurityPolicy;\n /**\n * rscKit({ backendPaths }), normalised: a proxy in front sends a path equal\n * to one, or under it, to the backend and everything else here. `[]` when\n * none; absent from a build before 0.30.53.\n */\n backendPaths?: string[];\n /** rscKit({ subdomains }): top-level directories served on their own subdomain. Absent when none. */\n subdomains?: string[];\n };\n routes: ManifestRoute[];\n intercepts: ManifestIntercept[];\n /** Optional: a manifest from a build before api routes existed has none. */\n apis?: ManifestApiRoute[];\n}\n"]}
package/dist/request.d.ts CHANGED
@@ -5,6 +5,11 @@ export type RequestLike = Request | {
5
5
  headers: Record<string, string>;
6
6
  ip?: string;
7
7
  } | null;
8
+ /** A page by its url and the params its route matched, for a backend to build its request from. */
9
+ export interface ActionPage {
10
+ url: string;
11
+ params: Record<string, string>;
12
+ }
8
13
  /**
9
14
  * The request's headers.
10
15
  *
@@ -140,6 +145,20 @@ export declare function requestSearch(): string | null;
140
145
  * rather than about this renderer, which every visitor would otherwise share.
141
146
  */
142
147
  export declare function requestClientIp(): string | null;
148
+ /**
149
+ * One id for every host call this request makes, or null outside one.
150
+ *
151
+ * A render is several calls to the backend - the route's guards, then each
152
+ * read - and a session's flash lasts one request there. Spent by the first, a
153
+ * flash was gone by the read that showed it: Fortify's "We have emailed your
154
+ * password reset link" never reached the page. The id is how the backend
155
+ * keeps what it flashed for every call of the render, and for none after it.
156
+ *
157
+ * Made on the first call that asks, not with the request: a prerender watches
158
+ * crypto.randomUUID() for values frozen into a stored page, and the engine's
159
+ * own id is not one. A prerender has no request, so it never makes one.
160
+ */
161
+ export declare function requestRenderId(): string | null;
143
162
  /**
144
163
  * The backend guard checks already passed during this request, or null
145
164
  * outside one. A stored page is guarded before the store is looked in, and
@@ -252,6 +271,17 @@ export declare function renderingAsNobody(): boolean;
252
271
  */
253
272
  export declare function beginCheck(fields: string[], target: string | null): boolean;
254
273
  export declare function endCheck(): void;
274
+ /**
275
+ * Mark the action running now as posted from `page`, or clear the mark.
276
+ *
277
+ * A backend runs an action's guards against a request of its own, and the
278
+ * call is a POST from this renderer to the backend's endpoint: `signed` read
279
+ * the endpoint's url and refused every link, and a guard on a route param had
280
+ * none to read. The page the form was on is what the guard is about.
281
+ */
282
+ export declare function postedFrom(page: ActionPage | null): void;
283
+ /** The page the action running now was posted from, or null outside one. */
284
+ export declare function actionPage(): ActionPage | null;
255
285
  /** Whether the action running now is only being checked: its body must not run. */
256
286
  export declare function checkingOnly(): boolean;
257
287
  /**
package/dist/request.js CHANGED
@@ -466,6 +466,25 @@ export function requestClientIp() {
466
466
  const store = scope()?.getStore();
467
467
  return store?.request ? store.ip : null;
468
468
  }
469
+ /**
470
+ * One id for every host call this request makes, or null outside one.
471
+ *
472
+ * A render is several calls to the backend - the route's guards, then each
473
+ * read - and a session's flash lasts one request there. Spent by the first, a
474
+ * flash was gone by the read that showed it: Fortify's "We have emailed your
475
+ * password reset link" never reached the page. The id is how the backend
476
+ * keeps what it flashed for every call of the render, and for none after it.
477
+ *
478
+ * Made on the first call that asks, not with the request: a prerender watches
479
+ * crypto.randomUUID() for values frozen into a stored page, and the engine's
480
+ * own id is not one. A prerender has no request, so it never makes one.
481
+ */
482
+ export function requestRenderId() {
483
+ const store = scope()?.getStore();
484
+ if (!store?.request)
485
+ return null;
486
+ return (store.render ??= crypto.randomUUID());
487
+ }
469
488
  /**
470
489
  * The backend guard checks already passed during this request, or null
471
490
  * outside one. A stored page is guarded before the store is looked in, and
@@ -736,6 +755,23 @@ export function endCheck() {
736
755
  if (store)
737
756
  store.checking = undefined;
738
757
  }
758
+ /**
759
+ * Mark the action running now as posted from `page`, or clear the mark.
760
+ *
761
+ * A backend runs an action's guards against a request of its own, and the
762
+ * call is a POST from this renderer to the backend's endpoint: `signed` read
763
+ * the endpoint's url and refused every link, and a guard on a route param had
764
+ * none to read. The page the form was on is what the guard is about.
765
+ */
766
+ export function postedFrom(page) {
767
+ const store = scope()?.getStore();
768
+ if (store)
769
+ store.actionPage = page ?? undefined;
770
+ }
771
+ /** The page the action running now was posted from, or null outside one. */
772
+ export function actionPage() {
773
+ return scope()?.getStore()?.actionPage ?? null;
774
+ }
739
775
  /** Whether the action running now is only being checked: its body must not run. */
740
776
  export function checkingOnly() {
741
777
  return scope()?.getStore()?.checking !== undefined;