@softistx/alxia-react-router 0.83.1 → 0.84.2
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/README.md +18 -6
- package/dist/chunks/index-wyypkfdv.js.map +1 -1
- package/dist/errors/api-error.d.ts +4 -4
- package/dist/errors/api-error.d.ts.map +1 -1
- package/dist/errors/call-failure.d.ts +1 -1
- package/dist/errors/index.js.map +1 -1
- package/dist/subscription/react/index.d.ts +1 -1
- package/dist/subscription/react/index.js +2 -2
- package/dist/subscription/react/index.js.map +2 -2
- package/dist/subscription/react/use-live-subscription.d.ts +1 -1
- package/dist/subscription/react/use-live-subscription.d.ts.map +1 -1
- package/docs/guide/errors.md +5 -5
- package/docs/guide/subscriptions.md +2 -2
- package/docs/troubleshooting.md +21 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -38,6 +38,18 @@ own app, and make four changes.
|
|
|
38
38
|
bun add @softistx/alxia @softistx/alxia-react-router
|
|
39
39
|
```
|
|
40
40
|
|
|
41
|
+
The `@softistx` scope is restricted on npmjs and is read with a token. Point
|
|
42
|
+
Bun at it in `bunfig.toml`, with the token in an environment variable (here
|
|
43
|
+
`NPM_TOKEN`):
|
|
44
|
+
|
|
45
|
+
```toml
|
|
46
|
+
[install.scopes]
|
|
47
|
+
"@softistx" = { url = "https://registry.npmjs.org", token = "$NPM_TOKEN" }
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
A 401 or 404 on install means the token is missing
|
|
51
|
+
([troubleshooting](docs/troubleshooting.md#get-httpsregistrynpmjsorgsoftistx---401-or-404-on-a-softistx-package)).
|
|
52
|
+
|
|
41
53
|
**2. Add the plugin** to `vite.config.ts`. It can go anywhere in `plugins`:
|
|
42
54
|
|
|
43
55
|
```diff
|
|
@@ -97,7 +109,7 @@ client's files and the app's middlewares. So does React Router's prerendering.
|
|
|
97
109
|
optional peer, for `/vite`; `react` 19 is an optional peer, for `/pwa/react`, `/fetcher`, `/lists`, `/navigation` and `/oauth/react`; `jose` 6 is an optional peer, for `/oidc`. The six `workbox-*`
|
|
98
110
|
packages (`workbox-core`, `workbox-expiration`, `workbox-navigation-preload`,
|
|
99
111
|
`workbox-precaching`, `workbox-routing`, `workbox-strategies`) are optional
|
|
100
|
-
peers too, for `/pwa/worker` (the [PWA section](#installable-and-offline-pwa) has the install line). `@softistx/alxia-proxy` is an optional peer, for `/mcp` (`bun add @softistx/alxia-proxy`); `/mcp` also reads `@softistx/alxia`'s `MCP_RELAY_PATHS`. `react-hook-form` (7.55 or later) is an optional peer: `SectionForm`, the form `useSectionSave` and `useRowSave` take from `/fetcher`, is the shape of its `useForm()` result. `/errors` imports `react-router`, a required peer that is already installed. The package declares no dependency.
|
|
112
|
+
peers too, for `/pwa/worker` (the [PWA section](#installable-and-offline-pwa) has the install line). `@softistx/alxia-proxy` is an optional peer, for `/mcp` (`bun add @softistx/alxia-proxy`); `/mcp` also reads `@softistx/alxia`'s `MCP_RELAY_PATHS`. `react-hook-form` (7.55 or later) is an optional peer: `SectionForm`, the form `useSectionSave` and `useRowSave` take from `/fetcher`, is the shape of its `useForm()` result. `@softistx/graphql-client` (`^0.9.0`) is an optional peer, for `/subscription/react` (`bun add @softistx/graphql-client`). `/errors` imports `react-router`, a required peer that is already installed. The package declares no dependency.
|
|
101
113
|
|
|
102
114
|
Its `typescript` peer is 6 or 7. The template's TypeScript 5.9 typechecks,
|
|
103
115
|
but `bun add` warns about it; `bun add -d typescript@^6` silences the
|
|
@@ -866,7 +878,7 @@ banner and the rest.
|
|
|
866
878
|
## An API's refusals, worded for the page
|
|
867
879
|
|
|
868
880
|
`@softistx/alxia-react-router/errors` has no UI; its one runtime import is `react-router`, never `@softistx/alxia`. It
|
|
869
|
-
holds the shape of a GraphQL API's refusal, declared structurally (no `@
|
|
881
|
+
holds the shape of a GraphQL API's refusal, declared structurally (no `@softistx/graphql-client` at
|
|
870
882
|
runtime), a REST API's RFC 9457 problem reply (`problemError`), the request id an API echoes, the page a request is for, the
|
|
871
883
|
catalogue of the API's messages an app keeps, the words of a form's checks,
|
|
872
884
|
the provider that fills the catalogue in the browser, the wording of a refusal, the loaders and actions that answer with it, the JSON actions (CSRF check) with their fetcher hook, and what a failed call to the API becomes (`apiCallFailure`):
|
|
@@ -1158,7 +1170,7 @@ for the rules, the options and the errors.
|
|
|
1158
1170
|
### Keep it alive in the page: `useLiveSubscription`
|
|
1159
1171
|
|
|
1160
1172
|
`@softistx/alxia-react-router/subscription/react` is the browser side. It wraps
|
|
1161
|
-
`useSubscription` of `@
|
|
1173
|
+
`useSubscription` of `@softistx/graphql-client/react` (an optional peer, `^0.9.0`,
|
|
1162
1174
|
under a `GraphQLProvider`) and owns what a long-lived stream needs: reconnect
|
|
1163
1175
|
with a growing wait (1 s doubling to 30 s), a stop on a 401 or any 4xx repeating
|
|
1164
1176
|
cannot change, a 429's `retryAfter` honoured, events older than the highest
|
|
@@ -1826,7 +1838,7 @@ From `@softistx/alxia-react-router/errors` (`react-router` is its only package i
|
|
|
1826
1838
|
|
|
1827
1839
|
| export | |
|
|
1828
1840
|
| --- | --- |
|
|
1829
|
-
| `isApiErrorLike(error)` | whether `error` is an `@
|
|
1841
|
+
| `isApiErrorLike(error)` | whether `error` is an `@softistx/graphql-client` `ApiError`, like the client's `isApiError`, plus a numeric `status`, which `ApiErrorLike` promises; it holds across two copies of the client |
|
|
1830
1842
|
| `isStaleVersion(error)` | whether `error` is an API's refusal of an out-of-date update: an `ApiErrorLike` with status 409 whose `code` ends with `.errors.stale-version`; false for any other value |
|
|
1831
1843
|
| `ApiErrorLike`, `ApiErrorEntryLike`, `ApiErrorExtensionsLike`, `ApiErrorParamsLike`, `ApiFieldErrorLike` | the shape of the refusal: `errors`, `code`, `status`, `requestId?`, and each error's `extensions` (`code`, `params`, `fields`, `field`, `minutes`, `retryAfter`) |
|
|
1832
1844
|
| `waitMinutes(extensions)` | the minutes of a throttle's wait: `minutes` (at least one), else `retryAfter` rounded up |
|
|
@@ -1845,7 +1857,7 @@ From `@softistx/alxia-react-router/errors` (`react-router` is its only package i
|
|
|
1845
1857
|
| `apiCodeResolver(messages, { translate, language, codeOf?, isApiCode? })`, `ApiCodeResolver`, `ApiCodeResolverOptions`, `CodeIssueLike` | the `{ translate, codeOf }` a form's `useCodeResolver(schema, resolver)` takes: a check's API code is worded as the API words it, any other key by the app's translator; `CodeIssueLike` is the issue a custom `codeOf` receives |
|
|
1846
1858
|
| `ApiMessagesProvider({ messages, value, children })`, `ApiMessagesProviderProps` | `messages` is the store and `value` the root loader's data; fills the store in the browser from the root's data before the children render; a server render writes nothing. A function with no JSX, so no React import |
|
|
1847
1859
|
| `createApiErrors({ messages, unavailable, refused?, byCode?, reword?, isApiCode? })`, `ApiErrors`, `ApiErrorsOptions`, `FetcherResultOptions` | what a page says of a refusal, in a language: `apiErrorMessage(error, language)` (the catalogue's text of the code, else the API's message; `refused` replaces it for an error with no API code and `byCode` words given codes, such as a query's limits; `reword(text, error, { code, values, language })` words a family of codes once, on the final text of the catalogue, the API or `byCode`, returning `undefined` to keep it), `fieldErrors(error, language)` by input path, `translateCode(code, fallback, language, values?)`, `unavailableMessage(language)` and `apiRefusal(error, language)`; for an action, `fetcherResult(language, about, run, options?)` (`{ ok: true, …about, …value }`, or `{ ok: false, …about, error }` with the refusal's status; `options` is `FetcherResultOptions`: the `route` options plus `reword(error: ApiErrorLike)`, called for an API's own refusal only: the message of this call, or `undefined` to keep the worded one), `fetcherRefusal(error, language, route?)` (the refusal, or the thrown route error) and `submitForm(language, run, fieldOf, route?)` (`{ ok: true, value }`, or a `FormErrors` with the refusal's status); `formRefusal(error, language, fieldOf, route?)` (`{ error, fieldErrors, status }` for a fetcher form: each field issue under the form field `fieldOf` names, `error` empty when every issue found its field); `route` is the `RouteErrorOptions` of the `routeError` they throw through |
|
|
1848
|
-
| `apiCallFailure(error, { api, operation?, requestId?, signal?, passedThrough?, log? })`, `CallFailureOptions` | what a failed call to the API becomes, for a loader or an action to throw, logged with the request id: an `ApiError` as it is (with `requestId`), a `Response` of its own status for a 401, 403 or 404 without a GraphQL body, a 503 `Response` with no body for an unreachable, slow, garbled or aborted call (the reason is in the log), any other error as it is; the log lines start with `api`, and a `log` that throws never replaces the outcome. It recognises `@
|
|
1860
|
+
| `apiCallFailure(error, { api, operation?, requestId?, signal?, passedThrough?, log? })`, `CallFailureOptions` | what a failed call to the API becomes, for a loader or an action to throw, logged with the request id: an `ApiError` as it is (with `requestId`), a `Response` of its own status for a 401, 403 or 404 without a GraphQL body, a 503 `Response` with no body for an unreachable, slow, garbled or aborted call (the reason is in the log), any other error as it is; the log lines start with `api`, and a `log` that throws never replaces the outcome. It recognises `@softistx/graphql-client`'s errors by `name`, not `instanceof` |
|
|
1849
1861
|
| `operationName(document)`, `DocumentLike` | the name of the operation a document holds, for the log (else `query`, `mutation` or `subscription`); a structural `{ definitions }`, so `graphql`'s `DocumentNode` fits |
|
|
1850
1862
|
| `createErrorCatalogue({ messages, languages, read, versions, ttlMs, clientCodes, retryMs?, firstReadWaitMs?, log? })`, `ErrorCatalogue`, `ErrorCatalogueOptions`, `CatalogueReply` | keeps the API's error catalogue in the store: `fresh(language, now?)` and `freshAll(now?)` (a cold language is awaited for `firstReadWaitMs`, 1500 by default, and read once however many requests ask; a held one is served, and its version checked in the background once per `ttlMs`, a number or a getter; only a language whose version moved is read again; a failure is retried after `retryMs`, 5000 by default), `warm()` for startup, `clientMessages()` (the `clientCodes` the browser words itself, by language, for the root's loader), and, for tests, `reset()`, `heldVersion(language)`, `settled()` and the `now` parameters. `read` and `versions` are the app's calls to its API |
|
|
1851
1863
|
| `ApiRefusal` | `{ message, status }`: a failed call as a page says it; what `apiRefusal` returns for an API refusal (its status) or an unreachable API (503), else `undefined` |
|
|
@@ -2027,7 +2039,7 @@ From `@softistx/alxia-react-router/subscription` (no import, no peer):
|
|
|
2027
2039
|
| --- | --- |
|
|
2028
2040
|
| `createSubscriptionProxy({ endpoint, allow, getToken, headers?, origin?, heartbeatMs?, fetch? })`, `SubscriptionProxy`, `SubscriptionProxyOptions`, `SubscriptionArgs` | a resource route's `loader` (GET) and `action` (POST) relaying GraphQL subscriptions over SSE (graphql-sse's distinct connections mode). `allow` is `{ [operationName]: document }`: the proxy sends its own document, the client's `query` and `extensions` are ignored and an unknown name is a 403. Both methods refuse a cross-site request (403) and a POST that is not JSON (415); 401 without a token; 400 for a malformed or oversize request (body 64 KiB, query string and variables 16 KiB); the bearer and `headers` upstream (`headers(request, { request, context, params })`: a function gets the route's context, which never leaves it), a heartbeat comment every `heartbeatMs` (15000), the upstream aborted with the client, a pulled relay with a 1 MiB cap per event, an upstream 429 passed on with `Retry-After` and `retryAfter`, 502 for an upstream failure |
|
|
2029
2041
|
|
|
2030
|
-
From `@softistx/alxia-react-router/subscription/react` (imports `react` and `@
|
|
2042
|
+
From `@softistx/alxia-react-router/subscription/react` (imports `react` and `@softistx/graphql-client/react`, an optional peer):
|
|
2031
2043
|
|
|
2032
2044
|
| export | |
|
|
2033
2045
|
| --- | --- |
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/errors/api-error.ts", "../src/errors/route-error.ts", "../src/errors/problem-error.ts", "../src/errors/request-id.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * The shape of an API's refusal, as `@
|
|
5
|
+
"/**\n * The shape of an API's refusal, as `@softistx/graphql-client`'s `ApiError`\n * carries it, declared structurally: `/errors` never imports the client, so\n * an app needs it only if it calls the API through it. `api-error.spec.ts`\n * holds the two in step.\n */\n\n/** One refused input field: `extensions.fields` of a validation refusal. */\nexport interface ApiFieldErrorLike {\n\treadonly path: string;\n\treadonly code: string;\n\treadonly message: string;\n\t/** The values the field's message interpolates. */\n\treadonly params?: Readonly<Record<string, unknown>>;\n}\n\n/** The values a message interpolates; a throttle's wait is `minutes` or `retryAfter`. */\nexport interface ApiErrorParamsLike {\n\treadonly minutes?: unknown;\n\treadonly retryAfter?: unknown;\n\treadonly attemptsLeft?: unknown;\n\treadonly [key: string]: unknown;\n}\n\n/**\n * One GraphQL error's `extensions`. `code` is the API's own\n * `<module>.errors.<slug>`; the rest is what its messages name.\n */\nexport interface ApiErrorExtensionsLike {\n\treadonly code?: string;\n\t/** The values the message interpolates, when the API sends them. */\n\treadonly params?: ApiErrorParamsLike;\n\t/** A validation refusal: every field at fault, by input path. */\n\treadonly fields?: readonly ApiFieldErrorLike[];\n\t/** Any other refusal about one input field, by its path. */\n\treadonly field?: string;\n\t/** A throttle's wait, in minutes (`waitMinutes` coerces a string). */\n\treadonly minutes?: unknown;\n\t/** A throttle's wait, in seconds. */\n\treadonly retryAfter?: unknown;\n\t/** The tries a refused code leaves, as `@softistx/janus` counts them. */\n\treadonly attemptsLeft?: unknown;\n\treadonly [key: string]: unknown;\n}\n\n/** One error of a response's `errors`. */\nexport interface ApiErrorEntryLike {\n\treadonly message: string;\n\treadonly extensions?: ApiErrorExtensionsLike;\n}\n\n/** A refusal read from a GraphQL API: what `ApiError` has, and the request id. */\nexport interface ApiErrorLike extends Error {\n\treadonly errors: readonly ApiErrorEntryLike[];\n\t/** The first error's `extensions.code`. */\n\treadonly code: string | undefined;\n\t/** The HTTP status to answer with. */\n\treadonly status: number;\n\t/** The id the API logged the request under, when the caller kept it. */\n\treadonly requestId?: string;\n}\n\n/** Whether `error` is an `Error` of this `name`: the client's errors are told by it, never `instanceof`. */\nexport const isNamed = (error: unknown, name: string): error is Error =>\n\terror instanceof Error && error.name === name;\n\n/**\n * Whether `error` is an `ApiError` of `@softistx/graphql-client`, by the test\n * that client's `isApiError` makes (an `Error` named `ApiError` with an\n * `errors` array), plus a numeric `status`, which `ApiErrorLike` promises.\n * It holds across two copies of the client.\n */\nexport function isApiErrorLike(error: unknown): error is ApiErrorLike {\n\treturn (\n\t\tisNamed(error, 'ApiError') &&\n\t\tArray.isArray((error as { errors?: unknown }).errors) &&\n\t\ttypeof (error as { status?: unknown }).status === 'number'\n\t);\n}\n\n/**\n * Whether `error` is an API's refusal of an update whose version is out of\n * date: an `ApiError` with status 409 whose `code` ends with\n * `.errors.stale-version`. False for any other value.\n */\nexport function isStaleVersion(error: unknown): error is ApiErrorLike {\n\treturn (\n\t\tisApiErrorLike(error) &&\n\t\terror.status === 409 &&\n\t\ttypeof error.code === 'string' &&\n\t\terror.code.endsWith('.errors.stale-version')\n\t);\n}\n\n/**\n * The minutes a wait lasts, as the API words it: `minutes` (at least one, in\n * `extensions.params` or beside it), else the `retryAfter` seconds rounded\n * up, else one.\n */\nexport function waitMinutes(\n\textensions: ApiErrorExtensionsLike | undefined,\n): number {\n\tconst minutes = extensions?.params?.minutes ?? extensions?.minutes;\n\tif (minutes !== undefined) return Math.max(1, Number(minutes) || 1);\n\tconst seconds = extensions?.params?.retryAfter ?? extensions?.retryAfter;\n\treturn Math.max(1, Math.ceil(Number(seconds) / 60) || 1);\n}\n\nconst MAX_RETRY_AFTER = 86_400;\n\n/** A wait in seconds from one value: a finite number from 0, or a decimal string. */\nfunction secondsOf(value: unknown): number | undefined {\n\tconst seconds =\n\t\ttypeof value === 'string' && /^\\d+(\\.\\d+)?$/.test(value.trim())\n\t\t\t? Number(value.trim())\n\t\t\t: value;\n\treturn typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0\n\t\t? Math.min(MAX_RETRY_AFTER, Math.ceil(seconds)) + 0\n\t\t: undefined;\n}\n\n/**\n * The seconds a throttle asks to wait: `retryAfter` of the first error's\n * `extensions.params`, else (when that is unusable) of its `extensions`.\n * Only a finite number from 0, or a decimal string, counts; it is rounded up\n * and held at a day (86 400), and `-0` is 0. `undefined` when the API sent\n * none usable. Exported from `/errors`; `/session` words it as a typed\n * `retryAfter`.\n */\nexport function retryAfterOf(error: ApiErrorLike): number | undefined {\n\tconst extensions = error.errors[0]?.extensions;\n\treturn (\n\t\tsecondsOf(extensions?.params?.retryAfter) ??\n\t\tsecondsOf(extensions?.retryAfter)\n\t);\n}\n\n/** The API's `extensions.reason` of the first error (also in its `params`): `'throttled'` is a timed wait. */\nexport function reasonOf(error: ApiErrorLike): unknown {\n\tconst extensions = error.errors[0]?.extensions;\n\treturn extensions?.['reason'] ?? extensions?.params?.['reason'];\n}\n\n/** Whether the refusal carries `reason: 'throttled'`: a rate limit that asks to wait, whatever its code. */\nexport const isThrottledReason = (error: ApiErrorLike): boolean =>\n\treasonOf(error) === 'throttled';\n\n/**\n * The tries a refused code leaves, as `@softistx/janus` counts them:\n * `extensions.attemptsLeft` of the first error, else the same key in its\n * `params`. A whole number from 0 up; `undefined` when the API sent none or\n * something that is not a count. A throttled refusal (`isThrottledReason`)\n * spends no try: whatever count it carries (`0` included), it answers\n * `undefined`.\n */\nexport function attemptsLeftOf(error: ApiErrorLike): number | undefined {\n\tif (isThrottledReason(error)) return undefined;\n\tconst extensions = error.errors[0]?.extensions;\n\tfor (const value of [\n\t\textensions?.attemptsLeft,\n\t\textensions?.params?.attemptsLeft,\n\t]) {\n\t\tif (typeof value === 'number' && Number.isInteger(value) && value >= 0) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * The values a message names: `extensions.params` over the extensions\n * themselves, where older errors and the extras of a few sit.\n */\nexport function valuesOf(\n\textensions: ApiErrorExtensionsLike | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return undefined;\n\treturn extensions.params\n\t\t? { ...extensions, ...extensions.params }\n\t\t: extensions;\n}\n\n/** `@softistx/graphql-client`'s `ApiStatusError`, as far as the failure reads it. */\nexport interface StatusErrorLike extends Error {\n\tstatus: number;\n\tstatusText?: string | undefined;\n\tbody?: unknown;\n}\n\n/** `@softistx/graphql-client`'s `ApiUnavailableError`, as far as the failure reads it. */\nexport interface UnavailableErrorLike extends Error {\n\treason: string;\n}\n\nexport const isStatusError = (error: unknown): error is StatusErrorLike =>\n\tisNamed(error, 'ApiStatusError') &&\n\ttypeof (error as { status?: unknown }).status === 'number';\n\nexport const isUnavailableError = (\n\terror: unknown,\n): error is UnavailableErrorLike =>\n\tisNamed(error, 'ApiUnavailableError') &&\n\ttypeof (error as { reason?: unknown }).reason === 'string';\n",
|
|
6
6
|
"import { data } from 'react-router';\nimport { isApiErrorLike } from './api-error';\nimport { isProblemErrorLike } from './problem-error';\nimport { requestIdOf } from './request-id';\n\n/** The statuses an error page words: unauthenticated, forbidden, missing, unavailable. */\nconst ROUTED: ReadonlySet<number> = new Set([401, 403, 404, 503]);\n\n/**\n * What a route error of the API carries to the error page: the API's code\n * and message when it gave a code, and the `X-Request-Id` of the call as the\n * support reference (`errorRequestId`).\n */\nexport type RouteErrorData = {\n\tcode?: string | undefined;\n\tmessage?: string | undefined;\n\trequestId?: string | undefined;\n};\n\nexport interface RouteErrorOptions {\n\t/** The statuses that become a route error of their own; 401, 403, 404 and 503 by default. */\n\tstatuses?: ReadonlySet<number>;\n}\n\n/**\n * What a loader throws for an error from the API: an `ApiError` whose\n * status is routed (401, 403, 404 or 503) becomes a route error response of\n * that status, which the root `ErrorBoundary` renders as its page, with the\n * call's request id when the API gave one. A thrown routed `Response` that\n * carries a request id becomes one too (a bare `Response` hands the browser\n * its body only). Any other `ApiError` that has a request id becomes a 500\n * with just that id, so the generic error page can show it. A `ProblemError`\n * (`problemError`, a REST API's RFC 9457 reply) is treated alike, its message\n * being the problem's detail or title. Anything else\n * is returned as it is.\n */\nexport function routeError(\n\terror: unknown,\n\t{ statuses = ROUTED }: RouteErrorOptions = {},\n): unknown {\n\tif (isApiErrorLike(error)) {\n\t\tconst { requestId } = error;\n\t\tif (statuses.has(error.status)) {\n\t\t\treturn data<RouteErrorData>(\n\t\t\t\t{ code: error.code, message: error.message, requestId },\n\t\t\t\t{ status: error.status },\n\t\t\t);\n\t\t}\n\t\treturn requestId\n\t\t\t? data<RouteErrorData>({ requestId }, { status: 500 })\n\t\t\t: error;\n\t}\n\tif (isProblemErrorLike(error)) {\n\t\tconst { requestId } = error;\n\t\tif (statuses.has(error.status)) {\n\t\t\treturn data<RouteErrorData>(\n\t\t\t\t{ message: error.message, requestId },\n\t\t\t\t{ status: error.status },\n\t\t\t);\n\t\t}\n\t\treturn requestId\n\t\t\t? data<RouteErrorData>({ requestId }, { status: 500 })\n\t\t\t: error;\n\t}\n\tif (error instanceof Response && statuses.has(error.status)) {\n\t\tconst requestId = requestIdOf(error);\n\t\tif (requestId) {\n\t\t\treturn data<RouteErrorData>({ requestId }, { status: error.status });\n\t\t}\n\t}\n\treturn error;\n}\n\n/**\n * The support reference an error page shows: the API's `X-Request-Id` a\n * route error carries (`routeError`), if it carries one.\n */\nexport function errorRequestId(error: unknown): string | undefined {\n\tif (typeof error !== 'object' || error === null) return undefined;\n\tconst { data: body } = error as { data?: unknown };\n\tif (typeof body !== 'object' || body === null) return undefined;\n\tconst { requestId } = body as { requestId?: unknown };\n\treturn typeof requestId === 'string' && requestId ? requestId : undefined;\n}\n",
|
|
7
7
|
"import { isNamed } from './api-error';\n\n/** A reply of a REST/OpenAPI client, as far as `problemError` reads it: `{ status, data }`. */\nexport interface ProblemReply {\n\treadonly status: number;\n\t/** The parsed body; a problem document (RFC 9457) when the API refused. */\n\treadonly data?: unknown;\n}\n\nexport interface ProblemErrorOptions {\n\t/** The `x-request-id` the API answered (`requestIdOf(response)`). */\n\trequestId?: string | undefined;\n}\n\n/** A refusal read from a REST API's RFC 9457 problem reply. */\nexport interface ProblemErrorLike extends Error {\n\t/** The HTTP status of the reply. */\n\treadonly status: number;\n\t/** The problem's `title`, else `Error <status>`. */\n\treadonly title: string;\n\t/** The problem's `detail`, when it has one. */\n\treadonly detail?: string | undefined;\n\t/** The problem's `type` URI, when it has one. */\n\treadonly type?: string | undefined;\n\t/** The problem's `instance` URI, when it has one. */\n\treadonly instance?: string | undefined;\n\t/** The id the API logged the request under, when the caller kept it. */\n\trequestId?: string | undefined;\n}\n\nconst text = (value: unknown): string | undefined =>\n\ttypeof value === 'string' && value ? value : undefined;\n\n/**\n * The error of an RFC 9457 problem reply. Its `message` is the problem's\n * `detail`, else its `title`, else `Error <status>`.\n */\nexport class ProblemError extends Error implements ProblemErrorLike {\n\toverride readonly name = 'ProblemError';\n\treadonly status: number;\n\treadonly title: string;\n\treadonly detail: string | undefined;\n\treadonly type: string | undefined;\n\treadonly instance: string | undefined;\n\trequestId: string | undefined;\n\n\tconstructor(reply: ProblemReply, { requestId }: ProblemErrorOptions = {}) {\n\t\tconst body =\n\t\t\ttypeof reply.data === 'object' && reply.data !== null\n\t\t\t\t? (reply.data as {\n\t\t\t\t\t\ttitle?: unknown;\n\t\t\t\t\t\tdetail?: unknown;\n\t\t\t\t\t\ttype?: unknown;\n\t\t\t\t\t\tinstance?: unknown;\n\t\t\t\t\t})\n\t\t\t\t: {};\n\t\tconst title = text(body.title) ?? `Error ${reply.status}`;\n\t\tconst detail = text(body.detail);\n\t\tsuper(detail ?? title);\n\t\tthis.status = reply.status;\n\t\tthis.title = title;\n\t\tthis.detail = detail;\n\t\tthis.type = text(body.type);\n\t\tthis.instance = text(body.instance);\n\t\tthis.requestId = requestId;\n\t}\n}\n\n/**\n * Turns a REST/OpenAPI client's `{ status, data }` reply into a\n * `ProblemError`; a body that is not a problem document gives `Error <status>`.\n */\nexport function problemError(\n\treply: ProblemReply,\n\toptions?: ProblemErrorOptions,\n): ProblemError {\n\treturn new ProblemError(reply, options);\n}\n\n/**\n * Whether `error` is a `ProblemError`, told by its name and a numeric\n * `status`, never `instanceof`, so it holds across two copies of the package.\n */\nexport function isProblemErrorLike(error: unknown): error is ProblemErrorLike {\n\treturn (\n\t\tisNamed(error, 'ProblemError') &&\n\t\ttypeof (error as { status?: unknown }).status === 'number'\n\t);\n}\n",
|
|
8
8
|
"/** The header an API echoes on every response: the id its logs carry. */\nexport const REQUEST_ID_HEADER = 'x-request-id';\n\n/** The request id a response carries, if the API sent one. */\nexport function requestIdOf(response: Response): string | undefined {\n\treturn response.headers.get(REQUEST_ID_HEADER) || undefined;\n}\n"
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The shape of an API's refusal, as `@
|
|
2
|
+
* The shape of an API's refusal, as `@softistx/graphql-client`'s `ApiError`
|
|
3
3
|
* carries it, declared structurally: `/errors` never imports the client, so
|
|
4
4
|
* an app needs it only if it calls the API through it. `api-error.spec.ts`
|
|
5
5
|
* holds the two in step.
|
|
@@ -57,7 +57,7 @@ export interface ApiErrorLike extends Error {
|
|
|
57
57
|
/** Whether `error` is an `Error` of this `name`: the client's errors are told by it, never `instanceof`. */
|
|
58
58
|
export declare const isNamed: (error: unknown, name: string) => error is Error;
|
|
59
59
|
/**
|
|
60
|
-
* Whether `error` is an `ApiError` of `@
|
|
60
|
+
* Whether `error` is an `ApiError` of `@softistx/graphql-client`, by the test
|
|
61
61
|
* that client's `isApiError` makes (an `Error` named `ApiError` with an
|
|
62
62
|
* `errors` array), plus a numeric `status`, which `ApiErrorLike` promises.
|
|
63
63
|
* It holds across two copies of the client.
|
|
@@ -102,13 +102,13 @@ export declare function attemptsLeftOf(error: ApiErrorLike): number | undefined;
|
|
|
102
102
|
* themselves, where older errors and the extras of a few sit.
|
|
103
103
|
*/
|
|
104
104
|
export declare function valuesOf(extensions: ApiErrorExtensionsLike | undefined): Record<string, unknown> | undefined;
|
|
105
|
-
/** `@
|
|
105
|
+
/** `@softistx/graphql-client`'s `ApiStatusError`, as far as the failure reads it. */
|
|
106
106
|
export interface StatusErrorLike extends Error {
|
|
107
107
|
status: number;
|
|
108
108
|
statusText?: string | undefined;
|
|
109
109
|
body?: unknown;
|
|
110
110
|
}
|
|
111
|
-
/** `@
|
|
111
|
+
/** `@softistx/graphql-client`'s `ApiUnavailableError`, as far as the failure reads it. */
|
|
112
112
|
export interface UnavailableErrorLike extends Error {
|
|
113
113
|
reason: string;
|
|
114
114
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-error.d.ts","sourceRoot":"","sources":["../../src/errors/api-error.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,4EAA4E;AAC5E,MAAM,WAAW,iBAAiB;IACjC,QAAQ,CAAC,IA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,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,IAAI,CAAC,EAAE,OAAO,CAAC;CACf;AAED,0FAA0F;AAC1F,MAAM,WAAW,oBAAqB,SAAQ,KAAK;IAClD,MAAM,EAAE,MAAM,CAAC;CACf;AAED,eAAO,MAAM,aAAa,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,eAEG,CAAC;AAE5D,eAAO,MAAM,kBAAkB,GAC9B,OAAO,OAAO,KACZ,KAAK,IAAI,oBAE+C,CAAC"}
|
|
@@ -22,7 +22,7 @@ export interface CallFailureOptions {
|
|
|
22
22
|
* `requestId` and on a `Response` as `x-request-id`, where `routeError` reads
|
|
23
23
|
* it.
|
|
24
24
|
*
|
|
25
|
-
* It recognises `@
|
|
25
|
+
* It recognises `@softistx/graphql-client`'s errors by their `name`, never with
|
|
26
26
|
* `instanceof`, so it needs no import of the client and holds across two
|
|
27
27
|
* copies of it.
|
|
28
28
|
*/
|
package/dist/errors/index.js.map
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"import { valuesOf } from './api-error';\nimport type { ApiErrors, ApiErrorsOptions } from './api-errors';\nimport { API_CODE } from './code-resolver';\nimport { fieldErrorsOf, refusalOf } from './describe-refusal';\nimport { fetcherRefusal, fetcherResult } from './fetcher-result';\nimport { formRefusal } from './form-refusal';\nimport { submitForm } from './submit-form';\n\nexport function describeApiErrors<L extends string>({\n\tmessages,\n\tunavailable,\n\trefused,\n\treword,\n\tbyCode = {},\n\tisApiCode = (code) => API_CODE.test(code),\n}: ApiErrorsOptions<L>): ApiErrors<L> {\n\tconst translateCode: ApiErrors<L>['translateCode'] = (\n\t\tcode,\n\t\tfallback,\n\t\tlanguage,\n\t\tvalues,\n\t) => {\n\t\tif (!code) return fallback;\n\t\treturn messages.apiMessage(code, values, language) ?? fallback;\n\t};\n\n\tconst apiErrorMessage: ApiErrors<L>['apiErrorMessage'] = (\n\t\terror,\n\t\tlanguage,\n\t) => {\n\t\tconst code = error.code;\n\t\tif (refused && (!code || !isApiCode(code))) return refused(language);\n\t\tconst own = code && Object.hasOwn(byCode, code) ? byCode[code] : undefined;\n\t\tconst values = valuesOf(error.errors[0]?.extensions);\n\t\tconst text = own\n\t\t\t? own(error, language)\n\t\t\t: translateCode(code, error.message, language, values);\n\t\tif (!reword || !code) return text;\n\t\treturn (\n\t\t\treword(text, error, { code, values: values ?? {}, language }) ?? text\n\t\t);\n\t};\n\n\tconst unavailableMessage = (language: L) => unavailable(language);\n\n\tconst apiRefusal: ApiErrors<L>['apiRefusal'] = (error, language) =>\n\t\trefusalOf({ apiErrorMessage, unavailableMessage }, error, language);\n\n\tconst fieldErrors: ApiErrors<L>['fieldErrors'] = (error, language) =>\n\t\tfieldErrorsOf({ apiErrorMessage, translateCode }, error, language);\n\n\tconst parts = { apiRefusal, apiErrorMessage, fieldErrors };\n\n\treturn {\n\t\ttranslateCode,\n\t\tapiErrorMessage,\n\t\tunavailableMessage,\n\t\tfieldErrors,\n\t\tapiRefusal,\n\t\tfetcherRefusal: (error, language, route) =>\n\t\t\tfetcherRefusal(parts, error, language, route),\n\t\tformRefusal: (error, language, fieldOf, route) =>\n\t\t\tformRefusal(parts, error, language, fieldOf, route),\n\t\tfetcherResult: (language, about, run, options) =>\n\t\t\tfetcherResult(parts, language, about, run, options),\n\t\tsubmitForm: (language, run, fieldOf, route) =>\n\t\t\tsubmitForm(parts, language, run, fieldOf, route),\n\t};\n}\n",
|
|
11
11
|
"import type { data } from 'react-router';\nimport type { ApiErrorLike } from './api-error';\nimport { describeApiErrors } from './describe';\nimport type { FetcherResultOptions } from './fetcher-result';\nimport type { FormErrors } from './form-errors';\nimport type { FormRefusal } from './form-refusal';\nimport type { ApiMessages } from './messages';\nimport type { RouteErrorOptions } from './route-error';\n\n/** A refused call, as a page says it: the message, and the HTTP status to answer. */\nexport type ApiRefusal = { message: string; status: number };\n\nexport interface ApiErrorsOptions<L extends string> {\n\t/** The catalogue the API's codes are worded from. */\n\tmessages: ApiMessages<L>;\n\t/**\n\t * The app's own word for an API it cannot reach (a 503 `Response`): not\n\t * an API error, so never one of the catalogue's codes.\n\t */\n\tunavailable(language: L): string;\n\t/**\n\t * The app's generic refusal, said for an error with no API code (a raw\n\t * `BAD_USER_INPUT` before the API's validation layer), never the raw\n\t * message. Without it, such an error says the message the API sent.\n\t */\n\trefused?(language: L): string;\n\t/**\n\t * An app's own wording for given codes, such as the API's request limits\n\t * (depth, cost, introspection), whose params differ and name no field.\n\t * Checked after `refused`, before the catalogue.\n\t */\n\tbyCode?: Readonly<\n\t\tRecord<string, (error: ApiErrorLike, language: L) => string>\n\t>;\n\t/**\n\t * Words a whole family of codes once, after the text is worded. It runs\n\t * on the final text `apiErrorMessage` (so `apiRefusal`, `fetcherResult`,\n\t * `fetcherRefusal`, `submitForm` and a single `extensions.field`) says\n\t * for an error with a code, whichever produced it: the catalogue, the\n\t * API's own message, or `byCode`. It does not run on `refused`'s text, on\n\t * `unavailable`'s (a network failure), on `translateCode` nor on the\n\t * entries of `extensions.fields`. `values` are the merged values the\n\t * catalogue formats with (`extensions` and `extensions.params`, params\n\t * winning). Return the text to show, or `undefined` to keep `text`.\n\t */\n\treword?(\n\t\ttext: string,\n\t\terror: ApiErrorLike,\n\t\tcontext: {\n\t\t\tcode: string;\n\t\t\tvalues: Readonly<Record<string, unknown>>;\n\t\t\tlanguage: L;\n\t\t},\n\t): string | undefined;\n\t/** Whether a code is an API code; `<module>.errors.<slug>` by default. */\n\tisApiCode?(code: string): boolean;\n}\n\n/** What a page says of an API's refusals, in a language. */\nexport interface ApiErrors<L extends string> {\n\t/**\n\t * The catalogue's text of an API code in `language`, else `fallback` (the\n\t * message the API already worded). `values` are the message's arguments\n\t * (`extensions.params`).\n\t */\n\ttranslateCode(\n\t\tcode: string | undefined,\n\t\tfallback: string,\n\t\tlanguage: L,\n\t\tvalues?: Readonly<Record<string, unknown>>,\n\t): string;\n\t/**\n\t * What to show for an API error: `refused` for an error with no API code,\n\t * when given; else `byCode`'s wording of its code; else the catalogue's\n\t * text; else the message the API already worded.\n\t */\n\tapiErrorMessage(error: ApiErrorLike, language: L): string;\n\t/**\n\t * The message of each refused field, by input path, ready for a form: the\n\t * entries of `extensions.fields`, else the one field `extensions.field`\n\t * names, with the error's own message. Empty for neither.\n\t */\n\tfieldErrors(error: ApiErrorLike, language: L): Record<string, string>;\n\t/** `unavailable`, in `language`. */\n\tunavailableMessage(language: L): string;\n\t/**\n\t * What a failed call says to the user: an API refusal's message and its\n\t * status, or an API it cannot reach (a 503 `Response`: the unavailable\n\t * word). Undefined for anything else, which the caller rethrows.\n\t */\n\tapiRefusal(error: unknown, language: L): ApiRefusal | undefined;\n\t/**\n\t * A fetcher's refusal: `apiRefusal`'s, so the page stays where it was. A\n\t * 401 (the session caller redirects first) or any other failure is\n\t * thrown, through `routeError`, for the error page.\n\t */\n\tfetcherRefusal(\n\t\terror: unknown,\n\t\tlanguage: L,\n\t\troute?: RouteErrorOptions,\n\t): ApiRefusal;\n\t/**\n\t * A fetcher form's refusal (`fetcherRefusal`) with its field issues under\n\t * the form field `fieldOf` names for each input path: `{ error,\n\t * fieldErrors, status }`, `error` empty when every issue found its field.\n\t */\n\tformRefusal(\n\t\terror: unknown,\n\t\tlanguage: L,\n\t\tfieldOf: (path: string) => string | undefined,\n\t\troute?: RouteErrorOptions,\n\t): FormRefusal;\n\t/**\n\t * Runs the mutation of an action a fetcher posted to: `{ ok: true }` with\n\t * `about` and the mutation's value, or `{ ok: false, error }` with `about`\n\t * and the refusal's message, answered with its HTTP status. `options.reword`\n\t * words the refusal of this call from the caught API error (`undefined`\n\t * keeps the worded message); it is not called for an unreachable API.\n\t */\n\tfetcherResult<\n\t\tAbout extends object,\n\t\tValue extends object = Record<never, never>,\n\t>(\n\t\tlanguage: L,\n\t\tabout: About,\n\t\trun: () => Promise<Value>,\n\t\toptions?: FetcherResultOptions,\n\t): Promise<\n\t\t| ({ ok: true } & About & Value)\n\t\t| ReturnType<typeof data<{ ok: false; error: string } & About>>\n\t>;\n\t/**\n\t * Runs a form's mutation: `{ ok: true, value }`, or the form's errors\n\t * (`fieldErrors` under the form field `fieldOf` names an input path by,\n\t * and a `formError` for the rest) with the refusal's status. A 404 about\n\t * none of the form's fields, a 401 and other failures are thrown for the\n\t * error page, through `routeError` (with `route`).\n\t */\n\tsubmitForm<T>(\n\t\tlanguage: L,\n\t\trun: () => Promise<T>,\n\t\tfieldOf: (path: string) => string | undefined,\n\t\troute?: RouteErrorOptions,\n\t): Promise<{ ok: true; value: T } | ReturnType<typeof data<FormErrors>>>;\n}\n\n/**\n * The wording of an API's refusals for the languages `L`, from the\n * catalogue `messages` holds. Make one per app, beside its `createApiMessages`.\n */\nexport function createApiErrors<L extends string>(\n\toptions: ApiErrorsOptions<L>,\n): ApiErrors<L> {\n\treturn describeApiErrors(options);\n}\n",
|
|
12
12
|
"/** The methods of a `console` a report goes through. */\nexport type LogMethod = 'warn' | 'error';\n\n/**\n * A log whose methods can throw without breaking what reports through\n * them: a broken app log must not turn a handled failure into a rejection.\n */\nexport function quietLog<M extends LogMethod>(\n\tlog: Pick<Console, M>,\n\tmethods: readonly M[],\n): Pick<Console, M> {\n\tconst quiet = {} as Pick<Console, M>;\n\tfor (const method of methods) {\n\t\tquiet[method] = ((...args: unknown[]) => {\n\t\t\ttry {\n\t\t\t\t(log[method] as (...args: unknown[]) => void)(...args);\n\t\t\t} catch {\n\t\t\t\t// Swallowed on purpose: see above.\n\t\t\t}\n\t\t}) as Pick<Console, M>[M];\n\t}\n\treturn quiet;\n}\n",
|
|
13
|
-
"import { isApiErrorLike, isStatusError, isUnavailableError } from './api-error';\nimport { quietLog } from './log';\nimport { isProblemErrorLike } from './problem-error';\nimport { REQUEST_ID_HEADER } from './request-id';\n\n/** The statuses an API's gateway or auth layer may answer without a GraphQL body. */\nconst PASSED_THROUGH: ReadonlySet<number> = new Set([401, 403, 404]);\n\n/** The statuses a `Response` cannot carry a body with. */\nconst NO_BODY: ReadonlySet<number> = new Set([101, 204, 205, 304]);\n\nexport interface CallFailureOptions {\n\t/** What a log line names the API by, such as `my-api https://api.example.com/graphql`. */\n\tapi: string;\n\t/** The operation's name, for the log (`operationName(document)`). */\n\toperation?: string;\n\t/** The `x-request-id` the API answered, when it did (`requestIdOf(response)`). */\n\trequestId?: string;\n\t/** The incoming request's signal: an aborted call is answered 503. */\n\tsignal?: AbortSignal;\n\t/** The statuses without a GraphQL body that become a `Response` of their own; 401, 403 and 404 by default. */\n\tpassedThrough?: ReadonlySet<number>;\n\t/** Where the lines go; `console` by default. */\n\tlog?: Pick<Console, 'warn' | 'error'>;\n}\n\n/**\n * What a call became once it failed, for a loader or an action to throw: the\n * `ApiError` or `ProblemError` as it is (carrying `requestId`), a `Response` of the API's own\n * status for a 401, 403 or 404 without a GraphQL body, a 503 `Response` (with no body; the reason is in the log) for an\n * unreachable, slow, garbled or aborted API, and any other error as it is.\n * Every case it recognises is logged with the request id, when the API gave one, and never\n * the headers, the variables nor a token; the id rides on the `ApiError` as\n * `requestId` and on a `Response` as `x-request-id`, where `routeError` reads\n * it.\n *\n * It recognises `@
|
|
13
|
+
"import { isApiErrorLike, isStatusError, isUnavailableError } from './api-error';\nimport { quietLog } from './log';\nimport { isProblemErrorLike } from './problem-error';\nimport { REQUEST_ID_HEADER } from './request-id';\n\n/** The statuses an API's gateway or auth layer may answer without a GraphQL body. */\nconst PASSED_THROUGH: ReadonlySet<number> = new Set([401, 403, 404]);\n\n/** The statuses a `Response` cannot carry a body with. */\nconst NO_BODY: ReadonlySet<number> = new Set([101, 204, 205, 304]);\n\nexport interface CallFailureOptions {\n\t/** What a log line names the API by, such as `my-api https://api.example.com/graphql`. */\n\tapi: string;\n\t/** The operation's name, for the log (`operationName(document)`). */\n\toperation?: string;\n\t/** The `x-request-id` the API answered, when it did (`requestIdOf(response)`). */\n\trequestId?: string;\n\t/** The incoming request's signal: an aborted call is answered 503. */\n\tsignal?: AbortSignal;\n\t/** The statuses without a GraphQL body that become a `Response` of their own; 401, 403 and 404 by default. */\n\tpassedThrough?: ReadonlySet<number>;\n\t/** Where the lines go; `console` by default. */\n\tlog?: Pick<Console, 'warn' | 'error'>;\n}\n\n/**\n * What a call became once it failed, for a loader or an action to throw: the\n * `ApiError` or `ProblemError` as it is (carrying `requestId`), a `Response` of the API's own\n * status for a 401, 403 or 404 without a GraphQL body, a 503 `Response` (with no body; the reason is in the log) for an\n * unreachable, slow, garbled or aborted API, and any other error as it is.\n * Every case it recognises is logged with the request id, when the API gave one, and never\n * the headers, the variables nor a token; the id rides on the `ApiError` as\n * `requestId` and on a `Response` as `x-request-id`, where `routeError` reads\n * it.\n *\n * It recognises `@softistx/graphql-client`'s errors by their `name`, never with\n * `instanceof`, so it needs no import of the client and holds across two\n * copies of it.\n */\nexport function apiCallFailure(\n\terror: unknown,\n\t{\n\t\tapi,\n\t\toperation = 'operation',\n\t\trequestId,\n\t\tsignal,\n\t\tpassedThrough = PASSED_THROUGH,\n\t\tlog: appLog = console,\n\t}: CallFailureOptions,\n): unknown {\n\tconst log = quietLog(appLog, ['warn', 'error']);\n\tconst call = `${api}: ${operation}${requestId ? ` (request ${requestId})` : ''}`;\n\tconst headers: Record<string, string> = requestId\n\t\t? { [REQUEST_ID_HEADER]: requestId }\n\t\t: {};\n\tconst unavailable = (reason: string, cause?: unknown): Response => {\n\t\tlog.error(`${call} ${reason}`, cause ?? '');\n\t\treturn new Response(null, { status: 503, headers });\n\t};\n\tif (isApiErrorLike(error)) {\n\t\t// The client's `ApiError.requestId` is writable, though the structural type marks it readonly.\n\t\tif (requestId) (error as { requestId?: string }).requestId = requestId;\n\t\tconst line = `${call} answered ${error.status}${error.code ? ` ${error.code}` : ''}`;\n\t\tif (error.status >= 500) log.error(line);\n\t\telse log.warn(line);\n\t\treturn error;\n\t}\n\tif (isProblemErrorLike(error)) {\n\t\tif (requestId) error.requestId = requestId;\n\t\tconst line = `${call} answered ${error.status}`;\n\t\tif (error.status >= 500) log.error(line);\n\t\telse log.warn(line);\n\t\treturn error;\n\t}\n\tif (isStatusError(error)) {\n\t\tif (passedThrough.has(error.status)) {\n\t\t\tlog.warn(`${call} answered ${error.status}`);\n\t\t\tconst statusText =\n\t\t\t\ttypeof error.statusText === 'string' ? error.statusText : '';\n\t\t\tif (NO_BODY.has(error.status)) {\n\t\t\t\treturn new Response(null, {\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t\tstatusText,\n\t\t\t\t\theaders,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn new Response(statusText, {\n\t\t\t\tstatus: error.status,\n\t\t\t\tstatusText,\n\t\t\t\theaders,\n\t\t\t});\n\t\t}\n\t\treturn unavailable(`answered ${error.status} without GraphQL`, error.body);\n\t}\n\tif (isUnavailableError(error)) return unavailable(error.reason, error.cause);\n\tif (signal?.aborted) return unavailable('aborted', error);\n\treturn error;\n}\n\n/** A document, as far as `operationName` reads it: `graphql`'s `DocumentNode` fits. */\nexport interface DocumentLike {\n\treadonly definitions: readonly {\n\t\treadonly kind: string;\n\t\treadonly operation?: string | undefined;\n\t\treadonly name?: { readonly value: string } | undefined;\n\t}[];\n}\n\n/**\n * The name of the operation a document holds, for a log line: its name, else\n * its kind (`query`, `mutation`, `subscription`), else `operation`.\n */\nexport function operationName(document: DocumentLike): string {\n\tfor (const definition of document.definitions) {\n\t\tif (definition.kind === 'OperationDefinition') {\n\t\t\treturn definition.name?.value ?? definition.operation ?? 'operation';\n\t\t}\n\t}\n\treturn 'operation';\n}\n",
|
|
14
14
|
"import type { Held } from './catalogue-read';\n\n/** What the TTL check needs: the reader's state and the app's own calls. */\nexport interface CheckContext<L extends string> {\n\treader: {\n\t\theld: Map<L, Held>;\n\t\tload(language: L, now: number): Promise<void>;\n\t};\n\tversions(): Promise<Partial<Record<L, string>>>;\n\tttl(): number;\n\tretryMs: number;\n\tlog: Pick<Console, 'error'>;\n}\n\n/**\n * Asks the versions in one call and reads again the messages of each\n * language that moved. An API that cannot be reached keeps the messages\n * held (stale, still worded) and is asked again after `retryMs`.\n */\nexport async function checkVersions<L extends string>(\n\t{ reader, versions, ttl, retryMs, log }: CheckContext<L>,\n\tnow: number,\n) {\n\ttry {\n\t\tconst latest = await versions();\n\t\tfor (const [language, entry] of [...reader.held]) {\n\t\t\tif (latest[language] !== entry.version) {\n\t\t\t\tawait reader.load(language, now);\n\t\t\t} else {\n\t\t\t\tentry.checkedAt = now;\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\tlog.error(\n\t\t\t'alxia-react-router: the error catalogue was not checked, keeping what is held',\n\t\t\terror,\n\t\t);\n\t\tfor (const entry of reader.held.values()) {\n\t\t\tentry.checkedAt = now - ttl() + retryMs;\n\t\t}\n\t}\n}\n\n/**\n * The TTL, whose getter is the app's: one that throws, or that is not a\n * finite number of at least 0, is logged and `fallback` is used.\n */\nexport function safeTtl(\n\tttlMs: number | (() => number),\n\tfallback: number,\n\tlog: Pick<Console, 'error'>,\n) {\n\treturn () => {\n\t\ttry {\n\t\t\tconst ttl = typeof ttlMs === 'function' ? ttlMs() : ttlMs;\n\t\t\tif (typeof ttl === 'number' && Number.isFinite(ttl) && ttl >= 0) {\n\t\t\t\treturn ttl;\n\t\t\t}\n\t\t\tlog.error('alxia-react-router: ttlMs is not a duration, using retryMs');\n\t\t} catch (error) {\n\t\t\tlog.error('alxia-react-router: ttlMs threw, using retryMs', error);\n\t\t}\n\t\treturn fallback;\n\t};\n}\n",
|
|
15
15
|
"import type { ApiMessages, CatalogueMessage } from './messages';\n\n/** What the API answers for one language: its version and every message. */\nexport type CatalogueReply = {\n\tversion: string;\n\tmessages: ReadonlyArray<CatalogueMessage & { readonly code: string }>;\n};\n\n/** A language's catalogue as held, and when its version was last confirmed. */\nexport type Held = { version: string; checkedAt: number };\n\nexport interface CatalogueReaderOptions<L extends string> {\n\tmessages: ApiMessages<L>;\n\tread(language: L): Promise<CatalogueReply>;\n\tretryMs: number;\n\tfirstReadWaitMs: number;\n\tlog: Pick<Console, 'error'>;\n}\n\n/**\n * Waits for the read, until `firstReadWaitMs` after it started (not after\n * this request came: a hung API holds a request at most that long in\n * all); the read goes on either way.\n */\nasync function boundedWait(\n\tpending: { read: Promise<void>; started: number },\n\tfirstReadWaitMs: number,\n) {\n\tconst left = firstReadWaitMs - (performance.now() - pending.started);\n\tif (left <= 0) return;\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tconst limit = new Promise<void>((resolve) => {\n\t\ttimer = setTimeout(resolve, left);\n\t});\n\tawait Promise.race([pending.read, limit]);\n\tclearTimeout(timer);\n}\n\n/**\n * The reading half of the catalogue: the first read of each language (one in\n * flight, a bounded wait, a retry delay after a failure) and the version\n * each one holds. `createErrorCatalogue` adds the TTL check on top.\n */\nexport function createCatalogueReader<L extends string>({\n\tmessages,\n\tread,\n\tretryMs,\n\tfirstReadWaitMs,\n\tlog,\n}: CatalogueReaderOptions<L>) {\n\tconst held = new Map<L, Held>();\n\tconst loading = new Map<L, { read: Promise<void>; started: number }>();\n\tconst failedAt = new Map<L, number>();\n\n\t/** Reads one language's messages and holds them. */\n\tasync function load(language: L, now: number) {\n\t\tconst reply = await read(language);\n\t\tconst entries: Record<string, CatalogueMessage> = Object.create(null);\n\t\tfor (const { code, message, params } of reply.messages) {\n\t\t\tentries[code] = { message, params };\n\t\t}\n\t\tmessages.set(language, entries);\n\t\theld.set(language, { version: reply.version, checkedAt: now });\n\t}\n\n\t/** The first read of a language, once however many pages ask at the same time. */\n\tfunction loadOnce(language: L, now: number) {\n\t\tlet pending = loading.get(language);\n\t\tif (!pending) {\n\t\t\tconst started = performance.now();\n\t\t\tconst reading = load(language, now)\n\t\t\t\t.then(() => {\n\t\t\t\t\tfailedAt.delete(language);\n\t\t\t\t})\n\t\t\t\t.catch((error) => {\n\t\t\t\t\t// When it failed, not when it started: a read that hung for\n\t\t\t\t\t// the wait is not retried at once by the next request.\n\t\t\t\t\tfailedAt.set(language, now + (performance.now() - started));\n\t\t\t\t\tlog.error(\n\t\t\t\t\t\t`alxia-react-router: the error catalogue (${language}) was not read`,\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tloading.delete(language);\n\t\t\t\t});\n\t\t\tpending = { read: reading, started };\n\t\t\tloading.set(language, pending);\n\t\t}\n\t\treturn pending;\n\t}\n\n\treturn {\n\t\theld,\n\t\tload,\n\t\t/** Reads a language that is not held yet, unless a failure is still fresh. */\n\t\tasync first(language: L, now: number) {\n\t\t\tconst failed = failedAt.get(language);\n\t\t\tif (failed === undefined || now - failed >= retryMs) {\n\t\t\t\tawait boundedWait(loadOnce(language, now), firstReadWaitMs);\n\t\t\t}\n\t\t},\n\t\treset() {\n\t\t\theld.clear();\n\t\t\tloading.clear();\n\t\t\tfailedAt.clear();\n\t\t},\n\t};\n}\n",
|
|
16
16
|
"import { checkVersions, safeTtl } from './catalogue-check';\nimport { type CatalogueReply, createCatalogueReader } from './catalogue-read';\nimport { quietLog } from './log';\nimport type { ApiMessages, CatalogueMessages } from './messages';\n\nexport type { CatalogueReply } from './catalogue-read';\n\nexport interface ErrorCatalogueOptions<L extends string> {\n\t/** The store the page words refusals from (`createApiMessages`). */\n\tmessages: ApiMessages<L>;\n\t/** The languages to hold, each read once and kept fresh. */\n\tlanguages: readonly L[];\n\t/** Reads one language's catalogue from the API. */\n\tread(language: L): Promise<CatalogueReply>;\n\t/** Asks the API for the version of every language, in one call. */\n\tversions(): Promise<Partial<Record<L, string>>>;\n\t/** How long a held catalogue is served before its version is checked. */\n\tttlMs: number | (() => number);\n\t/** How soon a check or a first read that failed is tried again. Default 5000. */\n\tretryMs?: number;\n\t/**\n\t * How long a request waits for a language's first read; past it the\n\t * request goes on and the read carries on in the background. Default 1500.\n\t */\n\tfirstReadWaitMs?: number;\n\t/** The codes the browser words itself (`clientMessages`). */\n\tclientCodes: readonly string[];\n\t/** Where failures are reported. Default `console`. */\n\tlog?: Pick<Console, 'error'>;\n}\n\n/** The API's error catalogue, kept fresh for the server. */\nexport interface ErrorCatalogue<L extends string> {\n\t/**\n\t * The catalogue of `language`, ready to word a refusal. Only a language\n\t * with no catalogue yet is awaited, for at most `firstReadWaitMs`. A held\n\t * one is served as it is, and once older than the TTL its version is\n\t * checked in the background, one check at a time.\n\t */\n\tfresh(language: L, now?: number): Promise<void>;\n\t/** Every language, fresh: what the root middleware awaits. */\n\tfreshAll(now?: number): Promise<void>;\n\t/** At startup: reads every language without holding the boot back. */\n\twarm(): void;\n\t/** The messages the browser words itself, by language, for the root's loader. */\n\tclientMessages(): Record<L, CatalogueMessages>;\n\t/**\n\t * Forgets everything held and in flight. For use between tests, with\n\t * nothing in flight: a read or check still running when it is called\n\t * finishes and holds its result again.\n\t */\n\treset(): void;\n\t/** The version held for a language, if any. */\n\theldVersion(language: L): string | undefined;\n\t/** Waits for the check in flight, if any (tests). */\n\tsettled(): Promise<void>;\n}\n\n/** The messages the browser words itself, by language. */\nfunction clientMessages<L extends string>(\n\tmessages: ApiMessages<L>,\n\tlanguages: readonly L[],\n\tclientCodes: readonly string[],\n) {\n\tconst byLanguage = {} as Record<L, CatalogueMessages>;\n\tfor (const language of languages) {\n\t\tconst entries: Record<string, CatalogueMessages[string]> =\n\t\t\tObject.create(null);\n\t\tfor (const code of clientCodes) {\n\t\t\tconst entry = messages.messageOf(language, code);\n\t\t\tif (entry) entries[code] = entry;\n\t\t}\n\t\tbyLanguage[language] = entries;\n\t}\n\treturn byLanguage;\n}\n\n/**\n * Keeps the API's error catalogue in `messages`: read on first use, checked\n * against the API's versions once per TTL, and re-read only for the\n * languages whose version moved. It is an instance, not module state.\n */\nexport function createErrorCatalogue<L extends string>({\n\tmessages,\n\tlanguages,\n\tread,\n\tversions,\n\tttlMs,\n\tretryMs = 5_000,\n\tfirstReadWaitMs = 1_500,\n\tclientCodes,\n\tlog: appLog = console,\n}: ErrorCatalogueOptions<L>): ErrorCatalogue<L> {\n\tif (languages.length === 0) {\n\t\tthrow new TypeError('createErrorCatalogue(): needs at least one language.');\n\t}\n\tconst log = quietLog(appLog, ['error']);\n\tconst ttl = safeTtl(ttlMs, retryMs, log);\n\tconst reader = createCatalogueReader({\n\t\tmessages,\n\t\tread,\n\t\tretryMs,\n\t\tfirstReadWaitMs,\n\t\tlog,\n\t});\n\tconst context = { reader, versions, ttl, retryMs, log };\n\tlet checking: Promise<void> | undefined;\n\n\tasync function fresh(language: L, now: number = Date.now()) {\n\t\tconst entry = reader.held.get(language);\n\t\tif (!entry) return reader.first(language, now);\n\t\tif (now - entry.checkedAt >= ttl() && !checking) {\n\t\t\tchecking = checkVersions(context, now)\n\t\t\t\t.finally(() => {\n\t\t\t\t\tchecking = undefined;\n\t\t\t\t})\n\t\t\t\t.catch(() => {});\n\t\t}\n\t}\n\n\tconst freshAll = async (now: number = Date.now()) => {\n\t\tawait Promise.all(languages.map((language) => fresh(language, now)));\n\t};\n\n\treturn {\n\t\tfresh,\n\t\tfreshAll,\n\t\twarm() {\n\t\t\tfreshAll().catch((error) => {\n\t\t\t\tlog.error(\n\t\t\t\t\t'alxia-react-router: the error catalogue was not warmed',\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tclientMessages: () => clientMessages(messages, languages, clientCodes),\n\t\treset() {\n\t\t\treader.reset();\n\t\t\tchecking = undefined;\n\t\t\tmessages.clear();\n\t\t},\n\t\theldVersion: (language) => reader.held.get(language)?.version,\n\t\tsettled: () => checking ?? Promise.resolve(),\n\t};\n}\n",
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* subscription kept alive in the browser (reconnect with a growing wait,
|
|
4
4
|
* end classification, version dedupe, a debounced revalidate), and the pure
|
|
5
5
|
* rules behind it. It pairs with `createSubscriptionProxy` from
|
|
6
|
-
* `@softistx/alxia-react-router/subscription`. `react` and `@
|
|
6
|
+
* `@softistx/alxia-react-router/subscription`. `react` and `@softistx/graphql-client` are
|
|
7
7
|
* its only imports.
|
|
8
8
|
*/
|
|
9
9
|
export { BACKOFF_MAX_MS, BACKOFF_MIN_MS, backoffDelay } from './backoff';
|
|
@@ -177,7 +177,7 @@ function createLiveController(options) {
|
|
|
177
177
|
};
|
|
178
178
|
}
|
|
179
179
|
// src/subscription/react/use-live-subscription.ts
|
|
180
|
-
import { useSubscription } from "@
|
|
180
|
+
import { useSubscription } from "@softistx/graphql-client/react";
|
|
181
181
|
import { useEffect, useRef, useState } from "react";
|
|
182
182
|
function useLiveSubscription(document, variables, options) {
|
|
183
183
|
const [status, setStatus] = useState("connecting");
|
|
@@ -223,5 +223,5 @@ export {
|
|
|
223
223
|
useLiveSubscription
|
|
224
224
|
};
|
|
225
225
|
|
|
226
|
-
//# debugId=
|
|
226
|
+
//# debugId=2E2FE090703EF59C64756E2164756E21
|
|
227
227
|
//# sourceMappingURL=index.js.map
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
"/** The clock the live rules use, injectable so specs can drive it by hand. */\nexport type Timers = {\n\tset: (fn: () => void, ms: number) => unknown;\n\tclear: (handle: unknown) => void;\n};\n\nexport const globalTimers: Timers = {\n\tset: (fn, ms) => setTimeout(fn, ms),\n\tclear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),\n};\n",
|
|
10
10
|
"/** The highest version seen per key: an event below it is stale. */\nexport function createVersions() {\n\tconst seen = new Map<string, number>();\n\treturn {\n\t\t/** True (and remembered) unless `version` is below the highest seen for `key`. */\n\t\taccept(key: string, version: number): boolean {\n\t\t\tconst highest = seen.get(key);\n\t\t\tif (highest !== undefined && version < highest) return false;\n\t\t\tseen.set(key, Math.max(version, highest ?? version));\n\t\t\treturn true;\n\t\t},\n\t};\n}\n",
|
|
11
11
|
"import { classifyEnd } from './classify';\nimport { createReconnector } from './reconnect';\nimport { createRevalidateScheduler } from './scheduler';\nimport { globalTimers, type Timers } from './timers';\nimport { createVersions } from './versions';\n\n/** What the live subscription is doing, for the page's indicator. */\nexport type LiveStatus = 'connecting' | 'live' | 'reconnecting' | 'stopped';\n\nexport type LiveControllerOptions<T> = {\n\t/** Which thing an event is about. With `versionOf`, enables dedupe; an event with no key is never dropped. */\n\tkeyOf?: ((change: T) => string | null | undefined) | undefined;\n\t/** How new the event's state is; below the highest seen for its key, it is dropped. */\n\tversionOf?: ((change: T) => number) | undefined;\n\t/** Opens the stream again. */\n\trestart: () => void;\n\t/** Reads the page's data again; at most once per debounce window. Without it, nothing is read again. */\n\trevalidate?: (() => void) | undefined;\n\t/** An event newer than any seen for its key. */\n\tonChange: (change: T) => void;\n\tonStatus: (status: LiveStatus) => void;\n\ttimers?: Timers | undefined;\n\trandom?: (() => number) | undefined;\n};\n\n/**\n * The rules of a live stream, apart from React so they can be tested with a\n * fake clock: events are hints with no replay, so the page reads again on\n * every reopen after the first, keeps the highest version per key,\n * reconnects with a growing wait, and stops on a refusal.\n */\nexport function createLiveController<T>(options: LiveControllerOptions<T>) {\n\tconst timers = options.timers ?? globalTimers;\n\tconst versions = createVersions();\n\tlet status: LiveStatus = 'connecting';\n\tlet opened = false;\n\n\tconst setStatus = (next: LiveStatus) => {\n\t\tif (next === status) return;\n\t\tstatus = next;\n\t\toptions.onStatus(next);\n\t};\n\tconst reconnector = createReconnector(\n\t\ttimers,\n\t\toptions.random ?? Math.random,\n\t\toptions.restart,\n\t);\n\tconst reads = createRevalidateScheduler(timers, () => options.revalidate?.());\n\tconst dispose = () => {\n\t\treconnector.cancel();\n\t\treads.cancel();\n\t};\n\tconst stop = () => {\n\t\tsetStatus('stopped');\n\t\tdispose();\n\t};\n\tconst fresh = (change: T): boolean => {\n\t\tconst key = options.keyOf?.(change);\n\t\tif (key == null || !options.versionOf) return true;\n\t\treturn versions.accept(key, options.versionOf(change));\n\t};\n\tconst requestRevalidate = () => {\n\t\tif (status !== 'stopped' && options.revalidate) reads.request();\n\t};\n\n\treturn {\n\t\tget status() {\n\t\t\treturn status;\n\t\t},\n\t\t/** The stream is accepted. Anything sent while it was down is lost, so after the first open the page reads again. */\n\t\topen() {\n\t\t\tif (status === 'stopped') return;\n\t\t\treconnector.reset();\n\t\t\tsetStatus('live');\n\t\t\tif (opened) requestRevalidate();\n\t\t\topened = true;\n\t\t},\n\t\t/** A result; false when it is stale. */\n\t\tdata(change: T): boolean {\n\t\t\tif (status === 'stopped' || !fresh(change)) return false;\n\t\t\toptions.onChange(change);\n\t\t\treturn true;\n\t\t},\n\t\trevalidate: requestRevalidate,\n\t\t/** The stream ended (clean, or failed with `error`): open it again, unless the refusal is permanent. */\n\t\tended(error?: unknown) {\n\t\t\tif (status === 'stopped') return;\n\t\t\tconst end = classifyEnd(error);\n\t\t\tif (end.kind === 'stop') return stop();\n\t\t\tsetStatus('reconnecting');\n\t\t\treconnector.schedule(end.afterMs);\n\t\t},\n\t\t/** The session is over (a 401): stopped until `retry`. */\n\t\tunauthenticated: stop,\n\t\t/** The user asks again after a stop. */\n\t\tretry() {\n\t\t\tdispose();\n\t\t\treconnector.reset();\n\t\t\tstatus = 'connecting';\n\t\t\toptions.onStatus('connecting');\n\t\t\toptions.restart();\n\t\t},\n\t\tdispose,\n\t};\n}\n",
|
|
12
|
-
"import type { GraphQLDocument } from '@
|
|
12
|
+
"import type { GraphQLDocument } from '@softistx/graphql-client';\nimport { useSubscription } from '@softistx/graphql-client/react';\nimport { useEffect, useRef, useState } from 'react';\nimport { createLiveController, type LiveStatus } from './controller';\n\nexport type LiveControls = {\n\t/** Asks for the page's data to be read again (debounced). */\n\trevalidate: () => void;\n};\n\nexport type UseLiveSubscriptionOptions<TEvent> = {\n\t/** Which thing an event is about. With `versionOf`, an event below the highest version seen for its key is dropped; an event with no key is never dropped. */\n\tkeyOf?: ((event: TEvent) => string | null | undefined) | undefined;\n\t/** How new the event's state is. Leave out with `keyOf` for a stream whose every event is the whole state. */\n\tversionOf?: ((event: TEvent) => number) | undefined;\n\t/** Each fresh event, in order. The latest function is called. */\n\tonChange: (event: TEvent, controls: LiveControls) => void;\n\t/** Reads the page's data again (a loader, a refetch): at most once per window of 300 ms of quiet or 2 s, and after every reopen but the first. Leave out for a stream that needs no read. */\n\trevalidate?: (() => void) | undefined;\n\t/** Connects nothing while `true`. */\n\tskip?: boolean | undefined;\n};\n\nexport type LiveSubscription = {\n\tstatus: LiveStatus;\n\t/** After a stop (`status === 'stopped'`): open the stream again. */\n\tretry: () => void;\n\t/** Asks for the page's data to be read again (debounced). */\n\trevalidate: () => void;\n};\n\n/**\n * A GraphQL subscription kept alive: reconnects with a growing wait (1 s to\n * 30 s), stops on a 401 or another refusal repeating cannot change, waits a\n * 429's `retryAfter`, drops events older than the highest version seen per\n * key, and reads the page again (debounced) after every reopen but the first,\n * since nothing is replayed. Pairs with `createSubscriptionProxy`.\n *\n * Needs `GraphQLProvider` above it.\n */\nexport function useLiveSubscription<TEvent, TVariables = Record<string, never>>(\n\tdocument: GraphQLDocument<TEvent, TVariables>,\n\tvariables: TVariables,\n\toptions: UseLiveSubscriptionOptions<TEvent>,\n): LiveSubscription {\n\tconst [status, setStatus] = useState<LiveStatus>('connecting');\n\t// What the controller calls is always the latest of these, without rebuilding it.\n\tconst latest = useRef(options);\n\tlatest.current = options;\n\tconst restartRef = useRef<() => void>(() => {});\n\tconst [controller] = useState(() => {\n\t\tconst live = createLiveController<TEvent>({\n\t\t\t// No versionOf: no dedupe, every event is delivered.\n\t\t\tkeyOf: (event) =>\n\t\t\t\tlatest.current.versionOf ? latest.current.keyOf?.(event) : undefined,\n\t\t\tversionOf: (event) => latest.current.versionOf?.(event) ?? 0,\n\t\t\trestart: () => restartRef.current(),\n\t\t\trevalidate: () => latest.current.revalidate?.(),\n\t\t\tonStatus: setStatus,\n\t\t\tonChange: (event) =>\n\t\t\t\tlatest.current.onChange(event, { revalidate: live.revalidate }),\n\t\t});\n\t\treturn live;\n\t});\n\tconst { restart } = useSubscription(\n\t\tdocument,\n\t\t...([\n\t\t\tvariables,\n\t\t\t{\n\t\t\t\tskip: options.skip,\n\t\t\t\tonOpen: () => controller.open(),\n\t\t\t\tonData: (event: TEvent) => void controller.data(event),\n\t\t\t\tonError: (error: unknown) => controller.ended(error),\n\t\t\t\tonComplete: () => controller.ended(),\n\t\t\t\tonUnauthenticated: () => controller.unauthenticated(),\n\t\t\t},\n\t\t] as never),\n\t);\n\trestartRef.current = restart;\n\tuseEffect(() => () => controller.dispose(), [controller]);\n\treturn { status, retry: controller.retry, revalidate: controller.revalidate };\n}\n"
|
|
13
13
|
],
|
|
14
14
|
"mappings": ";AAAO,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AAMvB,SAAS,YAAY,CAAC,SAAiB,QAAwB;AAAA,EACrE,MAAM,OAAO,KAAK,IAAI,gBAAgB,iBAAiB,KAAK,OAAO;AAAA,EACnE,OAAO,KAAK,MAAM,QAAQ,MAAM,SAAS,IAAI;AAAA;;ACE9C,SAAS,YAAY,CAAC,OAAqC;AAAA,EAC1D,MAAM,QAAQ,MAAM,SAAS,IAAI;AAAA,EACjC,MAAM,UAAU,OAAO,OAAO,cAAc,MAAM,MAAM,UAAU;AAAA,EAClE,OAAO,OAAO,SAAS,OAAO,KAAK,UAAU,IAAI,UAAU,OAAO;AAAA;AAU5D,SAAS,WAAW,CAAC,OAA0B;AAAA,EACrD,IAAI,UAAU;AAAA,IAAW,OAAO,EAAE,MAAM,QAAQ;AAAA,EAChD,MAAM,IAAI;AAAA,EACV,MAAM,SAAS,EAAE,cAAc,EAAE;AAAA,EACjC,IAAI,WAAW;AAAA,IAAK,OAAO,EAAE,MAAM,OAAO;AAAA,EAC1C,MAAM,OAAO,EAAE,SAAS,IAAI,YAAY;AAAA,EACxC,IAAI,SAAS,6BAA6B,UAAU,OAAO,KAAK;AAAA,IAC/D,OAAO,EAAE,MAAM,QAAQ;AAAA,EACxB;AAAA,EACA,IAAI,WAAW;AAAA,IAAK,OAAO,EAAE,MAAM,SAAS,SAAS,aAAa,CAAC,EAAE;AAAA,EACrE,IAAI,WAAW,aAAa,UAAU,OAAO,SAAS,KAAK;AAAA,IAC1D,OAAO,EAAE,MAAM,OAAO;AAAA,EACvB;AAAA,EACA,OAAO,EAAE,MAAM,QAAQ;AAAA;;ACjCjB,SAAS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O,QAAQ,YAAY,KAAK,KAAK;AAAA,MAC3D,SAAS,MAAM,WAAW,QAAQ;AAAA,MAClC,YAAY,MAAM,OAAO,QAAQ,aAAa;AAAA,MAC9C,UAAU;AAAA,MACV,UAAU,CAAC,UACV,OAAO,QAAQ,SAAS,OAAO,EAAE,YAAY,KAAK,WAAW,CAAC;AAAA,IAChE,CAAC;AAAA,IACD,OAAO;AAAA,GACP;AAAA,EACD,QAAQ,YAAY,gBACnB,UACA,GAAI;AAAA,IACH;AAAA,IACA;AAAA,MACC,MAAM,QAAQ;AAAA,MACd,QAAQ,MAAM,WAAW,KAAK;AAAA,MAC9B,QAAQ,CAAC,UAAkB,KAAK,WAAW,KAAK,KAAK;AAAA,MACrD,SAAS,CAAC,UAAmB,WAAW,MAAM,KAAK;AAAA,MACnD,YAAY,MAAM,WAAW,MAAM;AAAA,MACnC,mBAAmB,MAAM,WAAW,gBAAgB;AAAA,IACrD;AAAA,EACD,CACD;AAAA,EACA,WAAW,UAAU;AAAA,EACrB,UAAU,MAAM,MAAM,WAAW,QAAQ,GAAG,CAAC,UAAU,CAAC;AAAA,EACxD,OAAO,EAAE,QAAQ,OAAO,WAAW,OAAO,YAAY,WAAW,WAAW;AAAA;",
|
|
15
|
-
"debugId": "
|
|
15
|
+
"debugId": "2E2FE090703EF59C64756E2164756E21",
|
|
16
16
|
"names": []
|
|
17
17
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { GraphQLDocument } from '@
|
|
1
|
+
import type { GraphQLDocument } from '@softistx/graphql-client';
|
|
2
2
|
import { type LiveStatus } from './controller';
|
|
3
3
|
export type LiveControls = {
|
|
4
4
|
/** Asks for the page's data to be read again (debounced). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-live-subscription.d.ts","sourceRoot":"","sources":["../../../src/subscription/react/use-live-subscription.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,
|
|
1
|
+
{"version":3,"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AAC,GACzC,gBAAgB,CAqClB"}
|
package/docs/guide/errors.md
CHANGED
|
@@ -27,7 +27,7 @@ import is `react-router`, never `@softistx/alxia`, so a page can import it
|
|
|
27
27
|
|
|
28
28
|
| export | what it is |
|
|
29
29
|
| --- | --- |
|
|
30
|
-
| `ApiErrorLike`, `isApiErrorLike(error)` | the shape of `@
|
|
30
|
+
| `ApiErrorLike`, `isApiErrorLike(error)` | the shape of `@softistx/graphql-client`'s `ApiError`, and the test for it |
|
|
31
31
|
| `isStaleVersion(error)` | whether `error` is an API's refusal of an out-of-date update: an `ApiErrorLike` with status 409 whose `code` ends with `.errors.stale-version`; false for any other value |
|
|
32
32
|
| `ApiErrorEntryLike`, `ApiErrorExtensionsLike`, `ApiErrorParamsLike`, `ApiFieldErrorLike` | one error of the response, its `extensions`, their `params`, and one refused field |
|
|
33
33
|
| `waitMinutes(extensions)` | the minutes of a throttle's wait: `minutes` (at least one), else `retryAfter` rounded up to minutes |
|
|
@@ -54,7 +54,7 @@ import is `react-router`, never `@softistx/alxia`, so a page can import it
|
|
|
54
54
|
|
|
55
55
|
## Recognising an API error
|
|
56
56
|
|
|
57
|
-
The subpath does not depend on `@
|
|
57
|
+
The subpath does not depend on `@softistx/graphql-client`. `isApiErrorLike` tests
|
|
58
58
|
an `Error` named `ApiError` that has an `errors` array, like the client's
|
|
59
59
|
`isApiError`, plus a numeric `status`, which `ApiErrorLike` promises. It holds
|
|
60
60
|
when two copies of the client are installed.
|
|
@@ -956,7 +956,7 @@ throw, and logs it:
|
|
|
956
956
|
| anything else | the same error | none |
|
|
957
957
|
|
|
958
958
|
It recognises the client's errors by their `name`, never with `instanceof`, so
|
|
959
|
-
it imports nothing from `@
|
|
959
|
+
it imports nothing from `@softistx/graphql-client` and holds across two copies of
|
|
960
960
|
it. Pass `requestId` from the response (`requestIdOf(response)`), and the id
|
|
961
961
|
rides on the `ApiError` and on the `Response`, where `routeError` reads it.
|
|
962
962
|
`passedThrough` replaces the statuses that keep their own (401, 403 and 404),
|
|
@@ -969,11 +969,11 @@ throws never replaces the outcome: the error or `Response` is returned as if
|
|
|
969
969
|
the line had been written.
|
|
970
970
|
|
|
971
971
|
An app writes one `execute` that sends the call and ends in `apiCallFailure`.
|
|
972
|
-
The example uses `@
|
|
972
|
+
The example uses `@softistx/graphql-client`; `operationName` reads a document
|
|
973
973
|
structurally, so `graphql` is not imported by the subpath.
|
|
974
974
|
|
|
975
975
|
```ts
|
|
976
|
-
import { createGraphQLClient } from '@
|
|
976
|
+
import { createGraphQLClient } from '@softistx/graphql-client';
|
|
977
977
|
import {
|
|
978
978
|
apiCallFailure,
|
|
979
979
|
operationName,
|
|
@@ -145,7 +145,7 @@ they like: rate-limit it (`@softistx/alxia-rate-limit`) if the API does not.
|
|
|
145
145
|
|
|
146
146
|
`@softistx/alxia-react-router/subscription/react` is the browser side of the route
|
|
147
147
|
above. `useLiveSubscription(document, variables, options)` wraps
|
|
148
|
-
`useSubscription` of `@
|
|
148
|
+
`useSubscription` of `@softistx/graphql-client/react` (an optional peer, `^0.9.0`;
|
|
149
149
|
the page needs its `GraphQLProvider`) and handles what a stream that lives for
|
|
150
150
|
minutes needs. The bare client never retries, reconnects or deduplicates.
|
|
151
151
|
|
|
@@ -202,7 +202,7 @@ each render does not reopen the stream; only the document and the variables
|
|
|
202
202
|
|
|
203
203
|
## Testing
|
|
204
204
|
|
|
205
|
-
For the hook, mock `@
|
|
205
|
+
For the hook, mock `@softistx/graphql-client/react`'s `useSubscription` and call the
|
|
206
206
|
`onOpen`, `onData`, `onError` and `onComplete` it was given. For the rules, use
|
|
207
207
|
`createLiveController` with a `timers` of your own (a fake clock).
|
|
208
208
|
|
package/docs/troubleshooting.md
CHANGED
|
@@ -7,6 +7,7 @@ a loader, a message React Router or the browser prints, or an error from
|
|
|
7
7
|
|
|
8
8
|
**Thrown or printed**
|
|
9
9
|
|
|
10
|
+
- [`GET https://registry.npmjs.org/@softistx/… - 401`, or `404` on a `@softistx` package](#get-httpsregistrynpmjsorgsoftistx---401-or-404-on-a-softistx-package)
|
|
10
11
|
- [`docs/flows/…: <what is wrong with the front-matter>`](#docsflows-what-is-wrong-with-the-front-matter)
|
|
11
12
|
- [`The returned state is not the one this sign-in sent.` and the other `OidcError` messages (`/oidc`)](#the-returned-state-is-not-the-one-this-sign-in-sent-and-the-other-oidcerror-messages-oidc)
|
|
12
13
|
- [`capture file x.1440.light.webp is missing from docs/flows/captures/`](#capture-file-x1440lightwebp-is-missing-from-docsflowscaptures)
|
|
@@ -1955,7 +1956,7 @@ export const failed = (error: unknown) =>
|
|
|
1955
1956
|
Logged as an error by `apiCallFailure`, and the loader gets a 503 `Response`
|
|
1956
1957
|
with no body (the reason is in the log line).
|
|
1957
1958
|
|
|
1958
|
-
**Why:** `@
|
|
1959
|
+
**Why:** `@softistx/graphql-client` could not get an answer: `unreachable` is a
|
|
1959
1960
|
refused connection or a DNS failure, `timeout` is a call past the deadline the
|
|
1960
1961
|
app gave it, and `invalid-response` is an answer that is no GraphQL response
|
|
1961
1962
|
(a 2xx with no `data`, garbled JSON). The log line's second argument is the
|
|
@@ -2253,6 +2254,25 @@ stepUpSteps({
|
|
|
2253
2254
|
});
|
|
2254
2255
|
```
|
|
2255
2256
|
|
|
2257
|
+
### `GET https://registry.npmjs.org/@softistx/… - 401`, or `404` on a `@softistx` package
|
|
2258
|
+
|
|
2259
|
+
`bun add @softistx/alxia-react-router` (or any `@softistx` package) fails
|
|
2260
|
+
with a 401, or with `404 Not Found`, although the package exists.
|
|
2261
|
+
|
|
2262
|
+
**Why:** the `@softistx` scope is restricted on npmjs: it is read with a
|
|
2263
|
+
token, and a request without one is answered as if the package did not exist.
|
|
2264
|
+
|
|
2265
|
+
**Fix:** give Bun the token in `bunfig.toml`, from an environment variable
|
|
2266
|
+
(here `NPM_TOKEN`, any name works) rather than the file:
|
|
2267
|
+
|
|
2268
|
+
```toml
|
|
2269
|
+
[install.scopes]
|
|
2270
|
+
"@softistx" = { url = "https://registry.npmjs.org", token = "$NPM_TOKEN" }
|
|
2271
|
+
```
|
|
2272
|
+
|
|
2273
|
+
Export the variable before `bun install`; an unset one is simply omitted, so
|
|
2274
|
+
the install fails again with the same error.
|
|
2275
|
+
|
|
2256
2276
|
### `docs/flows/…: <what is wrong with the front-matter>`
|
|
2257
2277
|
|
|
2258
2278
|
A `FlowFormatError`, thrown by `loadHelpFlows` (at module load) and reported as
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softistx/alxia-react-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.84.2",
|
|
4
4
|
"description": "alxia as the server of a React Router framework app: server rendering behind the app's hooks, loaders reading its typed context, the client's assets served; the code with no UI an installable app shares (`/pwa`), its hooks (`/pwa/react`), `noCache` for the worker's script (`/pwa/server`), the service worker on Workbox (`/pwa/worker`) and its build (`/pwa/build`), an API's refusals worded for the page (`/errors`), the BFF session: cookies, sign-in, step-up and mail links (`/session`), its page hooks (`/session/react`) and what it shares with the page (`/session/model`), a GraphQL subscription relayed to the browser over SSE (`/subscription`) and kept alive in the page (`/subscription/react`), an API's MCP and OAuth endpoints relayed on the app's origin (`/mcp`), per-role flow docs, the help panel's data and its lazy `HelpPanel`, and the role guide's `useGuideRole` (`/help`, `/help/check`), an API's media files read and uploaded through the app (`/media`) and uploaded from the page with progress (`/media/client`), the page's CSP nonce and inline boot scripts (`/document`) and a streaming `entry.server` (`/entry`), the consent screen of an OAuth server: a route's loader and action, the connected apps' list and revoke (`/oauth`) and the decision hook (`/oauth/react`), a user's API keys listed, created behind a step-up and revoked (`/api-keys`) and `/oidc`: a relying party of an external OpenID Connect issuer (authorization code + PKCE, id token validation, a sealed token cookie, refresh and RP-initiated logout)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -166,7 +166,7 @@
|
|
|
166
166
|
},
|
|
167
167
|
"publishConfig": {
|
|
168
168
|
"registry": "https://registry.npmjs.org",
|
|
169
|
-
"access": "
|
|
169
|
+
"access": "restricted"
|
|
170
170
|
},
|
|
171
171
|
"scripts": {
|
|
172
172
|
"build": "bun run ../../build.ts",
|
|
@@ -212,7 +212,7 @@
|
|
|
212
212
|
"@softistx/alxia-openapi": "^0.7.0",
|
|
213
213
|
"@softistx/alxia-proxy": "^0.5.0",
|
|
214
214
|
"@softistx/alxia-secure-headers": "^0.6.0",
|
|
215
|
-
"@
|
|
215
|
+
"@softistx/graphql-client": "^0.9.0",
|
|
216
216
|
"@react-router/dev": "^8.5.0",
|
|
217
217
|
"@softistx/janus": "^0.80.0",
|
|
218
218
|
"@types/bun": "^1.4.4",
|
|
@@ -239,7 +239,7 @@
|
|
|
239
239
|
"peerDependencies": {
|
|
240
240
|
"@softistx/alxia": "^0.28.0",
|
|
241
241
|
"@softistx/alxia-proxy": "^0.5.0",
|
|
242
|
-
"@
|
|
242
|
+
"@softistx/graphql-client": "^0.9.0",
|
|
243
243
|
"isbot": "^5.0.0",
|
|
244
244
|
"jose": "^6.0.0",
|
|
245
245
|
"react": "^19.0.0",
|
|
@@ -256,7 +256,7 @@
|
|
|
256
256
|
"workbox-strategies": "^7.0.0"
|
|
257
257
|
},
|
|
258
258
|
"peerDependenciesMeta": {
|
|
259
|
-
"@
|
|
259
|
+
"@softistx/graphql-client": {
|
|
260
260
|
"optional": true
|
|
261
261
|
},
|
|
262
262
|
"@softistx/alxia-proxy": {
|