@cossackframework/node-adapter 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,78 +1,140 @@
1
1
  import { WebSocket as e, WebSocketServer as t } from "ws";
2
- import { InMemoryWebSocketRuntime as n, createInstance as r, isOriginAllowed as i } from "@cossackframework/core";
3
- import { URL as a } from "url";
4
- import * as o from "fs";
5
- import * as s from "path";
6
- import c from "nodemailer";
2
+ import { InMemoryWebSocketRuntime as n, closeUnauthorizedSocket as r, createInstance as i, isOriginAllowed as a, setClientAddress as o } from "@cossackframework/core";
3
+ import { URL as s } from "url";
4
+ import * as c from "fs";
5
+ import * as l from "path";
6
+ import u from "nodemailer";
7
+ //#region ../core/dist/shared/server-diagnostics.js
8
+ var d = /* @__PURE__ */ new Set([
9
+ "action",
10
+ "action-cleanup",
11
+ "parse",
12
+ "dispatch",
13
+ "delivery",
14
+ "task-setup",
15
+ "task-cleanup",
16
+ "component-cleanup",
17
+ "service-setup-cleanup",
18
+ "service-cleanup",
19
+ "authentication",
20
+ "scope",
21
+ "upgrade",
22
+ "initialization",
23
+ "initial-state",
24
+ "socket",
25
+ "runtime-cleanup"
26
+ ]), f = /* @__PURE__ */ new Set([
27
+ "COSSACK_RUNTIME_FAILED",
28
+ "COSSACK_RPC_INTERNAL_ERROR",
29
+ "COSSACK_RPC_CLEANUP_FAILED",
30
+ "COSSACK_WEBSOCKET_MESSAGE_INVALID",
31
+ "COSSACK_TASK_FAILED",
32
+ "COSSACK_TASK_CLEANUP_FAILED",
33
+ "COSSACK_COMPONENT_CLEANUP_FAILED",
34
+ "COSSACK_SERVICE_CLEANUP_FAILED"
35
+ ]), p = /* @__PURE__ */ new Set([
36
+ "cloudflare",
37
+ "cloudflare-workers",
38
+ "node",
39
+ "browser",
40
+ "web",
41
+ "unknown"
42
+ ]), m = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
43
+ function h(e, t) {
44
+ try {
45
+ let n = Object.getOwnPropertyDescriptor(e, t);
46
+ return n && "value" in n ? n.value : void 0;
47
+ } catch {
48
+ return;
49
+ }
50
+ }
51
+ function g(e, t) {
52
+ return typeof e == "string" && e.replace(/[^a-zA-Z0-9_.$/\[\]:*-]/g, "_").slice(0, t) || "unknown";
53
+ }
54
+ function _(e, t, n = "COSSACK_RUNTIME_FAILED") {
55
+ let r = h(e, "requestId"), i = h(e, "runtime"), a = h(e, "startedAt"), o = typeof a == "number" && Number.isFinite(a) ? performance.now() - a : 0;
56
+ console.error({
57
+ event: "cossack.runtime.failure",
58
+ requestId: typeof r == "string" && m.test(r) ? r : "unavailable",
59
+ route: g(h(e, "route"), 160),
60
+ action: g(h(e, "action"), 80),
61
+ component: g(h(e, "component"), 80),
62
+ runtime: typeof i == "string" && p.has(i) ? i : "unknown",
63
+ durationMs: Number.isFinite(o) ? Math.max(0, Math.round(o)) : 0,
64
+ stage: d.has(t) ? t : "unknown",
65
+ code: f.has(n) ? n : "COSSACK_RUNTIME_FAILED"
66
+ });
67
+ }
68
+ //#endregion
7
69
  //#region src/runtime.ts
