@softistx/alxia-react-router 0.83.1 → 0.85.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -10
- package/dist/chunks/{index-6jf7zpxz.js → index-97e6pc48.js} +7 -6
- package/dist/chunks/index-97e6pc48.js.map +11 -0
- package/dist/chunks/{index-5gqcpyyg.js → index-nc5af0fn.js} +15 -4
- package/dist/chunks/index-nc5af0fn.js.map +10 -0
- package/dist/chunks/index-q0ks955b.js +10 -0
- package/dist/chunks/{index-59vhfj6n.js.map → index-q0ks955b.js.map} +2 -2
- 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/pwa/build/build-worker.d.ts +9 -2
- package/dist/pwa/build/build-worker.d.ts.map +1 -1
- package/dist/pwa/build/index.js +1 -1
- package/dist/pwa/build/precache.d.ts +3 -2
- package/dist/pwa/build/precache.d.ts.map +1 -1
- package/dist/pwa/index.d.ts +1 -1
- package/dist/pwa/index.d.ts.map +1 -1
- package/dist/pwa/index.js +1 -1
- package/dist/pwa/model/precache-list.d.ts +12 -2
- package/dist/pwa/model/precache-list.d.ts.map +1 -1
- package/dist/pwa/worker/index.d.ts +1 -0
- package/dist/pwa/worker/index.d.ts.map +1 -1
- package/dist/pwa/worker/index.js +5 -5
- package/dist/pwa/worker/index.js.map +2 -2
- 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/dist/vite/index.d.ts +2 -2
- package/dist/vite/index.js +1 -1
- package/dist/vite/index.js.map +1 -1
- package/docs/guide/errors.md +5 -5
- package/docs/guide/pwa.md +33 -5
- package/docs/guide/subscriptions.md +2 -2
- package/docs/roadmap.md +5 -0
- package/docs/troubleshooting.md +25 -1
- package/package.json +5 -5
- package/dist/chunks/index-59vhfj6n.js +0 -10
- package/dist/chunks/index-5gqcpyyg.js.map +0 -10
- package/dist/chunks/index-6jf7zpxz.js.map +0 -11
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"precache-list.d.ts","sourceRoot":"","sources":["../../../src/pwa/model/precache-list.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,wEAAwE;AACxE,KAAK,cAAc,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE9E,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACvC,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,aAAa,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAKrE,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CASpE;AAED,
|
|
1
|
+
{"version":3,"file":"precache-list.d.ts","sourceRoot":"","sources":["../../../src/pwa/model/precache-list.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,wEAAwE;AACxE,KAAK,cAAc,GAAG;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAE9E,mEAAmE;AACnE,MAAM,MAAM,eAAe,GAAG;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,cAAc,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACvC,CAAC;AAEF,gEAAgE;AAChE,MAAM,MAAM,aAAa,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;CAAE,CAAC;AAKrE,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,eAAe,CASpE;AAED;;;;;GAKG;AACH,MAAM,MAAM,cAAc,GACvB,KAAK,GACL,MAAM,GACN,MAAM,GACN,CAAC,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC;AAUlC;;;GAGG;AACH,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,eAAe,EACzB,MAAM,GAAE,cAAsB,GAC5B,aAAa,EAAE,CAiBjB;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC5B,UAAU,EAAE,SAAS,MAAM,EAAE,EAC7B,OAAO,EAAE,MAAM,EACf,IAAI,SAAa,GACf,aAAa,EAAE,CAQjB"}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* packages (`core`, `expiration`, `navigation-preload`, `precaching`,
|
|
5
5
|
* `routing`, `strategies`, optional peers) are its only package imports.
|
|
6
6
|
*/
|
|
7
|
+
export { injectedPrecache } from './injected';
|
|
7
8
|
export type { ExpirationOptions, WorkerOptions } from './plan';
|
|
8
9
|
export { startWorker } from './start-worker';
|
|
9
10
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pwa/worker/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/pwa/worker/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC"}
|
package/dist/pwa/worker/index.js
CHANGED
|
@@ -3,12 +3,11 @@ import {
|
|
|
3
3
|
isStorable2
|
|
4
4
|
} from "../../chunks/index-zdbqzcjp.js";
|
|
5
5
|
import {
|
|
6
|
-
|
|
7
|
-
} from "../../chunks/index-
|
|
6
|
+
injectedPrecache2
|
|
7
|
+
} from "../../chunks/index-q0ks955b.js";
|
|
8
8
|
import {
|
|
9
9
|
SKIP_WAITING2
|
|
10
10
|
} from "../../chunks/index-rfr02vg4.js";
|
|
11
|
-
|
|
12
11
|
// src/pwa/worker/start-worker.ts
|
|
13
12
|
import {
|
|
14
13
|
clientsClaim,
|
|
@@ -96,7 +95,7 @@ var workerScope = () => globalThis;
|
|
|
96
95
|
|
|
97
96
|
// src/pwa/worker/start-worker.ts
|
|
98
97
|
function startWorker(options) {
|
|
99
|
-
const plan = workerPlan(options,
|
|
98
|
+
const plan = workerPlan(options, injectedPrecache2());
|
|
100
99
|
const scope = workerScope();
|
|
101
100
|
const { contract } = options;
|
|
102
101
|
setCacheNameDetails(plan.cacheNameDetails);
|
|
@@ -137,8 +136,9 @@ function startWorker(options) {
|
|
|
137
136
|
});
|
|
138
137
|
}
|
|
139
138
|
export {
|
|
139
|
+
injectedPrecache2 as injectedPrecache,
|
|
140
140
|
startWorker
|
|
141
141
|
};
|
|
142
142
|
|
|
143
|
-
//# debugId=
|
|
143
|
+
//# debugId=7DA3F7F688E186F864756E2164756E21
|
|
144
144
|
//# sourceMappingURL=index.js.map
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
"import {\n\ttype Caching,\n\ttype CachingOptions,\n\tcachingFor,\n\ttype RequestFacts,\n} from '../model/caching';\nimport type { PrecacheEntry } from '../model/precache-list';\nimport { isStorable } from '../model/storable';\nimport { SKIP_WAITING, type WorkerContract } from '../model/worker-contract';\n\n/** How many files, and for how long, a runtime cache keeps. */\nexport interface ExpirationOptions {\n\tmaxEntries?: number;\n\tmaxAgeSeconds?: number;\n}\n\nexport interface WorkerOptions {\n\t/** The app's contract: cache names, offline page, the worker's URL. */\n\tcontract: WorkerContract;\n\t/** What `cachingFor` reads besides the contract: `never`, `immutable`, `manifestPath`, `serviceWorkerUrl`. */\n\tcaching?: Omit<CachingOptions, 'contract'>;\n\t/** The hashed bundles' cache. `{ maxEntries: 200 }` by default. */\n\tassets?: ExpirationOptions;\n\t/** The other static files' cache. `{ maxEntries: 100, maxAgeSeconds: 30 days }` by default. */\n\tstatic?: ExpirationOptions;\n\t/** Start the worker alongside a page load. `true` by default. */\n\tnavigationPreload?: boolean;\n\t/** The precache list. By default the one the build wrote into the worker. */\n\tprecache?: readonly PrecacheEntry[];\n}\n\nexport type WorkerRoute =\n\t| {\n\t\t\tcaching: 'navigation';\n\t\t\tstrategy: 'network-only';\n\t\t\tfallback: string | undefined;\n\t }\n\t| {\n\t\t\tcaching: 'immutable';\n\t\t\tstrategy: 'cache-first';\n\t\t\tcacheName: string;\n\t\t\texpiration: ExpirationOptions & { maxEntries: number };\n\t }\n\t| {\n\t\t\tcaching: 'static';\n\t\t\tstrategy: 'stale-while-revalidate';\n\t\t\tcacheName: string;\n\t\t\texpiration: ExpirationOptions;\n\t };\n\nexport interface WorkerPlan {\n\tcacheNameDetails: { prefix: string; precache: 'precache'; suffix: string };\n\tprecache: readonly PrecacheEntry[];\n\troutes: readonly WorkerRoute[];\n\tnavigationPreload: boolean;\n}\n\nconst THIRTY_DAYS = 30 * 24 * 60 * 60;\n\n/** What the worker does, decided without Workbox so that it is tested as data. */\nexport function workerPlan(\n\toptions: WorkerOptions,\n\tinjected: readonly PrecacheEntry[] | undefined,\n): WorkerPlan {\n\tconst { contract } = options;\n\tif (!contract) {\n\t\tthrow new TypeError(\n\t\t\t'startWorker(): contract is required: pass defineWorkerContract({ cachePrefix }) from @softistx/alxia-react-router/pwa.',\n\t\t);\n\t}\n\tconst precache = options.precache ?? injected;\n\tif (!precache) {\n\t\tthrow new Error(\n\t\t\t'startWorker(): no precache list. Build this worker with alxia() from @softistx/alxia-react-router/vite (app/service-worker.ts) or buildWorker() from @softistx/alxia-react-router/pwa/build, which write it in.',\n\t\t);\n\t}\n\tconst offlineUrl = contract.offlineUrl;\n\tconst hasOffline = precache.some(\n\t\t(entry) => entry.url.split('?')[0] === offlineUrl,\n\t);\n\treturn {\n\t\tcacheNameDetails: {\n\t\t\tprefix: contract.cachePrefix,\n\t\t\tprecache: 'precache',\n\t\t\tsuffix: contract.cacheVersion,\n\t\t},\n\t\tprecache,\n\t\troutes: [\n\t\t\t{\n\t\t\t\tcaching: 'navigation',\n\t\t\t\tstrategy: 'network-only',\n\t\t\t\tfallback: hasOffline ? offlineUrl : undefined,\n\t\t\t},\n\t\t\t{\n\t\t\t\tcaching: 'immutable',\n\t\t\t\tstrategy: 'cache-first',\n\t\t\t\tcacheName: contract.cacheNames.assets,\n\t\t\t\texpiration: { maxEntries: 200, ...options.assets },\n\t\t\t},\n\t\t\t{\n\t\t\t\tcaching: 'static',\n\t\t\t\tstrategy: 'stale-while-revalidate',\n\t\t\t\tcacheName: contract.cacheNames.static,\n\t\t\t\texpiration: {\n\t\t\t\t\tmaxEntries: 100,\n\t\t\t\t\tmaxAgeSeconds: THIRTY_DAYS,\n\t\t\t\t\t...options.static,\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\tnavigationPreload: options.navigationPreload ?? true,\n\t};\n}\n\n/** Whether a request is answered the way `caching` says. */\nexport function matcher(\n\tcaching: Caching,\n\torigin: () => string,\n\toptions: WorkerOptions,\n): (o: { request: RequestFacts }) => boolean {\n\treturn ({ request }) =>\n\t\tcachingFor(request, origin(), {\n\t\t\t...options.caching,\n\t\t\tcontract: options.contract,\n\t\t}) === caching;\n}\n\n/** Stores only what `isStorable` accepts: a public, same-origin 200. */\nexport const storableOnly = {\n\tasync cacheWillUpdate({\n\t\tresponse,\n\t}: {\n\t\tresponse: Response;\n\t}): Promise<Response | null> {\n\t\treturn isStorable(response) ? response : null;\n\t},\n};\n\nexport function isSkipWaiting(data: unknown): boolean {\n\treturn (data as { type?: unknown } | null | undefined)?.type === SKIP_WAITING;\n}\n\n/** Deletes the caches an earlier version of the contract owned. */\nexport async function deleteObsoleteCaches(\n\tcontract: Pick<WorkerContract, 'obsoleteCaches'>,\n\tstorage: Pick<CacheStorage, 'keys' | 'delete'>,\n): Promise<void> {\n\tconst names = await storage.keys();\n\tawait Promise.all(\n\t\tcontract.obsoleteCaches(names).map((name) => storage.delete(name)),\n\t);\n}\n",
|
|
7
7
|
"/**\n * The part of the service worker's global scope that `startWorker` reads,\n * declared here so no WebWorker-only type reaches the package's declarations\n * (the DOM lib has no `ServiceWorkerGlobalScope`).\n */\nexport interface WorkerScope {\n\treadonly location: { readonly origin: string };\n\tskipWaiting(): Promise<void>;\n\taddEventListener(\n\t\ttype: 'activate' | 'message',\n\t\tlistener: (event: {\n\t\t\tdata?: unknown;\n\t\t\twaitUntil(promise: Promise<unknown>): void;\n\t\t}) => void,\n\t): void;\n}\n\n/** The worker's scope. Called only inside `startWorker`, never at module load. */\nexport const workerScope = (): WorkerScope =>\n\tglobalThis as unknown as WorkerScope;\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": "
|
|
10
|
-
"debugId": "
|
|
9
|
+
"mappings": ";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAKA;AACA;AACA;AACA;AACA;AAAA;AAAA;AAAA;AAAA;;;ACgDA,IAAM,cAAc,KAAK,KAAK,KAAK;AAG5B,SAAS,UAAU,CACzB,SACA,UACa;AAAA,EACb,QAAQ,aAAa;AAAA,EACrB,IAAI,CAAC,UAAU;AAAA,IACd,MAAM,IA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,MAAM,CAAC;AAAA,GACtD;AAAA,EACD,MAAM,iBAAiB,WAAW,CAAC,UAAU;AAAA,IAC5C,IAAI,cAAc,MAAM,IAAI;AAAA,MAAQ,MAAM,YAAY;AAAA,GACtD;AAAA;",
|
|
10
|
+
"debugId": "7DA3F7F688E186F864756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -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;AAA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Q,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,"file":"use-live-subscription.d.ts","sourceRoot":"","sources":["../../../src/subscription/react/use-live-subscription.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAGhE,OAAO,EAAwB,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAErE,MAAM,MAAM,YAAY,GAAG;IAC1B,6DAA6D;IAC7D,UAAU,EAAE,MAAM,IAAI,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,0BAA0B,CAAC,MAAM,IAAI;IAChD,8JAA8J;IAC9J,KAAK,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC;IACnE,8GAA8G;IAC9G,SAAS,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC,GAAG,SAAS,CAAC;IACpD,iEAAiE;IACjE,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,KAAK,IAAI,CAAC;IAC1D,6LAA6L;IAC7L,UAAU,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;IACtC,qCAAqC;IACrC,IAAI,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC9B,MAAM,EAAE,UAAU,CAAC;IACnB,oEAAoE;IACpE,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB,6DAA6D;IAC7D,UAAU,EAAE,MAAM,IAAI,CAAC;CACvB,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,EAC7E,QAAQ,EAAE,eAAe,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7C,SAAS,EAAE,UAAU,EACrB,OAAO,EAAE,0BAA0B,CAAC,MAAM,CAAC,GACzC,gBAAgB,CAqClB"}
|
package/dist/vite/index.d.ts
CHANGED
|
@@ -14,8 +14,8 @@ export interface AlxiaOptions {
|
|
|
14
14
|
/**
|
|
15
15
|
* The service worker, bundled into `build/client/service-worker.js` after
|
|
16
16
|
* `react-router build`, with its precache list: a file relative to Vite's
|
|
17
|
-
* root, or options (`file`, `contract`, `offline`, `
|
|
18
|
-
* `minify`). By default `app/service-worker.ts` when it exists, and
|
|
17
|
+
* root, or options (`file`, `contract`, `offline`, `precacheRoutes`,
|
|
18
|
+
* `precacheAssets`, `minify`). By default `app/service-worker.ts` when it exists, and
|
|
19
19
|
* nothing without it; `false` builds none. Needs Bun.
|
|
20
20
|
*/
|
|
21
21
|
readonly worker?: false | string | AlxiaWorkerOptions;
|
package/dist/vite/index.js
CHANGED
package/dist/vite/index.js.map
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/vite/index.ts", "../src/vite/bun.ts", "../src/vite/bundle.ts", "../src/vite/compress.ts", "../src/vite/config.ts", "../src/vite/node.ts", "../src/vite/socket.ts", "../src/vite/dev.ts", "../src/vite/hosts.ts", "../src/vite/inline.ts", "../src/vite/preview.ts", "../src/vite/runtime.ts", "../src/vite/worker.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"/**\n * `@softistx/alxia-react-router/vite`: `alxia()`, the Vite plugin that makes alxia\n * the server of a React Router app, under `react-router dev` and in\n * `react-router build`, with or without an `app/server.ts`.\n */\nimport { join, relative } from 'node:path';\n// Types only: the plugin runs on whichever Vite the app has, never on a\n// copy of this package's own.\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { ssrEnvironment } from './bundle';\nimport { type PrecompressOptions, precompressClient } from './compress';\nimport {\n\tclientPath,\n\tcontextOf,\n\tDEFAULT,\n\tisChildCompiler,\n\tSERVER,\n\tserverBuildOptions,\n\tserverFile,\n} from './config';\nimport { serveDev } from './dev';\nimport { NAME, PASS_THROUGH, serverEntry } from './entry';\nimport { hostsToAdd, wantedHosts } from './hosts';\nimport { inlineAliases, inlinedFile } from './inline';\nimport { servePreview } from './preview';\nimport { requireBun } from './runtime';\nimport { type AlxiaWorkerOptions, buildAppWorker } from './worker';\n\nexport type { PrecompressOptions } from './compress';\nexport type { AlxiaWorkerOptions } from './worker';\n\nexport interface AlxiaOptions {\n\t/**\n\t * The server file, relative to Vite's root: a module whose default export\n\t * is `createServer()` from `@softistx/alxia-react-router`. By default `server.ts`\n\t * in React Router's app directory, `app/server.ts`, when it exists, and\n\t * otherwise `createServer()` with no options.\n\t */\n\treadonly entry?: string;\n\t/**\n\t * The service worker, bundled into `build/client/service-worker.js` after\n\t * `react-router build`, with its precache list: a file relative to Vite's\n\t * root, or options (`file`, `contract`, `offline`, `
|
|
5
|
+
"/**\n * `@softistx/alxia-react-router/vite`: `alxia()`, the Vite plugin that makes alxia\n * the server of a React Router app, under `react-router dev` and in\n * `react-router build`, with or without an `app/server.ts`.\n */\nimport { join, relative } from 'node:path';\n// Types only: the plugin runs on whichever Vite the app has, never on a\n// copy of this package's own.\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport { ssrEnvironment } from './bundle';\nimport { type PrecompressOptions, precompressClient } from './compress';\nimport {\n\tclientPath,\n\tcontextOf,\n\tDEFAULT,\n\tisChildCompiler,\n\tSERVER,\n\tserverBuildOptions,\n\tserverFile,\n} from './config';\nimport { serveDev } from './dev';\nimport { NAME, PASS_THROUGH, serverEntry } from './entry';\nimport { hostsToAdd, wantedHosts } from './hosts';\nimport { inlineAliases, inlinedFile } from './inline';\nimport { servePreview } from './preview';\nimport { requireBun } from './runtime';\nimport { type AlxiaWorkerOptions, buildAppWorker } from './worker';\n\nexport type { PrecompressOptions } from './compress';\nexport type { AlxiaWorkerOptions } from './worker';\n\nexport interface AlxiaOptions {\n\t/**\n\t * The server file, relative to Vite's root: a module whose default export\n\t * is `createServer()` from `@softistx/alxia-react-router`. By default `server.ts`\n\t * in React Router's app directory, `app/server.ts`, when it exists, and\n\t * otherwise `createServer()` with no options.\n\t */\n\treadonly entry?: string;\n\t/**\n\t * The service worker, bundled into `build/client/service-worker.js` after\n\t * `react-router build`, with its precache list: a file relative to Vite's\n\t * root, or options (`file`, `contract`, `offline`, `precacheRoutes`,\n\t * `precacheAssets`, `minify`). By default `app/service-worker.ts` when it exists, and\n\t * nothing without it; `false` builds none. Needs Bun.\n\t */\n\treadonly worker?: false | string | AlxiaWorkerOptions;\n\t/**\n\t * Writes `.br` and `.gz` copies beside the client build's compressible\n\t * files (JavaScript, CSS, HTML, SVG, JSON, text, WebAssembly, source\n\t * maps, fonts) of at least `minSize` bytes (1024), after the service\n\t * worker is built: the server sends them to a browser that accepts them.\n\t * On by default; `false` writes none.\n\t */\n\treadonly precompress?: false | PrecompressOptions;\n\t/**\n\t * Hosts added to Vite's `server.allowedHosts` and `preview.allowedHosts`,\n\t * beside the comma-separated `DEV_ALLOWED_HOSTS` variable and the hosts\n\t * the app's own config sets (a leading dot allows the subdomains too).\n\t * For a dev tunnel on a public hostname. Never allows every host: an app\n\t * that set `allowedHosts: true` keeps it. Nothing by default.\n\t */\n\treadonly allowedHosts?: readonly string[];\n}\n\nconst RESOLVED_SERVER = `\\0${SERVER}`;\nconst RESOLVED_DEFAULT = `\\0${DEFAULT}`;\n\n/**\n * Whether there is a server to be: not in the Vite server React Router\n * compiles route modules in, nor in a single-page app. Throws when the\n * server build would be split in several.\n */\nfunction servesApp(resolved: ResolvedConfig): boolean {\n\t// React Router compiles route modules in a Vite server of its own,\n\t// with every plugin but its own: there is nothing to serve there.\n\tif (isChildCompiler(resolved)) return false;\n\tconst rr = contextOf(resolved);\n\t// A single-page app has no server to be.\n\tif (rr.ssr && rr.serverBundles !== undefined) {\n\t\tthrow new Error(\n\t\t\t`${NAME}: serverBundles splits React Router's server build in several, and alxia serves one. Remove serverBundles from react-router.config.ts.`,\n\t\t);\n\t}\n\treturn rr.ssr;\n}\n\n/**\n * The Vite plugin that makes alxia the server of a React Router app,\n * anywhere in `plugins`:\n *\n * ```ts\n * export default defineConfig({ plugins: [alxia(), reactRouter()] });\n * ```\n *\n * - **`react-router dev`**: every request Vite does not answer itself —\n * pages, data, `/api` — goes to the server, loaded through Vite's SSR\n * runner. HMR, an edit to the server, the app's own context keys and\n * its WebSocket routes work, with no restart.\n * - **`react-router build`**: `build/server/index.js` is the server, with\n * React Router's build inside it. `bun build/server/index.js` listens on\n * `PORT` (3000) and `HOST` (`0.0.0.0`); importing it starts nothing.\n * - **`vite preview`**: every request goes to that built server, as it\n * would answer it; so does React Router's prerendering.\n * - **Built for Bun**: the `ssr` environment resolves packages with the\n * `bun` export condition, leaves `bun` and `bun:*` external, and targets\n * `esnext` unless the app set a target. What the app set is kept.\n * - **Self-contained**: `react-router build` bundles every package into\n * `build/server/index.js` (`ssr.noExternal: true`), so `build/` runs with\n * no `node_modules`. `ssr.external` keeps the packages it names external,\n * and `ssr.external: true` all of them.\n *\n * The server is `app/server.ts`'s default export, `createServer()` from\n * `@softistx/alxia-react-router`, or without that file `createServer()` as it is.\n */\nexport function alxia(options: AlxiaOptions = {}): Plugin {\n\tlet config: ResolvedConfig | undefined;\n\tlet enabled = true;\n\n\treturn {\n\t\tname: NAME,\n\t\t// Before React Router's plugin, wherever it is listed: its config reads\n\t\t// the server build's input from this one's, and its dev middleware,\n\t\t// which would render the pages without alxia, comes after this one's.\n\t\tenforce: 'pre',\n\t\tconfig(userConfig, env) {\n\t\t\tconst wanted = wantedHosts(\n\t\t\t\toptions.allowedHosts,\n\t\t\t\tprocess.env['DEV_ALLOWED_HOSTS'],\n\t\t\t);\n\t\t\tconst server = hostsToAdd(userConfig.server?.allowedHosts, wanted);\n\t\t\t// Preview inherits the server's list when it has none: it then takes\n\t\t\t// the server's hosts along with the added ones.\n\t\t\tconst own = userConfig.preview?.allowedHosts;\n\t\t\tconst inherited = userConfig.server?.allowedHosts;\n\t\t\tconst preview =\n\t\t\t\twanted.length > 0 &&\n\t\t\t\town === undefined &&\n\t\t\t\tinherited !== undefined &&\n\t\t\t\tinherited !== true\n\t\t\t\t\t? hostsToAdd(undefined, [...inherited, ...wanted])\n\t\t\t\t\t: hostsToAdd(own ?? inherited, wanted);\n\t\t\tconst hosts = {\n\t\t\t\t...(server === undefined ? {} : { server: { allowedHosts: server } }),\n\t\t\t\t...(preview === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { preview: { allowedHosts: preview } }),\n\t\t\t};\n\t\t\tif (env.command === 'serve') {\n\t\t\t\treturn { ...hosts, ...inlineAliases() };\n\t\t\t}\n\t\t\tif (env.command !== 'build') return;\n\t\t\t// Vite 7's types know neither `rolldownVersion` nor `rolldownOptions`.\n\t\t\tconst meta = this.meta as { readonly rolldownVersion?: string };\n\t\t\tconst bundler = serverBuildOptions(meta.rolldownVersion !== undefined);\n\t\t\treturn { environments: { ssr: { build: bundler as never } } };\n\t\t},\n\t\tconfigEnvironment(name, options, env) {\n\t\t\t// After every config hook, React Router's included: the server\n\t\t\t// environment as the app and the plugins left it, built for Bun.\n\t\t\t// An app that chose `ssr.target: 'webworker'` keeps Vite's own.\n\t\t\tif (name !== 'ssr' || env.isSsrTargetWebworker === true) return;\n\t\t\treturn ssrEnvironment(options, env.command);\n\t\t},\n\t\tconfigResolved(resolved) {\n\t\t\tconfig = resolved;\n\t\t\tenabled = servesApp(resolved);\n\t\t},\n\t\tresolveId(id) {\n\t\t\tif (id === SERVER) return RESOLVED_SERVER;\n\t\t\tif (id === DEFAULT) return RESOLVED_DEFAULT;\n\t\t\t// An absolute path is never external: see inline.ts.\n\t\t\tif (this.environment?.name === 'ssr') return inlinedFile(id);\n\t\t\treturn undefined;\n\t\t},\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER && id !== RESOLVED_DEFAULT) return;\n\t\t\tif (config === undefined) return;\n\t\t\t// Disabled, a single-page app: React Router still builds its server\n\t\t\t// build, to render index.html, from this input.\n\t\t\tif (!enabled) return PASS_THROUGH;\n\t\t\tconst dev = config.command === 'serve';\n\t\t\tconst file =\n\t\t\t\tid === RESOLVED_DEFAULT ? undefined : serverFile(options.entry, config);\n\t\t\treturn serverEntry({\n\t\t\t\tfile,\n\t\t\t\tlabel: file === undefined ? '' : relative(config.root, file),\n\t\t\t\tdev,\n\t\t\t\tclient: dev ? undefined : clientPath(config),\n\t\t\t});\n\t\t},\n\t\tbuildApp: {\n\t\t\t// After React Router's builder: its client build, the one the worker reads.\n\t\t\torder: 'post',\n\t\t\tasync handler() {\n\t\t\t\tif (config === undefined) return;\n\t\t\t\tawait buildAppWorker(config, options.worker);\n\t\t\t\tif (!enabled || options.precompress === false) return;\n\t\t\t\tconst done = await precompressClient(\n\t\t\t\t\tjoin(contextOf(config).buildDirectory, 'client'),\n\t\t\t\t\toptions.precompress,\n\t\t\t\t);\n\t\t\t\tconfig.logger.info(\n\t\t\t\t\t`✓ ${done.files} client files precompressed (${(done.bytes / 1024).toFixed(0)} kB → ${(done.brotliBytes / 1024).toFixed(0)} kB brotli)`,\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tconfigureServer(server) {\n\t\t\tif (!enabled) return;\n\t\t\trequireBun('react-router dev');\n\t\t\treturn serveDev(server, options.entry);\n\t\t},\n\t\tconfigurePreviewServer(server) {\n\t\t\tif (!enabled) return;\n\t\t\t// React Router prerenders through a preview server of its own,\n\t\t\t// resolved as `serve` too: the message cannot tell the two apart.\n\t\t\trequireBun(\n\t\t\t\t'vite preview, or a react-router build that prerenders,',\n\t\t\t\t'bun --bun vite preview or bun --bun react-router build',\n\t\t\t);\n\t\t\t// Before Vite's own files: the built server answers every request.\n\t\t\tservePreview(server);\n\t\t},\n\t};\n}\n",
|
|
6
6
|
"/**\n * The server build, for Bun: what the plugin adds to Vite's `ssr`\n * environment so that `build/server/index.js` is built for the runtime\n * that runs it, and so is the module the dev server loads.\n */\nimport { builtinModules } from 'node:module';\nimport type { EnvironmentOptions } from 'vite';\n\n/** The export condition Bun resolves a package by, and the plugin adds. */\nconst BUN_CONDITION = 'bun';\n\n/**\n * Vite's own builtins for a server environment (its `nodeLikeBuiltins`),\n * which it uses when the config names none: Node's modules, `node:*` and\n * `bun:*`. Bare `bun` is among Node's modules only when Vite runs on Bun.\n */\nconst VITE_BUILTINS: readonly (string | RegExp)[] = [\n\t...builtinModules.filter((id) => !id.includes(':')),\n\t/^node:/,\n\t/^bun:/,\n];\n\n/**\n * Vite's default conditions for a server environment, and for its\n * externals, which it uses when the config names none. React Router's\n * plugin always names them; these are for a config where nothing did.\n */\nconst VITE_CONDITIONS = ['module', 'node', 'development|production'];\nconst VITE_EXTERNAL_CONDITIONS = ['node', 'module-sync'];\n\n/** Bun's own modules, which no bundler should try to resolve: `bun` and `bun:*`. */\nconst BUN_BUILTINS: readonly (string | RegExp)[] = [BUN_CONDITION, /^bun:/];\n\n/**\n * What to merge into `present` so that it holds `wanted`: Vite replaces its\n * default with any value set, so an unset option gets the default too.\n * Strings compare by value, patterns by source.\n */\nfunction adding<T extends string | RegExp>(\n\tpresent: readonly T[] | undefined,\n\tfallback: readonly T[],\n\twanted: readonly T[],\n): T[] {\n\tconst list = present ?? fallback;\n\tconst has = (item: T) =>\n\t\tlist.some((other) =>\n\t\t\ttypeof item === 'string'\n\t\t\t\t? other === item\n\t\t\t\t: other instanceof RegExp && other.source === item.source,\n\t\t);\n\treturn [\n\t\t...(present === undefined ? fallback : []),\n\t\t...wanted.filter((item) => !has(item)),\n\t];\n}\n\n/**\n * What the plugin adds to the `ssr` environment, given its options as the\n * config and every plugin's `config` hook left them. Vite merges the\n * result into them, concatenating arrays, so what the app set is kept:\n *\n * - `resolve.conditions` and `resolve.externalConditions` gain `bun`, so a\n * package that exports a `bun` variant is bundled, and checked, as Bun\n * would load it. Which variant wins stays the package's own order.\n * - `resolve.builtins` gains `bun` and `bun:*`: left external, whichever\n * runtime runs Vite. Vite's own builtins are kept when the app names none.\n * - `build.target` is `esnext`, Bun's, unless the app set one, at the top\n * level or on the environment.\n *\n * `ssr.target` stays `node`: Bun runs Node's modules, and `webworker`\n * would bundle every dependency with the browser's conditions. An app that\n * sets `webworker` itself gets none of this: the plugin leaves that\n * environment to Vite's own defaults.\n */\nexport function bunEnvironment(\n\toptions: EnvironmentOptions,\n): EnvironmentOptions {\n\tconst resolve = options.resolve ?? {};\n\tconst added: EnvironmentOptions = {\n\t\tresolve: {\n\t\t\tconditions: adding(resolve.conditions, VITE_CONDITIONS, [BUN_CONDITION]),\n\t\t\texternalConditions: adding(\n\t\t\t\tresolve.externalConditions,\n\t\t\t\tVITE_EXTERNAL_CONDITIONS,\n\t\t\t\t[BUN_CONDITION],\n\t\t\t),\n\t\t\tbuiltins: adding(resolve.builtins, VITE_BUILTINS, BUN_BUILTINS),\n\t\t},\n\t};\n\tif (options.build?.target === undefined) {\n\t\tadded.build = { target: 'esnext' };\n\t}\n\treturn added;\n}\n",
|
|
7
7
|
"/**\n * The server build, self-contained: every dependency bundled into\n * `build/server/index.js`, so that running it needs `build/` and Bun, and\n * no `node_modules`. A Docker image's final stage copies `build/` alone.\n */\nimport type { EnvironmentOptions } from 'vite';\nimport { bunEnvironment } from './bun';\n\n/**\n * What the plugin adds to the `ssr` environment under `react-router build`,\n * given its options as the config and the plugins left them:\n * `resolve.noExternal: true`, every package bundled. Never in dev, where\n * Vite's SSR runner loads the packages from `node_modules`.\n *\n * What the app set wins:\n *\n * - `ssr.external: ['sharp']`, or the same on `environments.ssr.resolve`,\n * keeps those packages external, imported from `node_modules` at\n * runtime: Vite reads `external` before `noExternal`. Bun's own modules,\n * `bun` and `bun:*`, and Node's are builtins, external whatever this says.\n * - `ssr.external: true` keeps every package external, Vite's own default:\n * the plugin adds nothing then.\n * - `ssr.noExternal`, a list, is a subset of everything: it changes nothing.\n *\n * React Router's own plugin reads `noExternal: true` and adds no externals\n * of its own; it runs after this one, which is `enforce: 'pre'`.\n */\nexport function bundledEnvironment(\n\toptions: EnvironmentOptions,\n): EnvironmentOptions | undefined {\n\tif (options.resolve?.external === true) return undefined;\n\treturn { resolve: { noExternal: true } };\n}\n\n/**\n * Everything the plugin adds to the `ssr` environment: built for Bun under\n * either command, and self-contained under `build` alone. In dev, Vite's\n * SSR runner loads the packages from `node_modules`.\n */\nexport function ssrEnvironment(\n\toptions: EnvironmentOptions,\n\tcommand: 'build' | 'serve',\n): EnvironmentOptions {\n\tconst added = bunEnvironment(options);\n\tconst bundled = command === 'build' ? bundledEnvironment(options) : undefined;\n\tif (bundled === undefined) return added;\n\treturn { ...added, resolve: { ...added.resolve, ...bundled.resolve } };\n}\n",
|
|
8
8
|
"/**\n * The client build's compressed copies: `app.js.br` and `app.js.gz` beside\n * every compressible file, which `app.static(…, { precompressed })` serves\n * to a browser that accepts them, so the server never compresses on a request.\n */\nimport { readdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport { extname, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { brotliCompress, constants, gzip } from 'node:zlib';\n\nconst brotli = promisify(brotliCompress);\nconst deflate = promisify(gzip);\n\n/** What compresses well: text, and the formats built on it. */\nconst COMPRESSIBLE = new Set([\n\t'.js',\n\t'.mjs',\n\t'.cjs',\n\t'.css',\n\t'.html',\n\t'.htm',\n\t'.svg',\n\t'.json',\n\t'.map',\n\t'.txt',\n\t'.xml',\n\t'.webmanifest',\n\t'.wasm',\n\t'.ico',\n\t'.ttf',\n\t'.otf',\n\t'.eot',\n]);\n\nexport interface PrecompressOptions {\n\t/** The smallest file, in bytes, that gets copies: 1024 by default. */\n\treadonly minSize?: number;\n}\n\nexport interface Precompressed {\n\t/** The files that got copies. */\n\treadonly files: number;\n\t/** Their size before, and the size of their brotli copies. */\n\treadonly bytes: number;\n\treadonly brotliBytes: number;\n}\n\nasync function* walk(dir: string): AsyncGenerator<string> {\n\tfor (const entry of await readdir(dir, { withFileTypes: true })) {\n\t\tconst path = join(dir, entry.name);\n\t\tif (entry.isDirectory()) yield* walk(path);\n\t\telse if (entry.isFile()) yield path;\n\t}\n}\n\n/**\n * Writes `<file>.br` and `<file>.gz` beside each compressible file of\n * `client` of at least `minSize` bytes, whichever is smaller than the file\n * itself. Brotli at its best quality: it runs once, at build time.\n */\nexport async function precompressClient(\n\tclient: string,\n\toptions: PrecompressOptions = {},\n): Promise<Precompressed> {\n\tconst minSize = options.minSize ?? 1024;\n\tlet files = 0;\n\tlet bytes = 0;\n\tlet brotliBytes = 0;\n\tfor await (const path of walk(client)) {\n\t\tif (!COMPRESSIBLE.has(extname(path).toLowerCase())) continue;\n\t\tconst body = await readFile(path);\n\t\tif (body.length < minSize) continue;\n\t\tconst [br, gz] = await Promise.all([\n\t\t\tbrotli(body, {\n\t\t\t\tparams: {\n\t\t\t\t\t[constants.BROTLI_PARAM_QUALITY]: constants.BROTLI_MAX_QUALITY,\n\t\t\t\t\t[constants.BROTLI_PARAM_SIZE_HINT]: body.length,\n\t\t\t\t},\n\t\t\t}),\n\t\t\tdeflate(body, { level: 9 }),\n\t\t]);\n\t\tlet written = false;\n\t\tfor (const [extension, copy] of [\n\t\t\t['br', br],\n\t\t\t['gz', gz],\n\t\t] as const) {\n\t\t\tif (copy.length < body.length) {\n\t\t\t\tawait writeFile(`${path}.${extension}`, copy);\n\t\t\t\twritten = true;\n\t\t\t} else {\n\t\t\t\t// A copy left by an earlier build would be stale.\n\t\t\t\tawait rm(`${path}.${extension}`, { force: true });\n\t\t\t}\n\t\t}\n\t\tif (!written) continue;\n\t\tfiles += 1;\n\t\tbytes += body.length;\n\t\tbrotliBytes += Math.min(br.length, body.length);\n\t}\n\treturn { files, bytes, brotliBytes };\n}\n",
|
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,
|
package/docs/guide/pwa.md
CHANGED
|
@@ -34,7 +34,7 @@ globals only inside its functions, never at load.
|
|
|
34
34
|
| `/pwa` | every runtime: the contract, `cachingFor`, `isStorable`, `registerServiceWorker`, `createUpdateNotice`, `manifestHref`, `webAppManifest`, `clearAppCaches`, the precache parts and `SERVICE_WORKER_URL` | nothing: it imports nothing |
|
|
35
35
|
| `/pwa/react` | the page's hooks: `useServiceWorker`, `useUpdateNotice`, `useOnline` | `react` (`^19`), an optional peer. Keep it out of the worker, which would bundle React |
|
|
36
36
|
| `/pwa/server` | the server file alone: `noCache` and `revalidated` | `@softistx/alxia`, a peer the package already has |
|
|
37
|
-
| `/pwa/worker` | the service worker bundle alone: `startWorker` | the six `workbox-*` packages (`core`, `expiration`, `navigation-preload`, `precaching`, `routing`, `strategies`), optional peers (`^7`) |
|
|
37
|
+
| `/pwa/worker` | the service worker bundle alone: `startWorker`, `injectedPrecache` | the six `workbox-*` packages (`core`, `expiration`, `navigation-preload`, `precaching`, `routing`, `strategies`), optional peers (`^7`) |
|
|
38
38
|
| `/pwa/build` | a build pipeline of your own: `buildWorker` | Bun; Node's built-ins are its only imports, and it reads `Bun` only inside the function. The Workbox peers must be installed to bundle the worker |
|
|
39
39
|
|
|
40
40
|
The main entry, `@softistx/alxia-react-router`, is not for those: it imports
|
|
@@ -123,6 +123,8 @@ network; `clientsClaim()` makes a first install control the open pages at
|
|
|
123
123
|
once; an update waits until the page posts `SKIP_WAITING`; and on `activate`
|
|
124
124
|
the caches the contract no longer owns (`obsoleteCaches`) are deleted.
|
|
125
125
|
|
|
126
|
+
`injectedPrecache()` (from `/pwa/worker`) returns the list the build wrote in, or `undefined`: an app can filter it and pass the result as `precache`.
|
|
127
|
+
|
|
126
128
|
The precache list is the `precache` option, or else
|
|
127
129
|
`globalThis.__ALXIA_PRECACHE__`, which the build writes into the bundle (a
|
|
128
130
|
worker bundled some other way passes `precache`, or defines that global in its
|
|
@@ -249,7 +251,32 @@ export default defineConfig({
|
|
|
249
251
|
| left out | `app/service-worker.ts`, when it exists |
|
|
250
252
|
| a string | another file, relative to Vite's root; the build fails when it is not there |
|
|
251
253
|
| `false` | no worker is built |
|
|
252
|
-
| an object | `file` (as the string), `contract`, `offline`, `precacheAssets` and `minify`, as in `buildWorker`'s table below |
|
|
254
|
+
| an object | `file` (as the string), `contract`, `offline`, `precacheRoutes`, `precacheAssets` and `minify`, as in `buildWorker`'s table below |
|
|
255
|
+
|
|
256
|
+
To keep the first-visit download to the shell, precache only the client
|
|
257
|
+
entry and the root route; the other routes' chunks are cached when visited:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
// vite.config.ts
|
|
261
|
+
import { alxia } from '@softistx/alxia-react-router/vite';
|
|
262
|
+
import { reactRouter } from '@react-router/dev/vite';
|
|
263
|
+
import { defineConfig } from 'vite';
|
|
264
|
+
|
|
265
|
+
export default defineConfig({
|
|
266
|
+
plugins: [reactRouter(), alxia({ worker: { precacheRoutes: 'root' } })],
|
|
267
|
+
});
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
`startWorker` can also filter the list the build wrote in:
|
|
271
|
+
|
|
272
|
+
```ts
|
|
273
|
+
// app/service-worker.ts
|
|
274
|
+
import { injectedPrecache, startWorker } from '@softistx/alxia-react-router/pwa/worker';
|
|
275
|
+
|
|
276
|
+
startWorker({
|
|
277
|
+
precache: (injectedPrecache() ?? []).filter(({ url }) => !url.endsWith('.css')),
|
|
278
|
+
});
|
|
279
|
+
```
|
|
253
280
|
|
|
254
281
|
The object form takes the options of [`buildWorker`](#with-buildworker), but
|
|
255
282
|
`root` and `client`, which the plugin knows. Its `contract` must be the same
|
|
@@ -299,7 +326,7 @@ console.log(
|
|
|
299
326
|
|
|
300
327
|
Run it as `bun scripts/build-worker.ts` after `react-router build`. The list is
|
|
301
328
|
the offline page, revisioned by its content (a changed page installs a new
|
|
302
|
-
worker), then every route
|
|
329
|
+
worker), then the routes' code (every route by default, see `precacheRoutes`), then the `precacheAssets` files. A new build
|
|
303
330
|
changes the list, so the worker's bytes, so the browser installs it.
|
|
304
331
|
|
|
305
332
|
| option | default | |
|
|
@@ -309,6 +336,7 @@ changes the list, so the worker's bytes, so the browser installs it.
|
|
|
309
336
|
| `client` | `build/client` | the client build, relative to `root` |
|
|
310
337
|
| `contract` | `SERVICE_WORKER_URL`, `OFFLINE_URL` | `{ serviceWorkerUrl, offlineUrl }`: where the worker is written and which offline page is precached. Pass the same object `startWorker` gets (the app's contract), or the build and the worker can disagree |
|
|
311
338
|
| `offline` | `true` | precache the offline page, which must exist in the client build ([`public/offline.html`](#the-offline-page)) |
|
|
339
|
+
| `precacheRoutes` | `"all"` | which routes' code is precached: `"all"`, `"root"` (the client entry and the `root` route, with their imports and CSS, the manifest, the offline page and `precacheAssets`), or a `RegExp` or `(routeId) => boolean` over the route ids (`routes/items`), which adds the matching routes to the entry and `root`, always kept. The other routes' chunks are cached when first visited, so an app with many routes keeps a short first-visit download. A navigation offline to a route not precached and never visited shows the offline page |
|
|
312
340
|
| `precacheAssets` | none | a regex over the names in `build/client/assets`, such as fonts; `fontPrecachePattern(['inter-latin', …])` from `/pwa` builds the font one |
|
|
313
341
|
| `minify` | `true` | |
|
|
314
342
|
|
|
@@ -318,7 +346,7 @@ Its errors are in [the troubleshooting page](../troubleshooting.md#buildworker-e
|
|
|
318
346
|
|
|
319
347
|
### The parts
|
|
320
348
|
|
|
321
|
-
|
|
349
|
+
By default a worker precaches the code of every route (`precacheRoutes: "all"`), so a client navigation offline to
|
|
322
350
|
a route never visited still finds its modules. Set
|
|
323
351
|
`routeDiscovery: { mode: 'initial' }` in `react-router.config.ts` as well,
|
|
324
352
|
or the navigation asks `/__manifest` for the route and shows the offline page
|
|
@@ -358,7 +386,7 @@ export const precache = [
|
|
|
358
386
|
];
|
|
359
387
|
```
|
|
360
388
|
|
|
361
|
-
`precacheList(manifest)` returns the manifest's own file first, then the
|
|
389
|
+
`precacheList(manifest, routes?)` (`routes` is a `PrecacheRoutes`: `'all'` by default, `'root'`, a RegExp or a predicate over route ids) returns the manifest's own file first, then the
|
|
362
390
|
entry's and every route's module, imports and CSS, each once, as
|
|
363
391
|
`{ url, revision: null }`: a hashed name needs no revision. Only `/assets/`
|
|
364
392
|
files named `name-<8 hash characters>.js` or `.css` are kept, so a sprite or
|
|
@@ -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/roadmap.md
CHANGED
|
@@ -133,6 +133,11 @@ Nothing queued; see Later.
|
|
|
133
133
|
|
|
134
134
|
### Unreleased
|
|
135
135
|
|
|
136
|
+
- **`precacheRoutes` for the worker.** `alxia({ worker: { precacheRoutes } })`
|
|
137
|
+
and `buildWorker` precache every route (`"all"`, the default), only the
|
|
138
|
+
client entry and the root route (`"root"`), or those plus the routes a
|
|
139
|
+
RegExp or predicate keeps. `injectedPrecache()` is exported from
|
|
140
|
+
`/pwa/worker`. See the [PWA guide](guide/pwa.md#with-buildworker).
|
|
136
141
|
- **`useStepUpRunner` in `@alxia/react-router/session/react`.** `run(request)`
|
|
137
142
|
posts a sensitive action and resolves with its outcome or `'cancelled'`;
|
|
138
143
|
the step-up opens and the same request is replayed once confirmed. See the
|
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
|
|
@@ -2901,6 +2921,10 @@ worker never caches that request.
|
|
|
2901
2921
|
**Fix:** set `routeDiscovery: { mode: 'initial' }` in `react-router.config.ts`,
|
|
2902
2922
|
so the client has every route from its first load.
|
|
2903
2923
|
|
|
2924
|
+
The same page also shows when `precacheRoutes` leaves the route out of the
|
|
2925
|
+
precache (`'root'`, a filter) and the route was never visited online: widen
|
|
2926
|
+
`precacheRoutes` to include it, or visit it once online.
|
|
2927
|
+
|
|
2904
2928
|
### An update waits an hour
|
|
2905
2929
|
|
|
2906
2930
|
A new worker is deployed and tabs still run the old one for up to an hour.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@softistx/alxia-react-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.85.0",
|
|
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": {
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
// src/pwa/worker/injected.ts
|
|
2
|
-
var PRECACHE_DEFINE = "globalThis.__ALXIA_PRECACHE__";
|
|
3
|
-
function injectedPrecache() {
|
|
4
|
-
return globalThis.__ALXIA_PRECACHE__;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
export { PRECACHE_DEFINE, injectedPrecache };
|
|
8
|
-
|
|
9
|
-
//# debugId=CA917CBC5F688F4264756E2164756E21
|
|
10
|
-
//# sourceMappingURL=index-59vhfj6n.js.map
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/pwa/model/precache-list.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"/**\n * What the service worker precaches, read from a build: every script and\n * stylesheet React Router's manifest names (the client entry and each\n * route's module, imports and CSS), and the manifest itself, so a client\n * navigation offline to a route never visited still finds its code. Only\n * hashed `/assets/` files: a new build names new files, so each precaches\n * under its own URL, revision `null`. Chunks only a component loads on\n * demand stay out: a cache-first route stores them the first time they load.\n *\n * Dependency-free: a build script runs it at build time.\n */\n\n/** A route or the entry, as `window.__reactRouterManifest` lists it. */\ntype ManifestModule = { module?: string; imports?: string[]; css?: string[] };\n\n/** The parts of React Router's browser manifest the list reads. */\nexport type BrowserManifest = {\n\turl: string;\n\tentry: ManifestModule;\n\troutes: Record<string, ManifestModule>;\n};\n\n/** A Workbox precache entry: a hashed URL needs no revision. */\nexport type PrecacheEntry = { url: string; revision: string | null };\n\n/** A Vite-hashed file under `/assets/`: `name-<8 hash chars>.js|css`. */\nconst HASHED_ASSET = /^\\/assets\\/[^/]+-[\\w-]{8}\\.(?:js|css)$/;\n\n/** Reads `window.__reactRouterManifest={…};` (build/client/assets/manifest-*.js). */\nexport function parseBrowserManifest(source: string): BrowserManifest {\n\tconst start = source.indexOf('{');\n\tconst end = source.lastIndexOf('}');\n\tif (start < 0 || end < start) {\n\t\tthrow new Error(\n\t\t\t\"parseBrowserManifest(): not React Router's browser manifest (build/client/assets/manifest-*.js).\",\n\t\t);\n\t}\n\treturn JSON.parse(source.slice(start, end + 1)) as BrowserManifest;\n}\n\n/** The hashed scripts and stylesheets every route needs, the manifest's own file first. */\nexport function precacheList(manifest: BrowserManifest): PrecacheEntry[] {\n\tconst urls = new Set<string>([manifest.url]);\n\tfor (const part of [manifest.entry, ...Object.values(manifest.routes)]) {\n\t\tfor (const url of [\n\t\t\t...(part.module ? [part.module] : []),\n\t\t\t...(part.imports ?? []),\n\t\t\t...(part.css ?? []),\n\t\t]) {\n\t\t\turls.add(url);\n\t\t}\n\t}\n\treturn [...urls]\n\t\t.filter((url) => HASHED_ASSET.test(url))\n\t\t.map((url) => ({ url, revision: null }));\n}\n\n/**\n * The precache entries of the files among `assetFiles` (the names in\n * build/client/assets) that `include` matches, sorted, under `base`: fonts\n * an app keeps offline, say. The regex is the app's.\n */\nexport function assetPrecache(\n\tassetFiles: readonly string[],\n\tinclude: RegExp,\n\tbase = '/assets/',\n): PrecacheEntry[] {\n\treturn assetFiles\n\t\t.filter((file) => {\n\t\t\tinclude.lastIndex = 0; // a /g or /y regex remembers its last match\n\t\t\treturn include.test(file);\n\t\t})\n\t\t.sort()\n\t\t.map((file) => ({ url: `${base}${file}`, revision: null }));\n}\n"
|
|
6
|
-
],
|
|
7
|
-
"mappings": ";AA0BA,IAAM,eAAe;AAGd,SAAS,qBAAoB,CAAC,QAAiC;AAAA,EACrE,MAAM,QAAQ,OAAO,QAAQ,GAAG;AAAA,EAChC,MAAM,MAAM,OAAO,YAAY,GAAG;AAAA,EAClC,IAAI,QAAQ,KAAK,MAAM,OAAO;AAAA,IAC7B,MAAM,IAAI,MACT,kGACD;AAAA,EACD;AAAA,EACA,OAAO,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,CAAC,CAAC;AAAA;AAIxC,SAAS,aAAY,CAAC,UAA4C;AAAA,EACxE,MAAM,OAAO,IAAI,IAAY,CAAC,SAAS,GAAG,CAAC;AAAA,EAC3C,WAAW,QAAQ,CAAC,SAAS,OAAO,GAAG,OAAO,OAAO,SAAS,MAAM,CAAC,GAAG;AAAA,IACvE,WAAW,OAAO;AAAA,MACjB,GAAI,KAAK,SAAS,CAAC,KAAK,MAAM,IAAI,CAAC;AAAA,MACnC,GAAI,KAAK,WAAW,CAAC;AAAA,MACrB,GAAI,KAAK,OAAO,CAAC;AAAA,IAClB,GAAG;AAAA,MACF,KAAK,IAAI,GAAG;AAAA,IACb;AAAA,EACD;AAAA,EACA,OAAO,CAAC,GAAG,IAAI,EACb,OAAO,CAAC,QAAQ,aAAa,KAAK,GAAG,CAAC,EACtC,IAAI,CAAC,SAAS,EAAE,KAAK,UAAU,KAAK,EAAE;AAAA;AAQlC,SAAS,cAAa,CAC5B,YACA,SACA,OAAO,YACW;AAAA,EAClB,OAAO,WACL,OAAO,CAAC,SAAS;AAAA,IACjB,QAAQ,YAAY;AAAA,IACpB,OAAO,QAAQ,KAAK,IAAI;AAAA,GACxB,EACA,KAAK,EACL,IAAI,CAAC,UAAU,EAAE,KAAK,GAAG,OAAO,QAAQ,UAAU,KAAK,EAAE;AAAA;",
|
|
8
|
-
"debugId": "812DDA9793A6A64B64756E2164756E21",
|
|
9
|
-
"names": []
|
|
10
|
-
}
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../src/pwa/build/build-worker.ts", "../src/pwa/build/precache.ts"],
|
|
4
|
-
"sourcesContent": [
|
|
5
|
-
"import { existsSync } from 'node:fs';\nimport { readdir, readFile, stat } from 'node:fs/promises';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport type { PrecacheEntry } from '../model/precache-list';\nimport {\n\tOFFLINE_URL,\n\tSERVICE_WORKER_URL,\n\ttype WorkerContract,\n} from '../model/worker-contract';\nimport { PRECACHE_DEFINE } from '../worker/injected';\nimport { browserManifestFile, revisionOf, workerPrecache } from './precache';\n\nexport interface BuildWorkerOptions {\n\t/**\n\t * The worker's source, relative to `root`: `app/service-worker.ts`. Named\n\t * `file`, not `entry`: `reveal` reads `alxia({ entry })`.\n\t */\n\tfile: string;\n\t/** `process.cwd()` by default. */\n\troot?: string;\n\t/** The client build, relative to `root`: `build/client` by default. */\n\tclient?: string;\n\t/** Where the worker is written and which offline page is precached. */\n\tcontract?: Pick<WorkerContract, 'serviceWorkerUrl' | 'offlineUrl'>;\n\t/** Precache the offline page, which must then exist. `true` by default. */\n\toffline?: boolean;\n\t/** More files of `assets/` to precache, such as fonts: the app's regex. */\n\tprecacheAssets?: RegExp;\n\t/** `true` by default. */\n\tminify?: boolean;\n}\n\nexport interface WorkerBuild {\n\t/** The absolute path of the worker written. */\n\tfile: string;\n\tprecache: PrecacheEntry[];\n\t/** The precached files' size, before compression. */\n\tprecacheBytes: number;\n\t/** The worker's own size. */\n\tbytes: number;\n}\n\n/** Not `requireBun` of `vite/`: `/pwa/build` imports Node's built-ins only. */\nexport function assertBun(\n\tonBun = (globalThis as { Bun?: unknown }).Bun !== undefined,\n): void {\n\tif (onBun) return;\n\tthrow new Error(\n\t\t'buildWorker() runs on Bun: it is running on Node. Run it with bun, or run react-router build with bun --bun.',\n\t);\n}\n\n/**\n * The file a root-relative URL names inside `client`. It fails closed: a URL\n * that is absolute, protocol-relative, not rooted at `/`, or that resolves to\n * `client` itself or outside it, is refused.\n */\nfunction urlInClient(client: string, url: string): string {\n\tconst path = join(client, url);\n\tif (\n\t\t!url.startsWith('/') ||\n\t\t/^[a-z][a-z0-9+.-]*:|^\\/\\//i.test(url) ||\n\t\t!path.startsWith(client + sep) ||\n\t\tpath.endsWith(sep)\n\t) {\n\t\tthrow new Error(`buildWorker(): ${url} is outside ${client}.`);\n\t}\n\treturn path;\n}\n\n/**\n * Bundles the worker (Workbox included) into the client build, after\n * `react-router build`, with the precache list written in: the offline page\n * by its content, every route's code and `precacheAssets`. A new build\n * changes the list, so the worker's bytes, so the browser installs it.\n * Runs on Bun; the only imports of this module are Node's built-ins.\n */\nexport async function buildWorker(\n\toptions: BuildWorkerOptions,\n): Promise<WorkerBuild> {\n\tassertBun();\n\tconst root = resolve(options.root ?? process.cwd());\n\tconst client = resolve(root, options.client ?? 'build/client');\n\tconst source = resolve(root, options.file);\n\tconst workerUrl = options.contract?.serviceWorkerUrl ?? SERVICE_WORKER_URL;\n\tconst offlineUrl = options.contract?.offlineUrl ?? OFFLINE_URL;\n\tif (!existsSync(source)) {\n\t\tthrow new Error(`buildWorker(): ${options.file} does not exist.`);\n\t}\n\tconst assets = join(client, 'assets');\n\tconst files = await readdir(assets).catch(() => []);\n\tconst manifest = browserManifestFile(files);\n\tlet offline: PrecacheEntry | undefined;\n\tif (options.offline !== false) {\n\t\tconst page = urlInClient(client, offlineUrl);\n\t\tif (!existsSync(page)) {\n\t\t\tthrow new Error(\n\t\t\t\t`buildWorker(): ${options.client ?? 'build/client'}${offlineUrl} does not exist. Add public${offlineUrl}, or pass offline: false (\\`worker: { offline: false }\\` in alxia()), or pass the app's contract (\\`worker: { contract }\\` in alxia()).`,\n\t\t\t);\n\t\t}\n\t\toffline = { url: offlineUrl, revision: revisionOf(await readFile(page)) };\n\t}\n\tconst precache = workerPrecache({\n\t\tmanifestSource: await readFile(join(assets, manifest), 'utf8'),\n\t\tassetFiles: files,\n\t\toffline,\n\t\tinclude: options.precacheAssets,\n\t});\n\tconst out = urlInClient(client, workerUrl);\n\tconst result = await Bun.build({\n\t\tentrypoints: [source],\n\t\toutdir: dirname(out),\n\t\tnaming: basename(out),\n\t\ttarget: 'browser',\n\t\tformat: 'iife',\n\t\tminify: options.minify ?? true,\n\t\tdefine: {\n\t\t\t// Workbox's production build: no logging, no dev assertions.\n\t\t\t'process.env.NODE_ENV': '\"production\"',\n\t\t\t[PRECACHE_DEFINE]: JSON.stringify(precache),\n\t\t},\n\t}).catch((error: unknown) => {\n\t\tconst detail =\n\t\t\terror instanceof AggregateError\n\t\t\t\t? error.errors.map(String).join('\\n')\n\t\t\t\t: String(error);\n\t\tthrow new Error(`buildWorker(): Bun.build failed:\\n${detail}`);\n\t});\n\tif (!result.success) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): Bun.build failed:\\n${result.logs.map(String).join('\\n')}`,\n\t\t);\n\t}\n\tlet precacheBytes = 0;\n\tfor (const { url } of precache) {\n\t\tprecacheBytes += (await stat(join(client, url))).size;\n\t}\n\treturn {\n\t\tfile: out,\n\t\tprecache,\n\t\tprecacheBytes,\n\t\tbytes: (await stat(out)).size,\n\t};\n}\n",
|
|
6
|
-
"import { createHash } from 'node:crypto';\nimport {\n\tassetPrecache,\n\ttype PrecacheEntry,\n\tparseBrowserManifest,\n\tprecacheList,\n} from '../model/precache-list';\n\n/** The one React Router browser manifest among the names in build/client/assets. */\nexport function browserManifestFile(files: readonly string[]): string {\n\tconst found = files.filter((file) => /^manifest-[\\w-]+\\.js$/.test(file));\n\tconst [only] = found;\n\tif (found.length !== 1 || only === undefined) {\n\t\tthrow new Error(\n\t\t\t`buildWorker(): expected one React Router browser manifest, build/client/assets/manifest-*.js, found ${found.length}. Run react-router build first.`,\n\t\t);\n\t}\n\treturn only;\n}\n\n/** A file's revision: the first 16 hex characters of its sha256. */\nexport function revisionOf(bytes: Uint8Array): string {\n\treturn createHash('sha256').update(bytes).digest('hex').slice(0, 16);\n}\n\n/**\n * The worker's precache list: the offline page (revisioned by its content),\n * every route's code, then the asset files `include` matches. Each URL once,\n * the first kept.\n */\nexport function workerPrecache(input: {\n\tmanifestSource: string;\n\tassetFiles: readonly string[];\n\toffline?: PrecacheEntry | undefined;\n\tinclude?: RegExp | undefined;\n}): PrecacheEntry[] {\n\tconst all = [\n\t\t...(input.offline ? [input.offline] : []),\n\t\t...precacheList(parseBrowserManifest(input.manifestSource)),\n\t\t...(input.include ? assetPrecache(input.assetFiles, input.include) : []),\n\t];\n\tconst seen = new Set<string>();\n\treturn all.filter(({ url }) => !seen.has(url) && seen.add(url));\n}\n"
|
|
7
|
-
],
|
|
8
|
-
"mappings": ";;;;;;;;;;;;;;AAAA;AACA;AACA;;;ACFA;AASO,SAAS,mBAAmB,CAAC,OAAkC;AAAA,EACrE,MAAM,QAAQ,MAAM,OAAO,CAAC,SAAS,wBAAwB,KAAK,IAAI,CAAC;AAAA,EACvE,OAAO,QAAQ;AAAA,EACf,IAAI,MAAM,WAAW,KAAK,SAAS,WAAW;AAAA,IAC7C,MAAM,IAAI,MACT,uGAAuG,MAAM,uCAC9G;AAAA,EACD;AAAA,EACA,OAAO;AAA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