@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/README.md CHANGED
@@ -10,11 +10,12 @@ Cossack and its packages.
10
10
 
11
11
  ## Exports
12
12
 
13
- - `CossackNodeAdapter` : handles WebSocket upgrades and component bootstrapping on a Node `http.Server`.
14
- - `nodeRuntimeAdapter` : pass to `createApp()` so SSR emits Node process-local WebSocket targets.
13
+ - `createNodeAdapter` : connects framework-guarded WebSocket upgrades to a Node server, shares process-local scope instances, and manages cleanup.
14
+ - `CossackNodeAdapter` and `nodeRuntimeAdapter` : legacy registry adapter and metadata-only adapter; generated apps use `createNodeAdapter`.
15
15
  - `serveStatic` : Node `fs`-based Hono middleware for serving static assets.
16
16
  - `NodeWebSocketRuntime` : the WebSocket runtime used by the adapter.
17
17
  - `createNodeEmailSender` : Node.js polyfill for Cloudflare's `send_email` binding (`env.EMAIL`).
18
+ - `cossackNode` from `/vite`: standalone Vite HTTP development integration; see the lifecycle limits below.
18
19
 
19
20
  ## Unified `env.EMAIL` (Cloudflare email binding polyfill)
20
21
 
@@ -29,23 +30,23 @@ Cloudflare Workers expose `env.EMAIL.send({ to, from, subject, html, text })` wh
29
30
  Then `await env.EMAIL.send({ to, from, subject, html, text })` works directly.
30
31
 
31
32
  ### Node.js
32
- Build the sender from SMTP env vars and inject it into `env`, then pass `env` both to `app.fetch` (HTTP transport) and to `CossackNodeAdapter` (WebSocket transport):
33
+ Build the sender from SMTP env vars and inject it into `env`, then pass `env` `app.fetch` for both HTTP requests and WebSocket authorization:
33
34
 
34
35
  ```ts
35
36
  import { serve } from '@hono/node-server';
36
37
  import { createApp } from '@cossackframework/framework/router';
37
38
  import {
38
- CossackNodeAdapter,
39
+ createNodeAdapter,
39
40
  createNodeEmailSender,
40
- nodeRuntimeAdapter,
41
41
  } from '@cossackframework/node-adapter';
42
42
  import { App } from './App';
43
43
  import { template } from './root';
44
44
 
45
+ const runtime = createNodeAdapter();
45
46
  const app = createApp({
46
47
  AppComponent: App,
47
48
  htmlTemplate: template,
48
- runtimeAdapter: nodeRuntimeAdapter,
49
+ runtimeAdapter: runtime,
49
50
  });
50
51
 
51
52
  const env = {
@@ -64,14 +65,8 @@ const server = serve(
64
65
  (info) => console.log(`Listening on http://localhost:${info.port}`),
65
66
  );
66
67
 