8
- var l = class extends n {
70
+ var v = class extends n {
9
71
  constructor(t) {
10
72
  super(t, {
11
73
  isOpen: (t) => t.readyState === e.OPEN,
12
- onError: (e) => console.error("[Cossack] Ignoring malformed WebSocket message:", e)
74
+ onError: () => _({ runtime: "node" }, "dispatch")
13
75
  });
14
76
  }
15
- addClient(e, t) {
16
- super.addClient(e, t), e.on("close", () => {
77
+ addClient(e, t, n, r) {
78
+ super.addClient(e, t, n, r), e.on("close", () => {
17
79
  this.removeClient(e);
18
80
  }), e.on("message", (t) => {
19
81
  this.onClientMessage(e, t.toString()).catch((e) => {
20
- console.error("[Cossack] Error handling Node WebSocket message:", e);
82
+ _({ runtime: "node" }, "dispatch");
21
83
  });
22
84
  });
23
85
  }
24
86
  };
25
87
  //#endregion
26
88
  //#region src/static-serve.ts
27
- function u(e) {
89
+ function y(e) {
28
90
  let t = e, n = t.indexOf("?");
29
91
  n !== -1 && (t = t.substring(0, n));
30
92
  let r = t.indexOf("#");
31
93
  return r !== -1 && (t = t.substring(0, r)), t.startsWith("/") || (t = "/" + t), t !== "/" && t.endsWith("/") && (t = t.slice(0, -1)), t;
32
94
  }
33
- function d(e) {
34
- let { root: t, prefix: n = "/", index: r = !0, cacheControl: i } = e, a = s.resolve(t), c = a + s.sep, l = (e) => {
35
- let t = s.resolve(e);
36
- return t === a || t.startsWith(c);
95
+ function b(e) {
96
+ let { root: t, prefix: n = "/", index: r = !0, cacheControl: i } = e, a = l.resolve(t), o = a + l.sep, s = (e) => {
97
+ let t = l.resolve(e);
98
+ return t === a || t.startsWith(o);
37
99
  };
38
- return async (e, c) => {
39
- if (e.req.method !== "GET" && e.req.method !== "HEAD") return c();
40
- let d = u(e.req.path);
41
- if (!d.startsWith(n)) return c();
42
- let p = d.substring(n.length);
43
- p === "" && (p = "/");
44
- let m;
45
- if (p === "/") {
46
- if (!r) return c();
47
- m = s.join(t, "index.html");
48
- } else if (m = s.join(t, p), r && !o.existsSync(m)) {
49
- let e = s.join(m, "index.html");
50
- o.existsSync(e) && (m = e);
100
+ return async (e, o) => {
101
+ if (e.req.method !== "GET" && e.req.method !== "HEAD") return o();
102
+ let u = y(e.req.path);
103
+ if (!u.startsWith(n)) return o();
104
+ let d = u.substring(n.length);
105
+ d === "" && (d = "/");
106
+ let f;
107
+ if (d === "/") {
108
+ if (!r) return o();
109
+ f = l.join(t, "index.html");
110
+ } else if (f = l.join(t, d), r && !c.existsSync(f)) {
111
+ let e = l.join(f, "index.html");
112
+ c.existsSync(e) && (f = e);
51
113
  }
52
- if (!l(m)) return c();
114
+ if (!s(f)) return o();
53
115
  try {
54
- let t = await o.promises.stat(m);
116
+ let t = await c.promises.stat(f);
55
117
  if (t.isDirectory()) if (r) {
56
- let e = s.join(m, "index.html");
118
+ let e = l.join(f, "index.html");
57
119
  try {
58
- await o.promises.access(e), m = e, t = await o.promises.stat(m);
120
+ await c.promises.access(e), f = e, t = await c.promises.stat(f);
59
121
  } catch {
60
- return c();
122
+ return o();
61
123
  }
62
- } else return c();
63
- let [n, l] = await Promise.all([o.promises.realpath(a), o.promises.realpath(m)]), u = s.relative(n, l);
64
- if (u === ".." || u.startsWith(`..${s.sep}`) || s.isAbsolute(u) || !t.isFile()) return c();
65
- let p = e.req.method === "HEAD" ? null : await o.promises.readFile(l), h = f(m), g = new Headers({ "Content-Type": h }), _ = typeof i == "function" ? i(m, d) : i;
66
- return _ && g.set("Cache-Control", _), new Response(p === null ? null : new Uint8Array(p), {
124
+ } else return o();
125
+ let [n, s] = await Promise.all([c.promises.realpath(a), c.promises.realpath(f)]), d = l.relative(n, s);
126
+ if (d === ".." || d.startsWith(`..${l.sep}`) || l.isAbsolute(d) || !t.isFile()) return o();
127
+ let p = e.req.method === "HEAD" ? null : await c.promises.readFile(s), m = x(f), h = new Headers({ "Content-Type": m }), g = typeof i == "function" ? i(f, u) : i;
128
+ return g && h.set("Cache-Control", g), new Response(p === null ? null : new Uint8Array(p), {
67
129
  status: 200,
68
- headers: g
130
+ headers: h
69
131
  });
70
132
  } catch {
71
- return c();
133
+ return o();
72
134
  }
73
135
  };
74
136
  }
75
- function f(e) {
137
+ function x(e) {
76
138
  return {
77
139
  ".html": "text/html",
78
140
  ".css": "text/css",
@@ -96,12 +158,12 @@ function f(e) {
96
158
  ".eot": "application/vnd.ms-fontobject",
97
159
  ".pdf": "application/pdf",
98
160
  ".zip": "application/zip"
99
- }[s.extname(e).toLowerCase()] || "application/octet-stream";
161
+ }[l.extname(e).toLowerCase()] || "application/octet-stream";
100
162
  }
101
163
  //#endregion
102
164
  //#region src/email.ts
103
- function p(e) {
104
- let t = c.createTransport({
165
+ function S(e) {
166
+ let t = u.createTransport({
105
167
  host: e.host,
106
168
  port: e.port,
107
169
  secure: e.secure ?? e.port === 465,
@@ -126,9 +188,220 @@ function p(e) {
126
188
  } };
127
189
  }
128
190
  //#endregion
191
+ //#region src/adapter.ts
192
+ function C(i = {}) {
193
+ let a = new t({ noServer: !0 }), s = /* @__PURE__ */ new WeakMap();
194
+ a.on("headers", (e, t) => {
195
+ let n = s.get(t);
196
+ if (n) {
197
+ for (let [t, r] of n) /^(connection|upgrade|content-length|transfer-encoding|set-cookie|sec-websocket-.*|x-cossack-upgrade)$/i.test(t) || e.push(`${t}: ${r}`);
198
+ for (let t of n.getSetCookie()) e.push(`set-cookie: ${t}`);
199
+ }
200
+ });
201
+ let c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set(), p = /* @__PURE__ */ new Set(), m = i.maxInstances ?? 512, h = i.idleTimeoutMs ?? 15 * 6e4, g = !1, v;
202
+ if (!Number.isInteger(m) || m < 1 || !Number.isFinite(h) || h < 0) throw TypeError("Node runtime requires positive integer maxInstances and nonnegative finite idleTimeoutMs");
203
+ let y = async (e) => {
204
+ let t = (await Promise.allSettled(e)).filter((e) => e.status === "rejected").map((e) => e.reason);
205
+ if (t.length) throw AggregateError(t, "Node runtime cleanup failed");
206
+ }, b = (e) => {
207
+ let t = e.dispose();
208
+ return d.add(t), t.then(() => d.delete(t), () => d.delete(t)), t;
209
+ }, x = async (e = !1) => {
210
+ let t = [], n = [...l].filter(([e, t]) => !u.has(e) && t.clients.size === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
211
+ for (let [r, i] of n) Date.now() - i.lastActive < h && l.size + u.size < m + +!e || (l.delete(r), t.push(b(i)));
212
+ await y(t);
213
+ }, S = (e) => {
214
+ if (g) return Promise.reject(/* @__PURE__ */ Error("Node runtime is disposed"));
215
+ let t = JSON.stringify([
216
+ e.componentId,
217
+ e.provider,
218
+ e.target
219
+ ]), r = u.get(t);
220
+ if (r) return r;
221
+ let i = l.get(t);
222
+ if (i) return Promise.resolve(i);
223
+ let a = x(!0);
224
+ if (l.size + u.size >= m) return a.then(() => {
225
+ throw Error("Node runtime instance limit reached");
226
+ });
227
+ let o = a.then(async () => {
228
+ if (g) throw Error("Node runtime is disposed");
229
+ let r = await e.createComponent(), i;
230
+ try {
231
+ let e = {
232
+ runtime: new n(r, { onError: () => _({ runtime: "node" }, "dispatch") }),
233
+ clients: /* @__PURE__ */ new Set(),
234
+ actions: /* @__PURE__ */ new Set(),
235
+ lastActive: Date.now(),
236
+ dispose: () => i ??= (async () => {
237
+ for (let t of e.clients) e.runtime.removeClient(t), t.close(1001, "Runtime shutting down"), t.terminate();
238
+ e.clients.clear(), await Promise.allSettled([...e.actions]), await r.destroyAsync();
239
+ })()
240
+ };
241
+ return l.set(t, e), e;
242
+ } catch (e) {
243
+ throw await r.destroyAsync(), e;
244
+ }
245
+ }).finally(() => u.delete(t));
246
+ return u.set(t, o), o;
247
+ }, C = async (t, n) => {
248
+ if (t.on("error", (e) => _({ runtime: "node" }, "socket")), n.rejectAuthorization) {
249
+ r(t);
250
+ return;
251
+ }
252
+ try {
253
+ let r = await S(n);
254
+ if (g || t.readyState !== e.OPEN) {
255
+ await x();
256
+ return;
257
+ }
258
+ r.clients.add(t), r.runtime.addClient(t, n.user, n.authorize ? void 0 : n.context, n.authorize ? (e, t) => n.authorize(t) : void 0), r.lastActive = Date.now(), t.on("close", () => {
259
+ r.clients.delete(t), r.runtime.removeClient(t), r.lastActive = Date.now(), x().catch((e) => _({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
260
+ }), t.on("message", (n) => {
261
+ if (g || t.readyState !== e.OPEN) return;
262
+ r.lastActive = Date.now();
263
+ let i = r.runtime.onClientMessage(t, n.toString());
264
+ r.actions.add(i), i.catch((e) => {
265
+ _({ runtime: "node" }, "dispatch"), t.close(1013, "Runtime unavailable");
266
+ }).finally(() => r.actions.delete(i));
267
+ }), await r.runtime.sendInitialState(t);
268
+ } catch {
269
+ _({ runtime: "node" }, "initialization"), t.close(1013, "Runtime unavailable");
270
+ }
271
+ }, w = () => {
272
+ if (v) return v;
273
+ g = !0;
274
+ for (let e of p) e();
275
+ p.clear();
276
+ for (let e of f) e.destroy();
277
+ return f.clear(), v = (async () => {
278
+ await Promise.allSettled([...u.values()]);
279
+ let e = [...l.values()];
280
+ l.clear();
281
+ try {
282
+ await y([...d, ...e.map(b)]);
283
+ } finally {
284
+ a.close();
285
+ }
286
+ })(), v;
287
+ };
288
+ return {
289
+ name: "node",
290
+ get instanceCount() {
291
+ return l.size;
292
+ },
293
+ getClientMetadata: () => ({ platform: "web" }),
294
+ dispose: w,
295
+ handleWebSocketUpgrade(e, t) {
296
+ let n = c.get(e.req.raw);
297
+ return g || !n ? new Response("WebSocket upgrade unavailable", { status: 503 }) : (n.upgrade = {
298
+ ...t,
299
+ context: t.context ?? e
300
+ }, new Response(null, {
301
+ status: 204,
302
+ headers: { "x-cossack-upgrade": n.token }
303
+ }));
304
+ },
305
+ attach(e, t) {
306
+ if (g) throw Error("Node runtime is disposed");
307
+ let n = (e, n, r) => {
308
+ e.url?.startsWith("/ws/") && (f.add(n), n.once("close", () => f.delete(n)), n.on("error", () => n.destroy()), (async () => {
309
+ let i = new Headers();
310
+ for (let t = 0; t < e.rawHeaders.length; t += 2) i.append(e.rawHeaders[t], e.rawHeaders[t + 1]);
311
+ let l = e.socket.encrypted ? "https" : "http", u = new Request(new URL(e.url, `${l}://${e.headers.host}`), { headers: i }), d = {
312
+ token: crypto.randomUUID(),
313
+ upgrade: void 0
314
+ };
315
+ o(u, e.socket.remoteAddress), c.set(u, d);
316
+ let f;
317
+ try {
318
+ f = await t(u);
319
+ } finally {
320
+ c.delete(u);
321
+ }
322
+ if (!(g || n.destroyed)) {
323
+ if (!d.upgrade || f.status !== 204 || f.headers.get("x-cossack-upgrade") !== d.token) {
324
+ let e = f.status >= 400 && f.status <= 599 ? f.status : 403;
325
+ await f.body?.cancel(), n.end(`HTTP/1.1 ${e} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
326
+ return;
327
+ }
328
+ s.set(e, f.headers);
329
+ try {
330
+ a.handleUpgrade(e, n, r, (e) => {
331
+ C(e, d.upgrade);
332
+ });
333
+ } finally {
334
+ s.delete(e);
335
+ }
336
+ }
337
+ })().catch((e) => {
338
+ _({ runtime: "node" }, "upgrade"), n.destroy();
339
+ }));
340
+ }, r = () => {
341
+ w().catch((e) => _({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
342
+ };
343
+ e.on("upgrade", n), e.once("close", r);
344
+ let i = () => {
345
+ e.off("upgrade", n), e.off("close", r), p.delete(i);
346
+ };
347
+ return p.add(i), i;
348
+ }
349
+ };
350
+ }
351
+ //#endregion
352
+ //#region src/shutdown.ts
353
+ function w(e, t) {
354
+ let n = t.timeoutMs ?? 1e4;
355
+ if (!Number.isFinite(n) || n <= 0) throw TypeError("Shutdown timeout must be positive and finite");
356
+ let r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set(), a, o = (e) => {
357
+ r.add(e), e.once("close", () => r.delete(e));
358
+ }, s = (e) => {
359
+ i.add(e), e.once("close", () => i.delete(e)), a && e.close();
360
+ }, c = (t, n) => {
361
+ n.once("finish", () => {
362
+ a && setImmediate(() => e.closeIdleConnections?.());
363
+ });
364
+ }, l = () => {
365
+ process.off("SIGTERM", d), process.off("SIGINT", d), e.off("connection", o), e.off("request", c), e.off("session", s);
366
+ }, u = () => a ??= (async () => {
367
+ let a = !1, o = !1, s = new Promise((t) => e.close(() => t()));
368
+ e.closeIdleConnections?.();
369
+ for (let e of i) e.close();
370
+ let c = Promise.resolve().then(() => t.dispose()).then(() => {
371
+ a = !0;
372
+ }, () => {
373
+ a = !0, o = !0;
374
+ }), u, d = await Promise.race([Promise.all([s, c]).then(() => !1), new Promise((e) => {
375
+ u = setTimeout(() => e(!0), n);
376
+ })]);
377
+ if (clearTimeout(u), d) {
378
+ e.closeAllConnections?.();
379
+ for (let e of i) e.destroy();
380
+ for (let e of r) e.destroy();
381
+ }
382
+ r.clear(), i.clear(), l();
383
+ let f = {
384
+ forced: d,
385
+ cleanupCompleted: a,
386
+ cleanupFailed: o
387
+ };
388
+ return t.onComplete?.(f), f;
389
+ })(), d = () => {
390
+ u();
391
+ };
392
+ return e.on("connection", o), e.on("request", c), e.on("session", s), process.on("SIGTERM", d), process.on("SIGINT", d), {
393
+ shutdown: u,
394
+ uninstall: l
395
+ };
396
+ }
397
+ //#endregion
129
398
  //#region src/index.ts
130
- var m = { name: "node" };
131
- function h(e) {
399
+ var T = { name: "node" }, E = class extends Error {
400
+ constructor() {
401
+ super("Node runtime instance limit reached");
402
+ }
403
+ };
404
+ function D(e) {
132
405
  if (e === null) return {};
133
406
  let t = JSON.parse(e);
134
407
  if (!t || typeof t != "object" || Array.isArray(t)) throw TypeError("WebSocket route params must be a JSON object");
@@ -139,9 +412,10 @@ function h(e) {
139
412
  }
140
413
  return n;
141
414
  }
142
- var g = class {
415
+ var O = class {
143
416
  wss;
144
417
  instances = /* @__PURE__ */ new Map();
418
+ pendingInstances = /* @__PURE__ */ new Map();
145
419
  componentRegistry;
146
420
  allowedOrigins;
147
421
  authenticate;
@@ -150,101 +424,135 @@ var g = class {
150
424
  maxInstances;
151
425
  idleTimeoutMs;
152
426
  constructor(e) {
153
- this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, this.env = e.env, this.maxInstances = e.maxInstances ?? 512, this.idleTimeoutMs = e.idleTimeoutMs ?? 15 * 6e4, e.server.on("upgrade", (t, n, r) => {
154
- new a(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
427
+ if (this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, this.env = e.env, this.maxInstances = e.maxInstances ?? 512, this.idleTimeoutMs = e.idleTimeoutMs ?? 15 * 6e4, !Number.isInteger(this.maxInstances) || this.maxInstances < 1 || !Number.isFinite(this.idleTimeoutMs) || this.idleTimeoutMs < 0) throw TypeError("Node runtime requires positive integer maxInstances and nonnegative finite idleTimeoutMs");
428
+ e.server.on("upgrade", (t, n, r) => {
429
+ new s(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
155
430
  });
156
431
  }
157
432
  handleUpgrade(e, t, n) {
158
- let o = new a(e.url || "", `http://${e.headers.host}`).toString(), s = e.headers.origin;
159
- if (!i(s, o, this.allowedOrigins)) {
433
+ let r = new s(e.url || "", `http://${e.headers.host}`).toString(), i = e.headers.origin;
434
+ if (!a(i, r, this.allowedOrigins)) {
160
435
  t.destroy();
161
436
  return;
162
437
  }
163
438
  this.wss.handleUpgrade(e, t, n, async (t) => {
164
- let n = new a(e.url || "", `http://${e.headers.host}`), i = n.pathname.split("/"), o = i.pop(), s = i.pop(), c = n.searchParams, u = c.get("routePath") || c.get("componentPath") || c.get("componentId");
165
- if (!o || !u) {
439
+ let n = new s(e.url || "", `http://${e.headers.host}`), r = n.pathname.split("/"), i = r.pop(), a = r.pop(), o = n.searchParams, c = o.get("routePath") || o.get("componentPath") || o.get("componentId");
440
+ if (!i || !c) {
166
441
  t.close(1008, "Missing target or routePath");
167
442
  return;
168
443
  }
169
- let d;
444
+ let l;
170
445
  try {
171
- d = h(c.get("params"));
446
+ l = D(o.get("params"));
172
447
  } catch {
173
448
  t.close(1008, "Invalid route params");
174
449
  return;
175
450
  }
176
- let f = this.componentRegistry.get(u);
177
- if (!f) {
451
+ let u = this.componentRegistry.get(c);
452
+ if (!u) {
178
453
  t.close(1008, "Component not found");
179
454
  return;
180
455
  }
181
- let p;
456
+ let d;
182
457
  try {
183
- p = this.authenticate ? await this.authenticate(e) : this.defaultUser;
184
- } catch (e) {
185
- console.error("[Cossack] Authentication failed, rejecting upgrade:", e), t.close(1008, "Authentication failed");
458
+ d = this.authenticate ? await this.authenticate(e) : this.defaultUser;
459
+ } catch {
460
+ _({ runtime: "node" }, "authentication"), t.close(1008, "Authentication failed");
186
461
  return;
187
462
  }
188
- let m = c.get("pathname") || "/", g = {
189
- get: (e) => e === "user" ? p : void 0,
463
+ let f = o.get("pathname") || "/", p = {
464
+ get: (e) => e === "user" ? d : void 0,
465
+ env: this.env,
190
466
  req: {
191
- path: m,
192
- param: (e) => e ? d[e] : { ...d },
467
+ header: (t) => {
468
+ let n = new Headers();
469
+ for (let t = 0; t < e.rawHeaders.length; t += 2) n.append(e.rawHeaders[t], e.rawHeaders[t + 1]);
470
+ return t === void 0 ? Object.fromEntries(n) : n.get(t) ?? void 0;
471
+ },
472
+ path: f,
473
+ param: (e) => e ? l[e] : { ...l },
193
474
  query: (e) => {
194
- if (e) return c.get(e);
475
+ if (e) return o.get(e);
195
476
  let t = {};
196
- return c.forEach((e, n) => {
477
+ return o.forEach((e, n) => {
197
478
  t[n] = e;
198
479
  }), t;
199
480
  }
200
481
  }
201
- }, _ = Reflect.getMetadata("page:options", f), v;
482
+ }, m = Reflect.getMetadata("page:options", u), h;
202
483
  try {
203
- v = _?.scope ? await _.scope(g) : `user:${p?.id || "anonymous"}`;
204
- } catch (e) {
205
- console.error("[Cossack] Failed to resolve Node WebSocket scope:", e), t.close(1008, "Invalid WebSocket scope");
484
+ h = m?.scope ? await m.scope(p) : `user:${d?.id || "anonymous"}`;
485
+ } catch {
486
+ _({ runtime: "node" }, "scope"), t.close(1008, "Invalid WebSocket scope");
206
487
  return;
207
488
  }
208
- if (o !== v) {
489
+ if (i !== h) {
209
490
  t.close(1008, "Invalid WebSocket scope");
210
491
  return;
211
492
  }
212
- let y = `${u}:${s ?? "page"}:${o}`;
213
- this.pruneInstances(!0);
214
- let b = this.instances.get(y), x = b?.runtime;
215
- if (!x) {
216
- if (this.instances.size >= this.maxInstances) {
217
- t.close(1013, "Runtime instance limit reached");
218
- return;
219
- }
220
- let e = r(f);
221
- await e.bootstrap({
222
- context: g,
223
- user: p,
224
- env: this.env,
225
- runtime: {
226
- platform: "web",
227
- adapter: "node"
228
- },
229
- page: m,
230
- providerName: s
231
- }), x = new l(e), b = {
232
- runtime: x,
233
- lastActive: Date.now()
234
- }, this.instances.set(y, b);
493
+ let g = `${c}:${a ?? "page"}:${i}`, v;
494
+ try {
495
+ v = await this.getOrCreateRuntime(g, u, {
496
+ context: p,
497
+ user: d,
498
+ pathname: f,
499
+ provider: a
500
+ });
501
+ } catch (e) {
502
+ _({ runtime: "node" }, "initialization"), t.close(1013, e instanceof E ? "Runtime instance limit reached" : "Runtime unavailable");
503
+ return;
504
+ }
505
+ let y = v.runtime;
506
+ v.lastActive = Date.now(), y.addClient(t, d, p);
507
+ try {
508
+ await y.sendInitialState(t);
509
+ } catch {
510
+ _({ runtime: "node" }, "initial-state"), t.close(1011, "Runtime unavailable");
235
511
  }
236
- b.lastActive = Date.now(), x.addClient(t, p);
237
- let S = x.component.getInitialState();
238
- t.send(JSON.stringify({
239
- type: "state-update",
240
- state: S
241
- }));
242
512
  });
243
513
  }
514
+ async getOrCreateRuntime(e, t, n) {
515
+ let r = this.instances.get(e);
516
+ if (r) return r;
517
+ let a = this.pendingInstances.get(e);
518
+ if (!a) {
519
+ if (this.pruneInstances(!0), this.instances.size + this.pendingInstances.size >= this.maxInstances) throw new E();
520
+ a = (async () => {
521
+ let r = i(t);
522
+ try {
523
+ await r.bootstrap({
524
+ context: n.context,
525
+ user: n.user,
526
+ env: this.env,
527
+ runtime: {
528
+ platform: "web",
529
+ adapter: "node"
530
+ },
531
+ page: n.pathname,
532
+ providerName: n.provider
533
+ });
534
+ } catch (e) {
535
+ throw await r.destroyAsync().catch((e) => {
536
+ _({ runtime: "node" }, "component-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED");
537
+ }), e;
538
+ }
539
+ let a = {
540
+ runtime: new v(r),
541
+ lastActive: Date.now()
542
+ };
543
+ return this.instances.set(e, a), a;
544
+ })(), this.pendingInstances.set(e, a);
545
+ }
546
+ try {
547
+ return await a;
548
+ } finally {
549
+ this.pendingInstances.get(e) === a && this.pendingInstances.delete(e);
550
+ }
551
+ }
244
552
  pruneInstances(e = !1) {
245
553
  let t = Date.now();
246
554
  for (let [e, n] of this.instances) n.runtime.clientCount === 0 && t - n.lastActive >= this.idleTimeoutMs && this.instances.delete(e);
247
- let n = Math.max(0, this.maxInstances - +!!e);
555
+ let n = Math.max(0, this.maxInstances - +!!e - this.pendingInstances.size);
248
556
  if (this.instances.size <= n) return;
249
557
  let r = [...this.instances.entries()].filter(([, e]) => e.runtime.clientCount === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
250
558
  for (let [e] of r) {
@@ -254,4 +562,4 @@ var g = class {
254
562
  }
255
563
  };
256
564
  //#endregion
257
- export { g as CossackNodeAdapter, l as NodeWebSocketRuntime, p as createNodeEmailSender, m as nodeRuntimeAdapter, d as serveStatic };
565
+ export { O as CossackNodeAdapter, v as NodeWebSocketRuntime, C as createNodeAdapter, S as createNodeEmailSender, w as installNodeShutdown, T as nodeRuntimeAdapter, b as serveStatic };
@@ -0,0 +1,4 @@
1
+ import { type EmailDeliveryProvider } from '@cossackframework/core/notifications';
2
+ import type { NodeEmailSender } from './email.js';
3
+ /** Adapt createNodeEmailSender() or another explicit structural SMTP sender. */
4
+ export declare function createSmtpNotificationEmailProvider(sender: NodeEmailSender): EmailDeliveryProvider;
@@ -0,0 +1,40 @@
1
+ import { NotificationDeliveryError as e } from "@cossackframework/core/notifications";
2
+ //#region src/notifications.ts
3
+ function t(t) {
4
+ return Object.freeze({
5
+ idempotency: "none",
6
+ async send(n) {
7
+ let { to: r, from: i, subject: a, html: o, text: s } = n;
8
+ if (![
9
+ r,
10
+ i,
11
+ a,
12
+ o,
13
+ s
14
+ ].every((e) => typeof e == "string") || !r || !i || !a || /[\r\n]/.test(r + i + a) || new TextEncoder().encode(r + i + a + o + s).byteLength > 256 * 1024) throw new e("rejected");
15
+ try {
16
+ let n = await t.send({
17
+ to: r,
18
+ from: i,
19
+ subject: a,
20
+ html: o,
21
+ text: s
22
+ }), c = n && typeof n == "object" ? Object.getOwnPropertyDescriptor(n, "messageId") : void 0, l = c && "value" in c ? c.value : void 0;
23
+ if (typeof l != "string" || !/^[\x21-\x7e]{1,255}$/.test(l)) throw new e("unknown");
24
+ return Object.freeze({
25
+ status: "provider-accepted",
26
+ messageId: l
27
+ });
28
+ } catch (t) {
29
+ let n;
30
+ try {
31
+ let e = t && typeof t == "object" ? Object.getOwnPropertyDescriptor(t, "responseCode") : void 0;
32
+ n = e && "value" in e ? e.value : void 0;
33
+ } catch {}
34
+ throw typeof n == "number" && Number.isInteger(n) && n >= 400 && n <= 599 ? new e("rejected", { retryable: n < 500 }) : new e("unknown");
35
+ }
36
+ }
37
+ });
38
+ }
39
+ //#endregion
40
+ export { t as createSmtpNotificationEmailProvider };