@venizia/ignis-worker 0.2.0-10

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.
Files changed (105) hide show
  1. package/dist/cjs/applications/index.d.ts +2 -0
  2. package/dist/cjs/applications/index.d.ts.map +1 -0
  3. package/dist/cjs/applications/index.js +18 -0
  4. package/dist/cjs/applications/index.js.map +1 -0
  5. package/dist/cjs/applications/worker.d.ts +67 -0
  6. package/dist/cjs/applications/worker.d.ts.map +1 -0
  7. package/dist/cjs/applications/worker.js +175 -0
  8. package/dist/cjs/applications/worker.js.map +1 -0
  9. package/dist/cjs/envelope/encode.d.ts +61 -0
  10. package/dist/cjs/envelope/encode.d.ts.map +1 -0
  11. package/dist/cjs/envelope/encode.js +116 -0
  12. package/dist/cjs/envelope/encode.js.map +1 -0
  13. package/dist/cjs/envelope/index.d.ts +3 -0
  14. package/dist/cjs/envelope/index.d.ts.map +1 -0
  15. package/dist/cjs/envelope/index.js +19 -0
  16. package/dist/cjs/envelope/index.js.map +1 -0
  17. package/dist/cjs/envelope/types.d.ts +37 -0
  18. package/dist/cjs/envelope/types.d.ts.map +1 -0
  19. package/dist/cjs/envelope/types.js +3 -0
  20. package/dist/cjs/envelope/types.js.map +1 -0
  21. package/dist/cjs/index.d.ts +5 -0
  22. package/dist/cjs/index.d.ts.map +1 -0
  23. package/dist/cjs/index.js +21 -0
  24. package/dist/cjs/index.js.map +1 -0
  25. package/dist/cjs/transport/common/index.d.ts +2 -0
  26. package/dist/cjs/transport/common/index.d.ts.map +1 -0
  27. package/dist/cjs/transport/common/index.js +18 -0
  28. package/dist/cjs/transport/common/index.js.map +1 -0
  29. package/dist/cjs/transport/common/types.d.ts +6 -0
  30. package/dist/cjs/transport/common/types.d.ts.map +1 -0
  31. package/dist/cjs/transport/common/types.js +3 -0
  32. package/dist/cjs/transport/common/types.js.map +1 -0
  33. package/dist/cjs/transport/fetch-bridge.d.ts +35 -0
  34. package/dist/cjs/transport/fetch-bridge.d.ts.map +1 -0
  35. package/dist/cjs/transport/fetch-bridge.js +95 -0
  36. package/dist/cjs/transport/fetch-bridge.js.map +1 -0
  37. package/dist/cjs/transport/in-process.d.ts +23 -0
  38. package/dist/cjs/transport/in-process.d.ts.map +1 -0
  39. package/dist/cjs/transport/in-process.js +47 -0
  40. package/dist/cjs/transport/in-process.js.map +1 -0
  41. package/dist/cjs/transport/index.d.ts +6 -0
  42. package/dist/cjs/transport/index.d.ts.map +1 -0
  43. package/dist/cjs/transport/index.js +22 -0
  44. package/dist/cjs/transport/index.js.map +1 -0
  45. package/dist/cjs/transport/shared.d.ts +102 -0
  46. package/dist/cjs/transport/shared.d.ts.map +1 -0
  47. package/dist/cjs/transport/shared.js +396 -0
  48. package/dist/cjs/transport/shared.js.map +1 -0
  49. package/dist/cjs/transport/worker.d.ts +62 -0
  50. package/dist/cjs/transport/worker.d.ts.map +1 -0
  51. package/dist/cjs/transport/worker.js +223 -0
  52. package/dist/cjs/transport/worker.js.map +1 -0
  53. package/dist/esm/applications/index.d.ts +2 -0
  54. package/dist/esm/applications/index.d.ts.map +1 -0
  55. package/dist/esm/applications/index.js +2 -0
  56. package/dist/esm/applications/index.js.map +1 -0
  57. package/dist/esm/applications/worker.d.ts +67 -0
  58. package/dist/esm/applications/worker.d.ts.map +1 -0
  59. package/dist/esm/applications/worker.js +171 -0
  60. package/dist/esm/applications/worker.js.map +1 -0
  61. package/dist/esm/envelope/encode.d.ts +61 -0
  62. package/dist/esm/envelope/encode.d.ts.map +1 -0
  63. package/dist/esm/envelope/encode.js +112 -0
  64. package/dist/esm/envelope/encode.js.map +1 -0
  65. package/dist/esm/envelope/index.d.ts +3 -0
  66. package/dist/esm/envelope/index.d.ts.map +1 -0
  67. package/dist/esm/envelope/index.js +3 -0
  68. package/dist/esm/envelope/index.js.map +1 -0
  69. package/dist/esm/envelope/types.d.ts +37 -0
  70. package/dist/esm/envelope/types.d.ts.map +1 -0
  71. package/dist/esm/envelope/types.js +2 -0
  72. package/dist/esm/envelope/types.js.map +1 -0
  73. package/dist/esm/index.d.ts +5 -0
  74. package/dist/esm/index.d.ts.map +1 -0
  75. package/dist/esm/index.js +5 -0
  76. package/dist/esm/index.js.map +1 -0
  77. package/dist/esm/transport/common/index.d.ts +2 -0
  78. package/dist/esm/transport/common/index.d.ts.map +1 -0
  79. package/dist/esm/transport/common/index.js +2 -0
  80. package/dist/esm/transport/common/index.js.map +1 -0
  81. package/dist/esm/transport/common/types.d.ts +6 -0
  82. package/dist/esm/transport/common/types.d.ts.map +1 -0
  83. package/dist/esm/transport/common/types.js +2 -0
  84. package/dist/esm/transport/common/types.js.map +1 -0
  85. package/dist/esm/transport/fetch-bridge.d.ts +35 -0
  86. package/dist/esm/transport/fetch-bridge.d.ts.map +1 -0
  87. package/dist/esm/transport/fetch-bridge.js +91 -0
  88. package/dist/esm/transport/fetch-bridge.js.map +1 -0
  89. package/dist/esm/transport/in-process.d.ts +23 -0
  90. package/dist/esm/transport/in-process.d.ts.map +1 -0
  91. package/dist/esm/transport/in-process.js +43 -0
  92. package/dist/esm/transport/in-process.js.map +1 -0
  93. package/dist/esm/transport/index.d.ts +6 -0
  94. package/dist/esm/transport/index.d.ts.map +1 -0
  95. package/dist/esm/transport/index.js +6 -0
  96. package/dist/esm/transport/index.js.map +1 -0
  97. package/dist/esm/transport/shared.d.ts +102 -0
  98. package/dist/esm/transport/shared.d.ts.map +1 -0
  99. package/dist/esm/transport/shared.js +391 -0
  100. package/dist/esm/transport/shared.js.map +1 -0
  101. package/dist/esm/transport/worker.d.ts +62 -0
  102. package/dist/esm/transport/worker.d.ts.map +1 -0
  103. package/dist/esm/transport/worker.js +219 -0
  104. package/dist/esm/transport/worker.js.map +1 -0
  105. package/package.json +94 -0
