@cossackframework/node-adapter 0.8.3 → 0.9.1
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 +91 -19
- package/agent-docs.json +59 -0
- package/dist/adapter.d.ts +55 -0
- package/dist/application.d.ts +39 -0
- package/dist/index.d.ts +5 -55
- package/dist/index.js +445 -177
- package/dist/notifications.d.ts +4 -0
- package/dist/notifications.js +40 -0
- package/dist/shutdown.d.ts +24 -0
- package/dist/static-serve.d.ts +9 -0
- package/dist/storage.d.ts +26 -0
- package/dist/storage.js +241 -0
- package/dist/transport-routes-CjDWcC93.js +32 -0
- package/dist/vite.d.ts +23 -0
- package/dist/vite.js +128 -0
- package/package.json +28 -8
- package/dist/runtime.d.ts +0 -6
package/README.md
CHANGED
|
@@ -10,11 +10,12 @@ Cossack and its packages.
|
|
|
10
10
|
|
|
11
11
|
## Exports
|
|
12
12
|
|
|
13
|
-
- `
|
|
14
|
-
- `
|
|
15
|
-
- `
|
|
16
|
-
- `
|
|
17
|
-
- `createNodeEmailSender
|
|
13
|
+
- `createNodeAdapter`: connects framework-guarded WebSocket upgrades to a Node server, shares process-local scope instances, and manages cleanup.
|
|
14
|
+
- `serveStatic`: Node `fs`-based Hono middleware for serving static assets. It streams files with `Content-Length`, a weak `ETag`, `Last-Modified` and `Accept-Ranges: bytes`. A matching `If-None-Match`, or an `If-Modified-Since` when no `If-None-Match` is sent, returns `304`. A single `Range` on GET returns `206` with `Content-Range`, or `416` when it starts past the end; several ranges return the whole file. `If-Range` accepts only an unchanged `Last-Modified` date. HEAD returns the GET headers without a body. `prefix` matches whole path segments (`/assets` does not match `/assets-x`).
|
|
15
|
+
- `createStaticAssets`: an `ASSETS`-style binding backed by `serveStatic`.
|
|
16
|
+
- `installNodeShutdown`: SIGTERM/SIGINT draining for a Node server and its runtime.
|
|
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
|
|
33
|
+
Build the sender from SMTP environment variables and inject it into `env`. Pass `env` to `app.fetch` for 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
|
-
|
|
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:
|
|
49
|
+
runtimeAdapter: runtime,
|
|
49
50
|
});
|
|
50
51
|
|
|
51
52
|
const env = {
|
|
@@ -64,22 +65,16 @@ const server = serve(
|
|
|
64
65
|
(info) => console.log(`Listening on http://localhost:${info.port}`),
|
|
65
66
|
);
|
|
66
67
|
|
|
67
|
-
//
|
|
68
|
-
|
|
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
|
|
78
|
-
Configure
|
|
73
|
+
Configure through `.dev.vars` for Cloudflare development, or through your shell or an `.env` file for Node:
|
|
79
74
|
|
|
80
75
|
| Variable | Description | Default |
|
|
81
76
|
| -------------- | -------------------------------------------- | ------------------ |
|
|
82
|
-
| `SMTP_HOST` | SMTP server host (
|
|
77
|
+
| `SMTP_HOST` | SMTP server host (for example `smtp.gmail.com`) | : |
|
|
83
78
|
| `SMTP_PORT` | SMTP server port | `587` |
|
|
84
79
|
| `SMTP_SECURE` | Use TLS (`"true"` for port 465) | `port === 465` |
|
|
85
80
|
| `SMTP_USER` | SMTP username | : |
|
|
@@ -87,3 +82,80 @@ 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 are answered with `404` and closed when the adapter is the only `upgrade`
|
|
90
|
+
listener on the server; when another listener is attached they remain with the
|
|
91
|
+
host. Set `destroyUnmatchedUpgrades: true` or `false` to always or never reject them. Authentication, origin checks, route lookup,
|
|
92
|
+
and scope authorization run through the framework before the handshake. Response
|
|
93
|
+
cookies and application headers reach the handshake. Components for the same
|
|
94
|
+
page target (the page plus its route params, or its scope key) share one
|
|
95
|
+
initialization and process-local state.
|
|
96
|
+
|
|
97
|
+
`maxInstances` defaults to 512 and includes pending initialization.
|
|
98
|
+
`idleTimeoutMs` defaults to 15 minutes. Pruning runs on socket activity.
|
|
99
|
+
`maxPayload` caps one WebSocket message at 1 MiB by default. A larger message
|
|
100
|
+
closes the socket with code 1009 before the server parses it. Raise it only for
|
|
101
|
+
components that need bigger RPC payloads.
|
|
102
|
+
Call `await runtime.dispose()` before closing an embedded server. It detaches
|
|
103
|
+
upgrade listeners, ends sockets, waits for pending initialization and active
|
|
104
|
+
actions, and destroys components/services. Repeated calls share the same result.
|
|
105
|
+
A native server `close` event also triggers disposal. Actions must settle for
|
|
106
|
+
cleanup to finish. Disposed adapters cannot be attached again.
|
|
107
|
+
|
|
108
|
+
The request scheme follows the actual Node socket (HTTP or TLS). The adapter does
|
|
109
|
+
not trust forwarded scheme headers. Configure an origin policy for a trusted proxy
|
|
110
|
+
in the application. Generated production and development entries attach the adapter automatically.
|
|
111
|
+
The dev server disposes the previous runtime on source reload while Vite retains
|
|
112
|
+
its HMR connection. Clients reconnect to a fresh process-local scope.
|
|
113
|
+
|
|
114
|
+
## Vite development HTTP server
|
|
115
|
+
|
|
116
|
+
Generated Node Vite configurations include the separate tooling entry:
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { cossackNode } from '@cossackframework/node-adapter/vite';
|
|
120
|
+
|
|
121
|
+
// Add to the existing Vite plugins, alongside the Cossack framework plugins.
|
|
122
|
+
cossackNode();
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
This makes `cossack dev` and plain `vite dev` serve the exported `app` from
|
|
126
|
+
`/src/index.ts`. The entry can also export `env` and a runtime with `dispose()`
|
|
127
|
+
and `attach()`. The adapter imports no framework code. Vite remains an optional
|
|
128
|
+
peer dependency and is not imported by the main runtime entry.
|
|
129
|
+
|
|
130
|
+
The HTTP middleware runs after Vite's public asset and module handlers. A separate
|
|
131
|
+
`/ws/` listener loads the same application before the first WebSocket upgrade,
|
|
132
|
+
including when no application HTTP request has run. Other upgrade paths remain
|
|
133
|
+
with Vite. Server-source edits replace the server module graph, detach and dispose
|
|
134
|
+
the old runtime, and close its sockets. The browser HMR connection stays open.
|
|
135
|
+
Cleanup can continue while the replacement runtime starts. Source reload does
|
|
136
|
+
not undo in-flight application effects.
|
|
137
|
+
An edit during asynchronous initialization discards the stale entry before it can
|
|
138
|
+
accept a request. Initialization failures retry with a fresh entry.
|
|
139
|
+
|
|
140
|
+
Generated entries export `createEnv(variables)`. The plugin passes values from
|
|
141
|
+
Vite's environment files, with process variables taking precedence. The factory
|
|
142
|
+
preserves arbitrary bindings, supplies the `DB_PATH` default, and configures
|
|
143
|
+
`EMAIL` when `SMTP_HOST` is present. SMTP configuration requires `SMTP_USER` and
|
|
144
|
+
`SMTP_PASS`. The same factory supplies production bindings. Private bindings are
|
|
145
|
+
not added to Vite's client environment. The existing `VITE_` public-prefix rule
|
|
146
|
+
still applies. Custom entries without a factory retain their exported `env`.
|
|
147
|
+
|
|
148
|
+
The generated `scripts/dev.js` is a thin Vite launcher. It retains the optional
|
|
149
|
+
`COSSACK_LOCAL` overlay and its `PORT`/3000 default. Application routing, upgrades,
|
|
150
|
+
bindings, and cleanup all use the plugin. Plain `vite dev` and `cossack dev` use
|
|
151
|
+
Vite's usual port options. Both normal and JSON CLI development commands supervise
|
|
152
|
+
the child process and honor a requested shutdown.
|
|
153
|
+
|
|
154
|
+
Closing Vite waits up to five seconds for runtime cleanup. Use
|
|
155
|
+
`cossackNode({ entry: '/src/custom.ts', shutdownTimeoutMs: 2000 })` to change the
|
|
156
|
+
entry or the deadline. A deadline stops the wait. It cannot terminate application I/O.
|
|
157
|
+
Embedded Vite servers (`server.middlewareMode`) retain ownership of their listener
|
|
158
|
+
and lifecycle and are not installed by this plugin.
|
|
159
|
+
|
|
160
|
+
This plugin applies only to development. Production keeps the generated Node
|
|
161
|
+
server and static-file middleware. The plugin is omitted from Desktop mode.
|
package/agent-docs.json
ADDED
|
@@ -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.\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,55 @@
|
|
|
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
|
+
componentId: string;
|
|
9
|
+
user?: unknown;
|
|
10
|
+
context?: Context;
|
|
11
|
+
authorize?: (operation: (context: Context) => Promise<void>) => Promise<boolean>;
|
|
12
|
+
rejectAuthorization?: boolean;
|
|
13
|
+
createComponent(): Promise<Cossack>;
|
|
14
|
+
}
|
|
15
|
+
/** Host event contract for HTTP/1.1 WebSocket upgrade handling. */
|
|
16
|
+
export interface NodeUpgradeServer {
|
|
17
|
+
on(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
|
|
18
|
+
once(event: 'close', listener: () => void): unknown;
|
|
19
|
+
off(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
|
|
20
|
+
off(event: 'close', listener: () => void): unknown;
|
|
21
|
+
/** Used to decide whether unmatched upgrades belong to another listener. */
|
|
22
|
+
listenerCount?(event: 'upgrade'): number;
|
|
23
|
+
}
|
|
24
|
+
/** Default largest accepted WebSocket message (1 MiB). Larger frames close the socket with 1009. */
|
|
25
|
+
export declare const DEFAULT_WEBSOCKET_MAX_PAYLOAD: number;
|
|
26
|
+
/** @internal Validates the ws `maxPayload`; the ws default (100 MiB) is never used. */
|
|
27
|
+
export declare function websocketMaxPayload(value: number | undefined): number;
|
|
28
|
+
export interface NodeAdapterOptions {
|
|
29
|
+
maxInstances?: number;
|
|
30
|
+
idleTimeoutMs?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Largest accepted WebSocket message in bytes. Defaults to 1 MiB. Larger
|
|
33
|
+
* messages close the connection with code 1009 before they are parsed.
|
|
34
|
+
*/
|
|
35
|
+
maxPayload?: number;
|
|
36
|
+
/**
|
|
37
|
+
* What to do with an upgrade request whose path is outside `/ws/`.
|
|
38
|
+
* `true` answers `404` and closes the socket. `false` leaves it to other
|
|
39
|
+
* listeners, which must then end it. By default the adapter rejects it only
|
|
40
|
+
* when no other `upgrade` listener is attached to the server at that time,
|
|
41
|
+
* so Vite HMR and host-owned WebSocket servers keep working.
|
|
42
|
+
*/
|
|
43
|
+
destroyUnmatchedUpgrades?: boolean;
|
|
44
|
+
}
|
|
45
|
+
/** Run the entire application's middleware before accepting a Node upgrade. */
|
|
46
|
+
export declare function createNodeAdapter(options?: NodeAdapterOptions): {
|
|
47
|
+
name: string;
|
|
48
|
+
readonly instanceCount: number;
|
|
49
|
+
getClientMetadata: () => {
|
|
50
|
+
platform: string;
|
|
51
|
+
};
|
|
52
|
+
dispose: () => Promise<void>;
|
|
53
|
+
handleWebSocketUpgrade(context: Context, upgrade: NodeWebSocketUpgrade): Response;
|
|
54
|
+
attach(server: NodeUpgradeServer, fetch: (request: Request) => Response | Promise<Response>): () => void;
|
|
55
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import type { createNodeAdapter } from './adapter.js';
|
|
3
|
+
type Variables = Record<string, string | undefined>;
|
|
4
|
+
type Bindings = Record<string, unknown>;
|
|
5
|
+
export interface NodeApplicationOptions {
|
|
6
|
+
/** The runtime adapter the framework application was created with. */
|
|
7
|
+
runtime: ReturnType<typeof createNodeAdapter>;
|
|
8
|
+
/** The framework application's `fetch`. */
|
|
9
|
+
fetch(request: Request, env: never): Response | Promise<Response>;
|
|
10
|
+
/** `import.meta.url` of the entry module: the built entry is `dist/server/index.js`, beside `dist/client`. */
|
|
11
|
+
entry: string;
|
|
12
|
+
/** `import.meta.env?.DEV` of the entry module. The Vite plugin makes the bindings in development. */
|
|
13
|
+
dev?: boolean;
|
|
14
|
+
/** More bindings, made from the environment variables. They replace the defaults of the same name. */
|
|
15
|
+
bindings?(variables: Variables): Bindings | Promise<Bindings>;
|
|
16
|
+
/** Runs once the production server listens, with the bindings. */
|
|
17
|
+
started?(env: Bindings): void;
|
|
18
|
+
}
|
|
19
|
+
export interface NodeApplication {
|
|
20
|
+
/** The Hono application: hashed build output first, then the framework. */
|
|
21
|
+
app: Hono;
|
|
22
|
+
/** The binding factory, which production and the Node Vite plugin share. */
|
|
23
|
+
createEnv(variables?: Variables): Promise<Bindings>;
|
|
24
|
+
/** The production bindings; empty in development. */
|
|
25
|
+
env: Bindings;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The Node server of a Cossack application. A project's `src/index.ts` exports its result:
|
|
29
|
+
*
|
|
30
|
+
* export const runtime = createNodeAdapter();
|
|
31
|
+
* const frameworkApp = createApp({ AppComponent: App, htmlTemplate: template, runtimeAdapter: runtime });
|
|
32
|
+
* export const { app, createEnv, env } = await nodeApplication({
|
|
33
|
+
* runtime, fetch: frameworkApp.fetch, entry: import.meta.url, dev: import.meta.env?.DEV,
|
|
34
|
+
* });
|
|
35
|
+
*
|
|
36
|
+
* It starts the server when the entry module is the program Node runs (`node dist/server/index.js`).
|
|
37
|
+
*/
|
|
38
|
+
export declare function nodeApplication(options: NodeApplicationOptions): Promise<NodeApplication>;
|
|
39
|
+
export {};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,55 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export
|
|
4
|
-
|
|
5
|
-
export
|
|
6
|
-
readonly name: 'node';
|
|
7
|
-
};
|
|
8
|
-
export { serveStatic, type StaticServeOptions } from './static-serve';
|
|
9
|
-
export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email';
|
|
10
|
-
export interface CossackNodeAdapterOptions {
|
|
11
|
-
server: Server;
|
|
12
|
-
componentRegistry: Map<string, new () => Cossack>;
|
|
13
|
-
path?: string;
|
|
14
|
-
/**
|
|
15
|
-
* Allowed Origin values for WebSocket upgrades. Defaults to same-origin
|
|
16
|
-
* (the request's own origin). Missing Origin headers are rejected, which
|
|
17
|
-
* blocks cross-site WebSocket hijacking.
|
|
18
|
-
*/
|
|
19
|
-
allowedOrigins?: string[];
|
|
20
|
-
/**
|
|
21
|
-
* Authenticate the WebSocket upgrade, returning the user object the
|
|
22
|
-
* component should run as (e.g. parsed from a cookie/JWT on `request`).
|
|
23
|
-
* Falls back to `defaultUser` then to `{ id: 'anonymous' }`. Provide this
|
|
24
|
-
* for any app with per-user state or authorization — otherwise every
|
|
25
|
-
* connection shares one anonymous identity.
|
|
26
|
-
*/
|
|
27
|
-
authenticate?: (request: IncomingMessage) => Promise<unknown> | unknown;
|
|
28
|
-
/** User used when no `authenticate` hook is provided. Defaults to `{ id: 'anonymous' }`. */
|
|
29
|
-
defaultUser?: unknown;
|
|
30
|
-
/**
|
|
31
|
-
* Runtime bindings to expose to components as `this.env` (mirrors
|
|
32
|
-
* Cloudflare's `env` argument). Use it to supply polyfills such as
|
|
33
|
-
* `{ EMAIL: createNodeEmailSender({...}) }` so the same
|
|
34
|
-
* `this.env.EMAIL.send(...)` call works on both runtimes.
|
|
35
|
-
*/
|
|
36
|
-
env?: Record<string, unknown>;
|
|
37
|
-
/** Maximum number of process-local component instances. Defaults to 512. */
|
|
38
|
-
maxInstances?: number;
|
|
39
|
-
/** Evict disconnected instances after this idle period. Defaults to 15 minutes. */
|
|
40
|
-
idleTimeoutMs?: number;
|
|
41
|
-
}
|
|
42
|
-
export declare class CossackNodeAdapter {
|
|
43
|
-
private wss;
|
|
44
|
-
private instances;
|
|
45
|
-
private componentRegistry;
|
|
46
|
-
private allowedOrigins?;
|
|
47
|
-
private authenticate?;
|
|
48
|
-
private defaultUser;
|
|
49
|
-
private env?;
|
|
50
|
-
private maxInstances;
|
|
51
|
-
private idleTimeoutMs;
|
|
52
|
-
constructor(options: CossackNodeAdapterOptions);
|
|
53
|
-
private handleUpgrade;
|
|
54
|
-
private pruneInstances;
|
|
55
|
-
}
|
|
1
|
+
export { serveStatic, createStaticAssets, type StaticServeOptions } from './static-serve.js';
|
|
2
|
+
export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email.js';
|
|
3
|
+
export { createNodeAdapter, DEFAULT_WEBSOCKET_MAX_PAYLOAD, type NodeAdapterOptions, type NodeWebSocketUpgrade, type NodeUpgradeServer } from './adapter.js';
|
|
4
|
+
export { installNodeShutdown, type NodeShutdownServer, type NodeShutdownOptions, type NodeShutdownResult } from './shutdown.js';
|
|
5
|
+
export { nodeApplication, type NodeApplication, type NodeApplicationOptions } from './application.js';
|