67
- // WebSocket: pass the same env so `@Server` methods over WS see `this.env.EMAIL`.
68
- new CossackNodeAdapter({
69
- server,
70
- // Keys match the routePath metadata emitted by Cossack, for example
71
- // new Map([['/account/:id', AccountPage]]).
72
- componentRegistry,
73
- env,
74
- });
68
+ // Run upgrades through the same middleware, bindings, scope checks, and services.
69
+ runtime.attach(server, (request) => app.fetch(request, env));
75
70
  ```
76
71
 
77
72
  ### Environment variables
@@ -87,3 +82,74 @@ Configure via `.dev.vars` (Cloudflare dev) or your shell/`.env` (Node):
87
82
  | `MAIL_FROM` | Default `from` address when omitted | `no-reply@example.com` |
88
83
 
89
84
  Now `await this.env.EMAIL.send(...)` works identically in `@Server` methods on both Cloudflare Workers and Node.js.
85
+
86
+ ## WebSocket lifetime
87
+
88
+ `runtime.attach(server, fetch)` handles `/ws/` upgrade requests. Other upgrade
89
+ paths remain available to the host. Authentication, origin checks, route lookup,
90
+ and scope authorization run through the framework before the handshake. Response
91
+ cookies and application headers reach the handshake. Components for the same
92
+ route/provider/scope share one initialization and process-local state.
93
+
94
+ `maxInstances` defaults to 512 and includes pending initialization.
95
+ `idleTimeoutMs` defaults to 15 minutes; pruning runs on socket activity.
96
+ Call `await runtime.dispose()` before closing an embedded server. It detaches
97
+ upgrade listeners, ends sockets, waits for pending initialization and active
98
+ actions, and destroys components/services. Repeated calls share the same result.
99
+ A native server `close` event also triggers disposal. Actions must settle for
100
+ cleanup to finish. Disposed adapters cannot be attached again.
101
+
102
+ The request scheme follows the actual Node socket (HTTP or TLS); the adapter does
103
+ not trust forwarded scheme headers. Configure origin policy for a trusted proxy
104
+ in the application. Generated production and development entries attach the adapter automatically.
105
+ The dev server disposes the previous runtime on source reload while Vite retains
106
+ its HMR connection; clients reconnect to a fresh process-local scope.
107
+
108
+ ## Vite development HTTP server
109
+
110
+ Generated Node Vite configurations include the separate tooling entry:
111
+
112
+ ```ts
113
+ import { cossackNode } from '@cossackframework/node-adapter/vite';
114
+
115
+ // Add to the existing Vite plugins, alongside the Cossack framework plugins.
116
+ cossackNode();
117
+ ```
118
+
119
+ This makes `cossack dev` and plain `vite dev` serve the exported `app` from
120
+ `/src/index.ts`. The entry can also export `env` and a runtime with `dispose()`
121
+ and `attach()`. The adapter imports no framework code. Vite remains an optional
122
+ peer dependency and is not imported by the main runtime entry.
123
+
124
+ The HTTP middleware runs after Vite's public asset and module handlers. A separate
125
+ `/ws/` listener loads the same application before the first WebSocket upgrade,
126
+ including when no application HTTP request has run. Other upgrade paths remain
127
+ with Vite. Server-source edits replace the server module graph, detach and dispose
128
+ the old runtime, and close its sockets. The browser HMR connection stays open.
129
+ Cleanup can continue while the replacement runtime starts; source reload does
130
+ not undo in-flight application effects.
131
+ An edit during asynchronous initialization discards the stale entry before it can
132
+ accept a request. Initialization failures retry with a fresh entry.
133
+
134
+ Generated entries export `createEnv(variables)`. The plugin passes values from
135
+ Vite's environment files, with process variables taking precedence. The factory
136
+ preserves arbitrary bindings, supplies the `DB_PATH` default, and configures
137
+ `EMAIL` when `SMTP_HOST` is present. SMTP configuration requires `SMTP_USER` and
138
+ `SMTP_PASS`. The same factory supplies production bindings. Private bindings are
139
+ not added to Vite's client environment; the existing `VITE_` public-prefix rule
140
+ still applies. Custom entries without a factory retain their exported `env`.
141
+
142
+ The generated `scripts/dev.js` is a thin Vite launcher. It retains the optional
143
+ `COSSACK_LOCAL` overlay and its `PORT`/3000 default; application routing, upgrades,
144
+ bindings and cleanup all use the plugin. Plain `vite dev` and `cossack dev` use
145
+ Vite's usual port options. Both normal and JSON CLI development commands supervise
146
+ the child process and bound requested shutdown.
147
+
148
+ Closing Vite waits up to five seconds for runtime cleanup; use
149
+ `cossackNode({ entry: '/src/custom.ts', shutdownTimeoutMs: 2000 })` to change the
150
+ entry or deadline. A deadline stops waiting; it cannot terminate application I/O.
151
+ Embedded Vite servers (`server.middlewareMode`) retain ownership of their listener
152
+ and lifecycle and are not installed by this plugin.
153
+
154
+ This plugin applies only to development. Production keeps the generated Node
155
+ server and static-file middleware. The plugin is omitted from Desktop mode.
@@ -0,0 +1,59 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "guides": [
4
+ {
5
+ "id": "node-runtime-lifecycle",
6
+ "title": "Attach and dispose the Node WebSocket runtime",
7
+ "summary": "Connect the process-local runtime to the host HTTP server after the framework fetch handler, preserve guarded upgrade checks, and await cleanup before shutdown.",
8
+ "imports": [
9
+ "@cossackframework/node-adapter",
10
+ "@cossackframework/node-adapter/vite"
11
+ ],
12
+ "markdown": "# Run the Node adapter with an explicit lifecycle\n\n`createNodeAdapter` handles only the framework's guarded `/ws/` upgrades. Keep ordinary HTTP handling on the framework's fetch handler, then pass that same handler to `runtime.attach(server, fetch)`. This ensures the framework runs middleware, origin checks, authorization and scope selection before the adapter accepts a socket. The adapter does not make WebSocket state durable or shared across Node processes.\n\nCall `await runtime.dispose()` before closing an embedded server. Disposal detaches listeners, closes sockets and waits for active actions and component cleanup. Do not use the legacy `CossackNodeAdapter` when generating new applications; generated apps use `createNodeAdapter`.\n\nFor Vite development, import `cossackNode` from the separate `/vite` entry. It is a development integration, not the production server; production uses the generated Node entry and static asset server.\n\nThe generated production entry explicitly calls `installNodeShutdown(server, { dispose: () => runtime.dispose(), onComplete })`. This installs SIGTERM/SIGINT handlers, stops HTTP admission, closes idle connections after accepted responses finish, and gives HTTP draining and runtime disposal one 10-second deadline. Repeated signals share the same drain. At the deadline it destroys remaining sockets and reports `forced`; ignored application I/O is not claimed complete. Generated entries exit 0 after a successful drain and 1 after forced or failed cleanup. Embedded hosts choose whether to install process handlers and what `onComplete` does; importing the adapter installs none. Call the returned `uninstall()` only when relinquishing that explicit ownership.\n",
13
+ "examples": [
14
+ {
15
+ "id": "attach-and-dispose",
16
+ "language": "typescript",
17
+ "source": "import { createServer } from 'node:http';\nimport { createNodeAdapter } from '@cossackframework/node-adapter';\n\nconst server = createServer();\nconst runtime = createNodeAdapter({ maxInstances: 32, idleTimeoutMs: 30_000 });\nruntime.attach(server, async () => new Response('framework response'));\nif (server.listenerCount('upgrade') !== 1) throw new Error('Expected the runtime upgrade listener');\nawait runtime.dispose();\nif (server.listenerCount('upgrade') !== 0) throw new Error('Disposal must detach the host listener');"
18
+ },
19
+ {
20
+ "id": "configure-vite-development",
21
+ "language": "typescript",
22
+ "source": "import { cossackNode } from '@cossackframework/node-adapter/vite';\n\nconst plugin = cossackNode({ entry: '/src/index.ts', shutdownTimeoutMs: 2_000 });\nif (plugin.name !== 'cossack-node-development' || plugin.apply !== 'serve') {\n throw new Error('The Node adapter plugin is a Vite development-only integration');\n}"
23
+ }
24
+ ]
25
+ },
26
+ {
27
+ "id": "notification-smtp-adapter",
28
+ "title": "Adapt SMTP with explicit delivery uncertainty",
29
+ "summary": "Adapt SMTP with explicit delivery uncertainty.",
30
+ "imports": [
31
+ "@cossackframework/node-adapter/notifications"
32
+ ],
33
+ "markdown": "Wrap the existing createNodeEmailSender with createSmtpNotificationEmailProvider and pass private SMTP host/port/credentials through server configuration. The provider accepts the structural NodeEmailSender contract, copies declared message fields, and does not send during construction. Neither SMTP response acceptance nor a messageId proves final delivery. Provider idempotency is none: the runtime key is not sent as a fabricated SMTP guarantee.\n\nNumeric SMTP 400-599 responseCode is an explicit rejection; 400-499 permits a safe runtime retry. Other thrown errors or malformed acceptance mean unknown. The adapter sends once and returns fixed redacted NotificationDeliveryError fields without transport messages/credentials. It rejects header injection and messages above its 256 KiB UTF-8 bound before I/O. Unknown outcomes must be reconciled, not blindly retried. Use a durable notification store for restart safety.\n\nThe executable example injects a structural sender and sends no mail. The separate real loopback SMTP acceptance covers preview without network, preaccept450 rejection/retry, exactly one DATA for the accepted operation, duplicate suppression and ambiguous post-DATA socket failure with SQLite restart/no resend. It uses no external account or email. See docs/notification-providers.md.",
34
+ "examples": [
35
+ {
36
+ "id": "notification-smtp-rejection",
37
+ "language": "typescript",
38
+ "source": "import { createSmtpNotificationEmailProvider } from '@cossackframework/node-adapter/notifications';\nimport { isNotificationDeliveryError } from '@cossackframework/core/notifications';\nlet sends = 0;\nconst provider = createSmtpNotificationEmailProvider({ async send() {\n sends++; throw Object.assign(Error('PRIVATE_SMTP_RESPONSE'), { responseCode: 450 });\n} });\nconst message = { to: 'recipient@example.test', from: 'sender@example.test', subject: 'Receipt', text: 'fixture', html: '<p>fixture</p>' };\nlet rejection: unknown;\ntry { await provider.send(message, { idempotencyKey: 'fixture-key' }); } catch (error) { rejection = error; }\nif (!isNotificationDeliveryError(rejection) || rejection.outcome !== 'rejected' || !rejection.retryable) throw Error('Explicit preaccept rejection should permit a safe runtime retry');\nif (provider.idempotency !== 'none' || Number(sends) !== 1 || rejection.message.includes('PRIVATE_')) throw Error('SMTP adapter must not retry or leak transport errors');\nconst uncertain = createSmtpNotificationEmailProvider({ async send() { throw Error('Unknown transport failure'); } });\nlet ambiguity: unknown;\ntry { await uncertain.send(message, { idempotencyKey: 'fixture-key' }); } catch (error) { ambiguity = error; }\nif (!isNotificationDeliveryError(ambiguity) || ambiguity.outcome !== 'unknown') throw Error('Ambiguous failures must stop non-idempotent retries');\n// Injected structural sender: no network. In applications wrap createNodeEmailSender().\n"
39
+ }
40
+ ]
41
+ },
42
+ {
43
+ "id": "authorized-local-storage",
44
+ "title": "Store authorized streamed files on Node",
45
+ "summary": "Wrap LocalStorageProvider in Storage to enforce authenticated tenant keys, byte limits and content types before provider I/O. Pass a request AbortSignal and consume or cancel download bodies. Progress counts bytes rather than final publication. Keys are validated independently by the provider.",
46
+ "imports": [
47
+ "@cossackframework/node-adapter/storage"
48
+ ],
49
+ "markdown": "Wrap LocalStorageProvider in Storage to enforce authenticated tenant keys, byte limits and content types before provider I/O. Pass a request AbortSignal and consume or cancel download bodies. Progress counts bytes rather than final publication. Keys are validated independently by the provider.\n\nThe local root persists immutable generations and atomically publishes metadata. Same-process instances serialize writes. Give the root and its parents trusted filesystem ownership and one Node process. This is not a distributed lock or a sudden-power-loss durability guarantee. Failed/cancelled transfers remove unpublished files; interrupted processes can leave orphan generations. Use real filesystem acceptance for persistence and cancellation. The example creates and removes a temporary root, uses public exports, and opens no network connections.",
50
+ "examples": [
51
+ {
52
+ "id": "authorized-local-storage-example",
53
+ "language": "typescript",
54
+ "source": "import { mkdtemp, rm } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\nimport { Storage } from '@cossackframework/core/storage';\nimport { LocalStorageProvider } from '@cossackframework/node-adapter/storage';\nconst root = await mkdtemp(join(tmpdir(), 'cossack-guide-'));\ntry {\n const storage = new Storage<{tenant: string}>({ provider: new LocalStorageProvider({root}), maxBytes: 1024,\n authorize: ({context, key}) => key.startsWith(context.tenant + '/') });\n const context = {tenant: 'demo'};\n await storage.put(context, 'demo/report', new Blob(['report']).stream(), {size: 6, contentType: 'text/plain'});\n const object = await storage.get(context, 'demo/report');\n if (!object || await new Response(object.body).text() !== 'report') throw Error('Missing persisted report');\n await storage.delete(context, 'demo/report');\n} finally { await rm(root, {recursive: true, force: true}); }\n"
55
+ }
56
+ ]
57
+ }
58
+ ]
59
+ }
@@ -0,0 +1,37 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { Duplex } from 'node:stream';
3
+ import type { Context } from 'hono';
4
+ import { type Cossack } from '@cossackframework/core';
5
+ /** Structural router contract: the Node library does not import the framework. */
6
+ export interface NodeWebSocketUpgrade {
7
+ target: string;
8
+ provider: string;
9
+ componentId: string;
10
+ user?: unknown;
11
+ context?: Context;
12
+ authorize?: (operation: (context: Context) => Promise<void>) => Promise<boolean>;
13
+ rejectAuthorization?: boolean;
14
+ createComponent(): Promise<Cossack>;
15
+ }
16
+ /** Host event contract for HTTP/1.1 WebSocket upgrade handling. */
17
+ export interface NodeUpgradeServer {
18
+ on(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
19
+ once(event: 'close', listener: () => void): unknown;
20
+ off(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
21
+ off(event: 'close', listener: () => void): unknown;
22
+ }
23
+ export interface NodeAdapterOptions {
24
+ maxInstances?: number;
25
+ idleTimeoutMs?: number;
26
+ }
27
+ /** Run the entire application's middleware before accepting a Node upgrade. */
28
+ export declare function createNodeAdapter(options?: NodeAdapterOptions): {
29
+ name: string;
30
+ readonly instanceCount: number;
31
+ getClientMetadata: () => {
32
+ platform: string;
33
+ };
34
+ dispose: () => Promise<void>;
35
+ handleWebSocketUpgrade(context: Context, upgrade: NodeWebSocketUpgrade): Response;
36
+ attach(server: NodeUpgradeServer, fetch: (request: Request) => Response | Promise<Response>): () => void;
37
+ };
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import type { IncomingMessage, Server } from 'http';
2
2
  import type { Cossack } from '@cossackframework/core';
3
- export * from './runtime';
3
+ export * from './runtime.js';
4
4
  /** Pass to `createApp({ runtimeAdapter })` so SSR emits process-runtime targets. */
5
5
  export declare const nodeRuntimeAdapter: {
6
6
  readonly name: 'node';
7
7
  };
8
- export { serveStatic, type StaticServeOptions } from './static-serve';
9
- export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email';
8
+ export { serveStatic, type StaticServeOptions } from './static-serve.js';
9
+ export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email.js';
10
10
  export interface CossackNodeAdapterOptions {
11
11
  server: Server;
12
12
  componentRegistry: Map<string, new () => Cossack>;
@@ -42,6 +42,7 @@ export interface CossackNodeAdapterOptions {
42
42
  export declare class CossackNodeAdapter {
43
43
  private wss;
44
44
  private instances;
45
+ private pendingInstances;
45
46
  private componentRegistry;
46
47
  private allowedOrigins?;
47
48
  private authenticate?;
@@ -51,5 +52,8 @@ export declare class CossackNodeAdapter {
51
52
  private idleTimeoutMs;
52
53
  constructor(options: CossackNodeAdapterOptions);
53
54
  private handleUpgrade;
55
+ private getOrCreateRuntime;
54
56
  private pruneInstances;
55
57
  }
58
+ export { createNodeAdapter, type NodeAdapterOptions, type NodeWebSocketUpgrade, type NodeUpgradeServer } from "./adapter.js";
59
+ export { installNodeShutdown, type NodeShutdownServer, type NodeShutdownOptions, type NodeShutdownResult } from './shutdown.js';