@@ -0,0 +1,223 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WorkerBffTransport = void 0;
4
+ const core_1 = require("@venizia/ignis-helpers/core");
5
+ const core_2 = require("@venizia/ignis-helpers/core");
6
+ const encode_1 = require("../envelope/encode");
7
+ const DEFAULT_TIMEOUT_MS = 30_000;
8
+ /** How long a still-serving worker gets to answer after it reports an error - see `handleWorkerError`. */
9
+ const WORKER_ERROR_GRACE_MS = 250;
10
+ const isErrorEnvelope = (data) => {
11
+ return 'error' in data;
12
+ };
13
+ /**
14
+ * UI-side half of the BFF: posts an encoded request to a real `Worker` and resolves the matching
15
+ * response by `id` - the far side of `WorkerApplication.listen()`.
16
+ *
17
+ * The three worker listeners are attached ONCE, in the constructor, and every request is tracked in
18
+ * `pendingRequests` instead. Registering them per request looks equivalent and is not: they are
19
+ * scoped to the shared `Worker`, so a single `messageerror` - which means exactly one message
20
+ * failed to deserialise - would fire every in-flight request's handler, rejecting nine healthy
21
+ * requests that are about to be answered normally.
22
+ */
23
+ class WorkerBffTransport extends core_1.BaseHelper {
24
+ constructor(opts) {
25
+ super({ scope: WorkerBffTransport.name });
26
+ this.requestIdGenerator = new core_2.RequestIdGenerator({
27
+ scope: WorkerBffTransport.name,
28
+ });
29
+ this.pendingRequests = new Map();
30
+ /** Set by `close()`, so a later `fetch()` is refused instead of reaching a worker nothing listens to. */
31
+ this.isClosed = false;
32
+ /** Outstanding `handleWorkerError` grace timers, cleared by `close()` so none outlives the transport. */
33
+ this.graceTimers = new Set();
34
+ /** Removes a pending request from the map and releases its timer and abort listener, so nothing can settle it twice. */
35
+ this.takePending = (opts) => {
36
+ const pending = this.pendingRequests.get(opts.id);
37
+ if (!pending) {
38
+ return undefined;
39
+ }
40
+ this.pendingRequests.delete(opts.id);
41
+ pending.release();
42
+ return pending;
43
+ };
44
+ this.handleMessage = (event) => {
45
+ // `event.data` is untyped (`any`) until narrowed below - a worker posts to this page for its own
46
+ // reasons too (a dev-server ping, a library handshake), and none of those carry an `id` this
47
+ // transport is waiting on.
48
+ const data = event.data;
49
+ if (!data?.id) {
50
+ return;
51
+ }
52
+ const pending = this.takePending({ id: data.id });
53
+ if (!pending) {
54
+ return;
55
+ }
56
+ if (isErrorEnvelope(data)) {
57
+ pending.reject(encode_1.BffEnvelope.decodeError({ envelope: data }));
58
+ return;
59
+ }
60
+ // Settled inside its own try: `decodeResponse` throws a `RangeError` for a status outside
61
+ // 200-599 and a `TypeError` on a malformed header tuple, and by this point the timer and the
62
+ // listeners are already gone - a throw that escaped here would leave the promise with nothing
63
+ // left to settle it, ever.
64
+ try {
65
+ pending.resolve(encode_1.BffEnvelope.decodeResponse({ envelope: data }));
66
+ }
67
+ catch (error) {
68
+ pending.reject((0, core_1.getError)({
69
+ message: `[WorkerBffTransport] Failed to decode the response envelope | id: ${data.id} | error: ${error}`,
70
+ }));
71
+ }
72
+ };
73
+ /**
74
+ * An `error` event does NOT mean the worker is dead.
75
+ *
76
+ * Measured in Chromium: a synchronous uncaught throw anywhere in the worker - a third-party timer,
77
+ * say - fires this event while the worker keeps serving, and the genuine responses to the
78
+ * in-flight requests arrive a moment later. Rejecting immediately reported a committed POST as
79
+ * failed and then dropped its real 200 on the floor, because nothing was left waiting for it.
80
+ *
81
+ * So the event is logged at once and the requests are given a grace window. Whatever the worker
82
+ * still answers inside it settles normally; whatever is left after it really is lost, and is
83
+ * rejected with the diagnostics rather than left to run out its own timeout.
84
+ */
85
+ this.handleWorkerError = (event) => {
86
+ // `String(event)` is always `[object ErrorEvent]` - it says nothing. Read the fields a browser
87
+ // actually populates, so the log names the file and line that failed.
88
+ const detail = this.describeErrorEvent(event);
89
+ this.logger
90
+ .for('handleWorkerError')
91
+ .error('Worker reported an error | pending: %s | detail: %s', this.pendingRequests.size, detail);
92
+ const affected = [...this.pendingRequests.keys()];
93
+ // Held so `close()` can clear it. A grace timer that outlives the transport keeps the process
94
+ // (or a test runner) awake and fires against a map nobody is watching any more.
95
+ const timer = setTimeout(() => {
96
+ this.graceTimers.delete(timer);
97
+ for (const id of affected) {
98
+ // `takePending` answers undefined for anything the worker managed to settle in the window.
99
+ this.takePending({ id })?.reject((0, core_1.getError)({
100
+ message: `[WorkerBffTransport] Worker failed while awaiting a response | id: ${id} | detail: ${detail}`,
101
+ }));
102
+ }
103
+ }, WORKER_ERROR_GRACE_MS);
104
+ this.graceTimers.add(timer);
105
+ };
106
+ /**
107
+ * `messageerror` means exactly ONE posted message failed to deserialise, and the event carries
108
+ * nothing that says which. With a single request in flight that is unambiguous, so it settles
109
+ * now; with several, the lost answer belongs to one of them and rejecting the rest would be a
110
+ * lie - each then ends on its own timeout, under its own id.
111
+ */
112
+ this.handleMessageError = (event) => {
113
+ if (this.pendingRequests.size !== 1) {
114
+ this.logger
115
+ .for(this.handleMessageError.name)
116
+ .warn('A worker message could not be deserialised and no single request owns it | inFlight: %d | event: %s', this.pendingRequests.size, String(event));
117
+ return;
118
+ }
119
+ const [id] = [...this.pendingRequests.keys()];
120
+ this.takePending({ id: id })?.reject((0, core_1.getError)({
121
+ message: `[WorkerBffTransport] The worker's response could not be deserialised | id: ${id} | event: ${String(event)}`,
122
+ }));
123
+ };
124
+ this.worker = opts.worker;
125
+ this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
126
+ this.worker.addEventListener('message', this.handleMessage);
127
+ this.worker.addEventListener('error', this.handleWorkerError);
128
+ this.worker.addEventListener('messageerror', this.handleMessageError);
129
+ }
130
+ /** `ErrorEvent` carries the useful fields; a plain `Event` does not, so both shapes are handled. */
131
+ describeErrorEvent(event) {
132
+ const candidate = event;
133
+ if (!candidate.message) {
134
+ return event.type;
135
+ }
136
+ return `${candidate.message} (${candidate.filename ?? 'unknown'}:${candidate.lineno ?? 0}:${candidate.colno ?? 0})`;
137
+ }
138
+ async fetch(opts) {
139
+ const { request } = opts;
140
+ const { signal } = request;
141
+ // Refused, not queued. `close()` detaches the message listener, so a request posted after it
142
+ // still reached the worker - which EXECUTED it, writes included - while the answer had nowhere
143
+ // to land and the caller waited out the full timeout.
144
+ if (this.isClosed) {
145
+ throw (0, core_1.getError)({
146
+ message: '[WorkerBffTransport] The transport is closed | open a new one to make requests',
147
+ });
148
+ }
149
+ if (signal?.aborted) {
150
+ throw this.toAbortError({ signal });
151
+ }
152
+ const id = this.requestIdGenerator.nextId();
153
+ // The URL is overridden rather than the request rebuilt: rebuilding reads the body once here
154
+ // and once inside `encodeRequest`, and it silently drops `signal` on the way.
155
+ const requestEnvelope = await encode_1.BffEnvelope.encodeRequest({
156
+ request,
157
+ id,
158
+ url: encode_1.BffEnvelope.toSyntheticUrl({ url: request.url }),
159
+ });
160
+ return new Promise((resolve, reject) => {
161
+ const timer = setTimeout(() => {
162
+ this.takePending({ id })?.reject((0, core_1.getError)({
163
+ message: `[WorkerBffTransport] Timed out waiting for a response | id: ${id} | timeoutMs: ${this.timeoutMs}`,
164
+ }));
165
+ }, this.timeoutMs);
166
+ const handleAbort = () => {
167
+ this.takePending({ id })?.reject(this.toAbortError({ signal }));
168
+ };
169
+ signal?.addEventListener('abort', handleAbort);
170
+ this.pendingRequests.set(id, {
171
+ resolve,
172
+ reject,
173
+ release: () => {
174
+ clearTimeout(timer);
175
+ signal?.removeEventListener('abort', handleAbort);
176
+ },
177
+ });
178
+ // Buffering the body took an await, and `addEventListener('abort')` never fires on a signal
179
+ // that aborted before it was attached - without this re-read that window loses the abort and
180
+ // the caller waits out the whole timeout.
181
+ if (signal?.aborted) {
182
+ handleAbort();
183
+ return;
184
+ }
185
+ // `close()` can land during that same await. The entry guard above is then stale, and posting
186
+ // reaches a worker that EXECUTES the request - writes included - while the answer has nowhere
187
+ // to land, because `close()` already detached the listener.
188
+ if (this.isClosed) {
189
+ this.takePending({ id })?.reject((0, core_1.getError)({
190
+ message: `[WorkerBffTransport] The transport closed while the request was being encoded | id: ${id}`,
191
+ }));
192
+ return;
193
+ }
194
+ this.worker.postMessage(requestEnvelope, requestEnvelope.body ? [requestEnvelope.body] : []);
195
+ });
196
+ }
197
+ /** `signal.reason` first, the way `globalThis.fetch` rejects, so `controller.abort(myReason)` still reaches the caller. */
198
+ toAbortError(opts) {
199
+ return (opts.signal?.reason ??
200
+ (0, core_1.getError)({ message: '[WorkerBffTransport] The request was aborted by its caller' }));
201
+ }
202
+ /**
203
+ * Detaches the three worker listeners and fails whatever is still in flight. The worker itself is
204
+ * left alone - this transport did not create it, and a page may hand the same one to another.
205
+ */
206
+ close() {
207
+ this.isClosed = true;
208
+ for (const timer of this.graceTimers) {
209
+ clearTimeout(timer);
210
+ }
211
+ this.graceTimers.clear();
212
+ this.worker.removeEventListener('message', this.handleMessage);
213
+ this.worker.removeEventListener('error', this.handleWorkerError);
214
+ this.worker.removeEventListener('messageerror', this.handleMessageError);
215
+ for (const id of [...this.pendingRequests.keys()]) {
216
+ this.takePending({ id })?.reject((0, core_1.getError)({
217
+ message: `[WorkerBffTransport] The transport was closed while awaiting a response | id: ${id}`,
218
+ }));
219
+ }
220
+ }
221
+ }
222
+ exports.WorkerBffTransport = WorkerBffTransport;
223
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../../../src/transport/worker.ts"],"names":[],"mappings":";;;AAAA,sDAAmE;AACnE,sDAAiE;AACjE,8CAAgD;AAIhD,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAElC,0GAA0G;AAC1G,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC,MAAM,eAAe,GAAG,CACtB,IAA8C,EACnB,EAAE;IAC7B,OAAO,OAAO,IAAI,IAAI,CAAC;AACzB,CAAC,CAAC;AASF;;;;;;;;;GASG;AACH,MAAa,kBAAmB,SAAQ,iBAAU;IAchD,YAAY,IAA4C;QACtD,KAAK,CAAC,EAAE,KAAK,EAAE,kBAAkB,CAAC,IAAI,EAAE,CAAC,CAAC;QAZ3B,uBAAkB,GAAG,IAAI,yBAAkB,CAAC;YAC3D,KAAK,EAAE,kBAAkB,CAAC,IAAI;SAC/B,CAAC,CAAC;QACc,oBAAe,GAAG,IAAI,GAAG,EAA2B,CAAC;QAEtE,yGAAyG;QACjG,aAAQ,GAAG,KAAK,CAAC;QAEzB,yGAAyG;QACxF,gBAAW,G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C;QACD,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,SAAS,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC;QAC/D,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;QACjE,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,cAAc,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;QAEzE,KAAK,MAAM,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;YAClD,IAAI,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,MAAM,CAC9B,IAAA,eAAQ,EAAC;gBACP,OAAO,EAAE,iFAAiF,EAAE,EAAE;aAC/F,CAAC,CACH,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAvQD,gDAuQC"}
@@ -0,0 +1,2 @@
1
+ export * from './worker.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/applications/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC"}
@@ -0,0 +1,2 @@
1
+ export * from './worker.js';
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/applications/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC"}
@@ -0,0 +1,67 @@
1
+ import { RestApplication } from '@venizia/ignis-kernel';
2
+ import type { Env, Schema } from 'hono';
3
+ /**
4
+ * Structural shape of the two globals `listen()` can attach to. Never `DedicatedWorkerGlobalScope`:
5
+ * naming it emits it into the published `.d.ts` and forces every consumer to compile with
6
+ * `lib.webworker`. `start` is optional because a `MessagePort`s queue starts disabled and only
7
+ * `start()` enables it, while a worker global scope has no such method at all.
8
+ */
9
+ export interface IWorkerMessageScope {
10
+ postMessage(message: unknown, transfer?: Array<ArrayBuffer | MessagePort>): void;
11
+ addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
12
+ removeEventListener?(type: 'message', listener: (event: MessageEvent) => void): void;
13
+ start?(): void;
14
+ }
15
+ /**
16
+ * Runs an IGNIS application inside a browser Web Worker: `listen()` replaces what
17
+ * `ServerApplication.start()` does with a socket, attaching `onmessage` instead. Gets REST
18
+ * controller registration by inheritance - `RestApplication.registerControllers()` - the whole
19
+ * reason the DI helpers and `RestComponent` sit in the kernel.
20
+ */
21
+ export declare abstract class WorkerApplication<AppEnv extends Env = Env, AppSchema extends Schema = {}, BasePath extends string = '/'> extends RestApplication<AppEnv, AppSchema, BasePath> {
22
+ /** Resolves once the router tree is mounted - what an envelope arriving during boot waits on. */
23
+ private servingPromise?;
24
+ /** The whole `listen()` call, kept so a second one is a no-op instead of a second listener. */
25
+ private listenPromise?;
26
+ private detachFromScope?;
27
+ private isStopped;
28
+ /**
29
+ * Every failure here is posted back as an `IBffErrorEnvelope`, the failed `postMessage` included:
30
+ * an exception nobody posts leaves the UI waiting out the transport timeout.
31
+ */
32
+ private handleMessage;
33
+ /** No transfer list: an error envelope carries no `ArrayBuffer` body, and this is already the fallback path - nothing left to hand off if this post fails too. */
34
+ private postErrorEnvelope;
35
+ /** Everything `ServerApplication.start()` does short of binding a socket. Once this resolves the application answers requests. */
36
+ private startServing;
37
+ /**
38
+ * Holds an envelope until the application is serving. A dedicated worker's queue is enabled when
39
+ * its module script is evaluated, so anything posted during boot - PGlite takes ~350ms - reaches
40
+ * this listener and would otherwise be dropped. One shared promise also hands them on in arrival
41
+ * order.
42
+ */
43
+ private dispatchMessage;
44
+ private attachTo;
45
+ /**
46
+ * `ServerApplication.start()` minus the socket. `opts.scope` defaults to `globalThis`, never a
47
+ * bare `self`, which would tie the published types to `lib.webworker`. Idempotent: without the
48
+ * guard one envelope runs its handler once per call - a POST inserting two rows - and Vite HMR
49
+ * re-evaluating the worker module is the everyday trigger. A boot failure keeps the listener
50
+ * attached so every request hears the failure instead of waiting out the transport timeout.
51
+ */
52
+ listen(opts?: {
53
+ scope?: MessagePort | IWorkerMessageScope;
54
+ }): Promise<void>;
55
+ /**
56
+ * The counterpart to `listen()`, and to `ServerApplication.stop()`: without it nothing drains the
57
+ * post-stop hooks, so a datasource's `end()` never runs and the OPFS exclusive lock a PGlite
58
+ * holds is never released - the next Worker then fails with `NoModificationAllowedError` until a
59
+ * full page reload. The Vite recipe is `import.meta.hot?.dispose(() => application.stop())`.
60
+ *
61
+ * Detaches BEFORE draining, unlike the server: here the listener IS the socket, and a request
62
+ * admitted while the hooks are closing a datasource has nothing left to run against. A stopped
63
+ * application is not restartable - build a new one.
64
+ */
65
+ stop(): Promise<void>;
66
+ }
67
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../../../src/applications/worker.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAIxC;;;;;GAKG;AACH,MAAM,WAAW,mBAAmB;IAClC,WAAW,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC,GAAG,IAAI,CAAC;IACjF,gBAAgB,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACjF,mBAAmB,CAAC,CAAC,IAAI,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,GAAG,IAAI,CAAC;IACrF,KAAK,CAAC,IAAI,IAAI,CAAC;CAChB;AAED;;;;;GAKG;AACH,8BAAsB,iBAAiB,CACrC,MAAM,SAAS,GAAG,GAAG,GAAG,EACxB,SAAS,SAAS,MAAM,GAAG,EAAE,EAC7B,QAAQ,SAAS,MAAM,GAAG,GAAG,CAC7B,SAAQ,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,QAAQ,CAAC;IACpD,iGAAiG;IACjG,OAAO,CAAC,cAAc,CAAC,CAAgB;IACvC,+FAA+F;IAC/F,OAAO,CAAC,aAAa,CAAC,CAAgB;IACtC,OAAO,CAAC,eAAe,CAAC,CAAa;IACrC,OAAO,CAAC,SAAS,CAAS;IAE1B;;;OAGG;YACW,aAAa;IAoC3B,kKAAkK;IAClK,OAAO,CAAC,iBAAiB;IAgBzB,kIAAkI;YACpH,YAAY;IAW1B;;;;;OAKG;YACW,eAAe;IAqC7B,OAAO,CAAC,QAAQ;IAsChB;;;;;;OAMG;IACG,MAAM,CAAC,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,WAAW,GAAG,mBAAmB,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAqBjF;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAU5B"}
@@ -0,0 +1,171 @@
1
+ import { getError } from '@venizia/ignis-helpers/core';
2
+ import { HTTP } from '@venizia/ignis-helpers/common';
3
+ import { RestApplication } from '@venizia/ignis-kernel';
4
+ import { BffEnvelope } from '../envelope/encode.js';
5
+ /**
6
+ * Runs an IGNIS application inside a browser Web Worker: `listen()` replaces what
7
+ * `ServerApplication.start()` does with a socket, attaching `onmessage` instead. Gets REST
8
+ * controller registration by inheritance - `RestApplication.registerControllers()` - the whole
9
+ * reason the DI helpers and `RestComponent` sit in the kernel.
10
+ */
11
+ export class WorkerApplication extends RestApplication {
12
+ constructor() {
13
+ super(...arguments);
14
+ this.isStopped = false;
15
+ }
16
+ /**
17
+ * Every failure here is posted back as an `IBffErrorEnvelope`, the failed `postMessage` included:
18
+ * an exception nobody posts leaves the UI waiting out the transport timeout.
19
+ */
20
+ async handleMessage(opts) {
21
+ const { scope, envelope } = opts;
22
+ const logger = this.logger.for(this.handleMessage.name);
23
+ let responseEnvelope;
24
+ let failure;
25
+ try {
26
+ const request = BffEnvelope.decodeRequest({ envelope });
27
+ const response = await this.getServer().fetch(request);
28
+ responseEnvelope = await BffEnvelope.encodeResponse({ response, id: envelope.id });
29
+ }
30
+ catch (error) {
31
+ logger.error('Failed to handle worker message | id: %s | error: %s', envelope.id, error);
32
+ failure = error;
33
+ }
34
+ if (responseEnvelope) {
35
+ try {
36
+ scope.postMessage(responseEnvelope, responseEnvelope.body ? [responseEnvelope.body] : []);
37
+ return;
38
+ }
39
+ catch (postError) {
40
+ logger.error('Failed to post response back to scope, falling back to an error envelope | id: %s | error: %s', envelope.id, postError);
41
+ failure = postError;
42
+ }
43
+ }
44
+ this.postErrorEnvelope({ scope, id: envelope.id, error: failure });
45
+ }
46
+ /** No transfer list: an error envelope carries no `ArrayBuffer` body, and this is already the fallback path - nothing left to hand off if this post fails too. */
47
+ postErrorEnvelope(opts) {
48
+ const { scope, id, error } = opts;
49
+ try {
50
+ scope.postMessage(BffEnvelope.encodeError({ id, error }));
51
+ }
52
+ catch (postError) {
53
+ this.logger
54
+ .for(this.postErrorEnvelope.name)
55
+ .error('Failed to post error envelope back to scope | id: %s | error: %s', id, postError);
56
+ }
57
+ }
58
+ /** Everything `ServerApplication.start()` does short of binding a socket. Once this resolves the application answers requests. */
59
+ async startServing() {
60
+ // The stack itself is `RestApplication.registerDefaultMiddlewares()` - a BFF must answer with
61
+ // the framework's envelope exactly as the server does, so it adds nothing and overrides nothing.
62
+ await this.registerDefaultMiddlewares();
63
+ await this.initialize();
64
+ await this.setupMiddlewares();
65
+ this.getServer().route(this.configs.path.base, this.rootRouter);
66
+ }
67
+ /**
68
+ * Holds an envelope until the application is serving. A dedicated worker's queue is enabled when
69
+ * its module script is evaluated, so anything posted during boot - PGlite takes ~350ms - reaches
70
+ * this listener and would otherwise be dropped. One shared promise also hands them on in arrival
71
+ * order.
72
+ */
73
+ async dispatchMessage(opts) {
74
+ const { scope, envelope } = opts;
75
+ const logger = this.logger.for(this.dispatchMessage.name);
76
+ try {
77
+ await this.servingPromise;
78
+ }
79
+ catch (error) {
80
+ logger.error('The application failed to start, answering with an error envelope | id: %s | error: %s', envelope.id, error);
81
+ this.postErrorEnvelope({ scope, id: envelope.id, error });
82
+ return;
83
+ }
84
+ // Answered, not dropped: a request admitted before `stop()` and still waiting on the boot has
85
+ // a caller holding a promise, and silence there is the timeout this whole path exists to avoid.
86
+ if (this.isStopped) {
87
+ logger.warn('Refusing a request that arrived after stop() | id: %s', envelope.id);
88
+ this.postErrorEnvelope({
89
+ scope,
90
+ id: envelope.id,
91
+ error: getError({
92
+ statusCode: HTTP.ResultCodes.RS_5.ServiceUnavailable,
93
+ message: `[WorkerApplication] The application was stopped before this request could run | id: ${envelope.id}`,
94
+ }),
95
+ });
96
+ return;
97
+ }
98
+ await this.handleMessage({ scope, envelope });
99
+ }
100
+ attachTo(opts) {
101
+ const { scope } = opts;
102
+ const logger = this.logger.for(this.attachTo.name);
103
+ // Typed as the broader `Event`, not `MessageEvent`: Node's ambient `worker_threads.MessagePort`
104
+ // (the fallback this package's DOM-less tsconfig resolves `MessagePort` to) declares
105
+ // `addEventListener` over `Event | MessageEvent`, and a handler narrower than that is not
106
+ // assignable to it.
107
+ const listener = (event) => {
108
+ const envelope = event.data;
109
+ // A worker scope receives every `postMessage` sent to it, not only ours - a dev-server ping,
110
+ // a devtools/extension probe, a library's own init handshake. None of those carry an `id`;
111
+ // silently dropping them (rather than dereferencing `envelope.id` inside `handleMessage`'s
112
+ // own catch block) is what keeps a foreign message from throwing a bare `TypeError` that
113
+ // would otherwise escape this listener entirely, unlogged and unposted.
114
+ if (!envelope?.id) {
115
+ logger.debug('Ignoring worker message with no request id | data: %j', envelope);
116
+ return;
117
+ }
118
+ // `dispatchMessage` never rejects - every failure inside it, including a failed post, is
119
+ // caught and handled internally. This `.catch` only guards the sliver of code before its own
120
+ // try block ever runs.
121
+ this.dispatchMessage({ scope, envelope }).catch(error => {
122
+ logger.error('Unexpected failure handling worker message | error: %s', error);
123
+ });
124
+ };
125
+ scope.addEventListener('message', listener);
126
+ scope.start?.();
127
+ this.detachFromScope = () => {
128
+ scope.removeEventListener?.('message', listener);
129
+ };
130
+ }
131
+ /**
132
+ * `ServerApplication.start()` minus the socket. `opts.scope` defaults to `globalThis`, never a
133
+ * bare `self`, which would tie the published types to `lib.webworker`. Idempotent: without the
134
+ * guard one envelope runs its handler once per call - a POST inserting two rows - and Vite HMR
135
+ * re-evaluating the worker module is the everyday trigger. A boot failure keeps the listener
136
+ * attached so every request hears the failure instead of waiting out the transport timeout.
137
+ */
138
+ async listen(opts) {
139
+ if (this.listenPromise) {
140
+ this.logger
141
+ .for(this.listen.name)
142
+ .warn('Already listening - ignoring this call | one scope, one listener');
143
+ return this.listenPromise;
144
+ }
145
+ // Everything down to the first `await` runs synchronously with the caller, which is what makes
146
+ // the listener observable to anything posted in the same turn.
147
+ const scope = opts?.scope ?? globalThis;
148
+ this.attachTo({ scope });
149
+ this.servingPromise = this.startServing();
150
+ this.listenPromise = this.servingPromise.then(() => this.executePostStartHooks());
151
+ return this.listenPromise;
152
+ }
153
+ /**
154
+ * The counterpart to `listen()`, and to `ServerApplication.stop()`: without it nothing drains the
155
+ * post-stop hooks, so a datasource's `end()` never runs and the OPFS exclusive lock a PGlite
156
+ * holds is never released - the next Worker then fails with `NoModificationAllowedError` until a
157
+ * full page reload. The Vite recipe is `import.meta.hot?.dispose(() => application.stop())`.
158
+ *
159
+ * Detaches BEFORE draining, unlike the server: here the listener IS the socket, and a request
160
+ * admitted while the hooks are closing a datasource has nothing left to run against. A stopped
161
+ * application is not restartable - build a new one.
162
+ */
163
+ async stop() {
164
+ this.isStopped = true;
165
+ this.detachFromScope?.();
166
+ this.detachFromScope = undefined;
167
+ await this.executePostStopHooks();
168
+ this.logger.for(this.stop.name).info('Worker application STOPPED');
169
+ }
170
+ }
171
+ //# sourceMappingURL=worker.js.map
@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IAAI,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAEzB,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;QAC1C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,qBAAqB,EAAE,CAAC,CAAC;QAElF,OAAO,IAAI,CAAC,aAAa,CAAC;IAC5B,CAAC;IAED;;;;;;;;;OASG;IACH,KAAK,CAAC,IAAI;QACR,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QAEtB,IAAI,CAAC,eAAe,EAAE,EAAE,CAAC;QACzB,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QAEjC,MAAM,IAAI,CAAC,oBAAoB,EAAE,CAAC;QAElC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IACrE,CAAC;CACF"}
@@ -0,0 +1,61 @@
1
+ import type { ApplicationError } from '@venizia/ignis-helpers/core';
2
+ import type { IBffErrorEnvelope, IBffRequestEnvelope, IBffResponseEnvelope } from './types.js';
3
+ /**
4
+ * Every request built inside the Worker uses this origin. Never `self.location.href`: a `blob:`
5
+ * worker origin is opaque and `new URL(path, blobUrl)` throws, and Hono's `getPath()` mis-parses
6
+ * `file://`. Hono never resolves the host - it string-scans from `indexOf(':') + 4`.
7
+ */
8
+ export declare const BFF_SYNTHETIC_ORIGIN = "http://ignis.internal";
9
+ /** Turns `Request`/`Response`/`Error` into plain structured-cloneable shapes and back - none of the three survives `postMessage` as itself. */
10
+ export declare class BffEnvelope {
11
+ /**
12
+ * Statuses the Fetch spec forbids a body on - `new Response(body, { status })` throws if `body`
13
+ * is anything but `null` for one of these, even an empty `ArrayBuffer`.
14
+ */
15
+ private static readonly NULL_BODY_STATUSES;
16
+ /**
17
+ * Moves a URL onto the synthetic origin, keeping everything below it. A caller builds a request
18
+ * against the page's real origin (or a relative path resolved against it); `decodeRequest` on the
19
+ * far side always reconstructs on `BFF_SYNTHETIC_ORIGIN`.
20
+ */
21
+ static toSyntheticUrl(opts: {
22
+ url: string;
23
+ }): string;
24
+ /**
25
+ * `url` overrides the request's own, so the origin rewrite costs nothing: rebuilding the `Request`
26
+ * to change its URL would read the body a second time, and a 10 MB upload would hold 20 MB on the
27
+ * UI thread. Reading the body here disturbs the caller's request exactly as `globalThis.fetch`
28
+ * does with the one it is handed.
29
+ */
30
+ static encodeRequest(opts: {
31
+ request: Request;
32
+ id: string;
33
+ url?: string;
34
+ }): Promise<IBffRequestEnvelope>;
35
+ static decodeRequest(opts: {
36
+ envelope: IBffRequestEnvelope;
37
+ }): Request;
38
+ static encodeResponse(opts: {
39
+ response: Response;
40
+ id: string;
41
+ }): Promise<IBffResponseEnvelope>;
42
+ static decodeResponse(opts: {
43
+ envelope: IBffResponseEnvelope;
44
+ }): Response;
45
+ /**
46
+ * Builds the shape an error crosses `postMessage` as. An `ApplicationError` cannot cross as itself
47
+ * - a custom `Error` subclass loses its name, its own properties and its prototype through
48
+ * structured clone - so it crosses normalised and `decodeError` rebuilds it on the far side.
49
+ *
50
+ * A foreign error gets `500`, matching what the framework's error middleware gives an UNEXPECTED
51
+ * one on the server. Anything reaching here already escaped the whole HTTP layer.
52
+ */
53
+ static encodeError(opts: {
54
+ id: string;
55
+ error: unknown;
56
+ }): IBffErrorEnvelope;
57
+ static decodeError(opts: {
58
+ envelope: IBffErrorEnvelope;
59
+ }): ApplicationError;
60
+ }
61
+ //# sourceMappingURL=encode.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../../../src/envelope/encode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAGpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM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