@venturekit/cli 0.0.0-dev.20260522121047 → 0.0.0-dev.20260602192622

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 (41) hide show
  1. package/dist/commands/dev.d.ts.map +1 -1
  2. package/dist/commands/dev.js +53 -1
  3. package/dist/commands/dev.js.map +1 -1
  4. package/dist/commands/migrate.d.ts.map +1 -1
  5. package/dist/commands/migrate.js +13 -5
  6. package/dist/commands/migrate.js.map +1 -1
  7. package/dist/commands/open.d.ts.map +1 -1
  8. package/dist/commands/open.js +5 -1
  9. package/dist/commands/open.js.map +1 -1
  10. package/dist/utils/auto-deps.d.ts.map +1 -1
  11. package/dist/utils/auto-deps.js +11 -0
  12. package/dist/utils/auto-deps.js.map +1 -1
  13. package/dist/utils/cdk-bridge.d.ts +1 -0
  14. package/dist/utils/cdk-bridge.d.ts.map +1 -1
  15. package/dist/utils/cdk-bridge.js +1 -0
  16. package/dist/utils/cdk-bridge.js.map +1 -1
  17. package/dist/utils/config-loader.d.ts +2 -0
  18. package/dist/utils/config-loader.d.ts.map +1 -1
  19. package/dist/utils/config-loader.js +2 -0
  20. package/dist/utils/config-loader.js.map +1 -1
  21. package/dist/utils/dev-cognito-ui-page.d.ts +1 -1
  22. package/dist/utils/dev-cognito-ui-page.d.ts.map +1 -1
  23. package/dist/utils/dev-cognito-ui-page.js +7 -2
  24. package/dist/utils/dev-cognito-ui-page.js.map +1 -1
  25. package/dist/utils/docker-compose.d.ts +13 -1
  26. package/dist/utils/docker-compose.d.ts.map +1 -1
  27. package/dist/utils/docker-compose.js +134 -34
  28. package/dist/utils/docker-compose.js.map +1 -1
  29. package/dist/utils/local-queue.d.ts +57 -29
  30. package/dist/utils/local-queue.d.ts.map +1 -1
  31. package/dist/utils/local-queue.js +257 -139
  32. package/dist/utils/local-queue.js.map +1 -1
  33. package/dist/utils/local-server.d.ts +20 -0
  34. package/dist/utils/local-server.d.ts.map +1 -1
  35. package/dist/utils/local-server.js +75 -6
  36. package/dist/utils/local-server.js.map +1 -1
  37. package/dist/utils/local-ws.d.ts +184 -0
  38. package/dist/utils/local-ws.d.ts.map +1 -0
  39. package/dist/utils/local-ws.js +667 -0
  40. package/dist/utils/local-ws.js.map +1 -0
  41. package/package.json +7 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"local-ws.d.ts","sourceRoot":"","sources":["../../src/utils/local-ws.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgDG;AAEH,OAAO,KAAK,KAAK,IAAI,MAAM,MAAM,CAAC;AAOlC;;;;;GAKG;AACH,MAAM,WAAW,qBAAqB;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED;;;;;GAKG;AACH,KAAK,aAAa,GAAG,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,WAAW,cAAc;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;OAKG;IACH,kBAAkB,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IAE9C;;;OAGG;IACH,eAAe,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAAC;IAE7C;;;OAGG;IACH,gBAAgB,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC;IAE9C;;;;OAIG;IACH,iBAAiB,IAAI,IAAI,CAAC;IAE1B;;;OAGG;IACH,eAAe,IAAI,MAAM,CAAC;IAE1B;;;;;;;;;OASG;IACH,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED,MAAM,WAAW,uBAAuB;IACtC,+DAA+D;IAC/D,WAAW,EAAE,MAAM,CAAC;IACpB,qEAAqE;IACrE,KAAK,EAAE,MAAM,CAAC;IACd,mEAAmE;IACnE,IAAI,EAAE,MAAM,CAAC;IACb;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,YAAY,CAAC,EAAE,cAAc,CAAC;CAC/B;AAcD;;;;;;;;;;;;GAYG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,CAiBpE;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,uBAAuB,GAAG,UAAU,CAqnB7E"}
@@ -0,0 +1,667 @@
1
+ /**
2
+ * Local WebSocket Hub for `vk dev`.
3
+ *
4
+ * # What this does
5
+ *
6
+ * Spins up a `WebSocketServer` on the same HTTP server as the dev
7
+ * routes and emulates API Gateway WebSocket → Lambda routing:
8
+ *
9
+ * - browser opens `ws://localhost:<port>/ws`
10
+ * - we generate a `connectionId` and invoke `src/ws/connect.ts` with
11
+ * a fake `$connect` event in the same shape Lambda receives in prod.
12
+ * - every inbound text frame invokes `src/ws/default.ts` with a
13
+ * `$default` event whose `body` is the raw frame payload.
14
+ * - on socket close we invoke `src/ws/disconnect.ts`.
15
+ *
16
+ * # Why a process-local hub
17
+ *
18
+ * The user's handlers call `connectionStore.save / authenticate /
19
+ * postToConnection / sendToUser` from `@venturekit/runtime/ws`. In
20
+ * production those calls hit DynamoDB + the API Gateway Management
21
+ * API. Locally we can't (and don't want to) spin up either, so the
22
+ * runtime checks for a process-local hub on
23
+ * `globalThis.__VK_LOCAL_WS_HUB__` and delegates to it. This file is
24
+ * that hub. It owns the in-memory registry AND the live `WebSocket`
25
+ * references, so a `postToConnection(connectionId, data)` call
26
+ * resolves to a direct `ws.send(data)` with no network hop.
27
+ *
28
+ * # Identity
29
+ *
30
+ * `connectionId` is `crypto.randomUUID()` stripped of dashes (32 hex
31
+ * chars) — visually consistent with API Gateway's connection ids.
32
+ *
33
+ * # Hot reload
34
+ *
35
+ * `setHandlerFiles` is called whenever the dev server's file watcher
36
+ * re-discovers `src/ws/*`. The hub also exposes `clearHandlerCache`
37
+ * so the dev server can drop loaded modules whenever any source
38
+ * changes (consistent with how queue + cron handlers are reloaded).
39
+ *
40
+ * # What this does NOT emulate
41
+ *
42
+ * - JWT verification — the user's `$default` already verifies
43
+ * against `cognito-local`, which works locally without changes.
44
+ * - Multi-process broadcast — every dev server has its own
45
+ * registry. Two parallel `vk dev` instances do not see each
46
+ * other's connections. Not a real-world local concern.
47
+ * - DynamoDB TTL — connections are removed on socket close. We
48
+ * don't need a 30s grace timer because nothing persists.
49
+ */
50
+ import * as crypto from 'crypto';
51
+ import * as fs from 'fs';
52
+ import * as path from 'path';
53
+ import chalk from 'chalk';
54
+ import { WebSocketServer, WebSocket } from 'ws';
55
+ const DEFAULT_TTL_SECONDS = 7200; // 2 hours — symmetric with runtime/ws.ts
56
+ const AUTH_GRACE_PERIOD_SECONDS = 30; // unauthenticated grace window
57
+ /**
58
+ * Strip dashes from `crypto.randomUUID()` for visual parity with API
59
+ * Gateway connection ids (32 hex chars, no dashes). Doesn't change
60
+ * uniqueness — just cosmetics in dev logs.
61
+ */
62
+ function newConnectionId() {
63
+ return crypto.randomUUID().replace(/-/g, '');
64
+ }
65
+ /**
66
+ * Discover the three reserved WebSocket route handler files in the
67
+ * project's `src/ws/` directory. Mirrors
68
+ * `discoverWsRoutes` in `@venturekit/infra` so the dev server picks
69
+ * up exactly the same files that the deploy synth wires to Lambda.
70
+ *
71
+ * Non-recursive on purpose — the API Gateway WebSocket convention
72
+ * has only three reserved keys; subdirectories would imply nested
73
+ * routing API GW WS doesn't have. Files like `helpers.ts`,
74
+ * `auth.ts`, `_middleware.ts` are silently skipped.
75
+ *
76
+ * Returns an empty `{}` when `wsDir` doesn't exist.
77
+ */
78
+ export function discoverWsHandlerFiles(wsDir) {
79
+ const result = {};
80
+ if (!fs.existsSync(wsDir))
81
+ return result;
82
+ for (const entry of fs.readdirSync(wsDir, { withFileTypes: true })) {
83
+ if (!entry.isFile())
84
+ continue;
85
+ if (!/\.(ts|js)$/.test(entry.name))
86
+ continue;
87
+ if (entry.name.endsWith('.d.ts'))
88
+ continue;
89
+ const baseName = entry.name.replace(/\.(ts|js)$/, '').toLowerCase();
90
+ if (baseName.endsWith('.test') || baseName.endsWith('.spec'))
91
+ continue;
92
+ const full = path.join(wsDir, entry.name);
93
+ if (baseName === 'connect')
94
+ result.connect = full;
95
+ else if (baseName === 'disconnect')
96
+ result.disconnect = full;
97
+ else if (baseName === 'default')
98
+ result.default = full;
99
+ }
100
+ return result;
101
+ }
102
+ /**
103
+ * Create the local WS hub. The returned object is also installed on
104
+ * `globalThis.__VK_LOCAL_WS_HUB__` so `@venturekit/runtime/ws`'s
105
+ * `connectionStore` delegates to it from inside user handlers.
106
+ *
107
+ * Calling this twice in the same process replaces the previous hub
108
+ * — useful in tests, harmless in dev (the dev server only creates
109
+ * one).
110
+ */
111
+ export function createLocalWsHub(options) {
112
+ const { projectName, stage, port, wsPath = '/ws', handlerFiles: initialFiles = {}, } = options;
113
+ /**
114
+ * Live registry: connectionId → { ws, record }. The same map is
115
+ * what `getByUser`, `getByTenant`, `postToConnection`, etc. read.
116
+ * Map ordering is insertion order, which keeps `getAll` stable
117
+ * across calls — useful in tests.
118
+ */
119
+ const registry = new Map();
120
+ let handlerFiles = { ...initialFiles };
121
+ let handlerLoader = null;
122
+ const handlerCache = new Map();
123
+ let wss = null;
124
+ let stopped = false;
125
+ /**
126
+ * In-flight `$disconnect` dispatch promises. The close listener
127
+ * adds to this set on entry and removes on settle. `stop()` awaits
128
+ * the set so leaked async work cannot bleed into the next test
129
+ * (or, in dev, into a subsequent hub instance after a watch-mode
130
+ * restart).
131
+ */
132
+ const pendingDisconnects = new Set();
133
+ /**
134
+ * The synthetic `domainName` we put on every event's
135
+ * `requestContext`. User code (e.g. `default.ts` in the
136
+ * mycohort-api) re-uses this when calling
137
+ * `connectionStore.postToConnection(domainName, stage, ...)` to
138
+ * reply over the same channel — locally that hits this hub's
139
+ * `postToConnection`, which ignores `domainName` and reads from
140
+ * the registry. Keeping the value realistic-looking helps when
141
+ * developers log it.
142
+ */
143
+ const localDomain = `localhost:${port}`;
144
+ /**
145
+ * Lazy-load + cache a handler module. Returns null when no file
146
+ * is registered for the route OR when the loader hasn't been set
147
+ * yet (we must not fail loudly here — dev startup shouldn't
148
+ * break for projects without ws handlers).
149
+ */
150
+ async function getHandler(routeKey) {
151
+ const file = routeKeyToFile(routeKey);
152
+ if (!file)
153
+ return null;
154
+ if (!handlerLoader)
155
+ return null;
156
+ const cached = handlerCache.get(file);
157
+ if (cached)
158
+ return cached;
159
+ const fn = await handlerLoader(file);
160
+ if (fn)
161
+ handlerCache.set(file, fn);
162
+ return fn;
163
+ }
164
+ function routeKeyToFile(routeKey) {
165
+ if (routeKey === '$connect')
166
+ return handlerFiles.connect;
167
+ if (routeKey === '$disconnect')
168
+ return handlerFiles.disconnect;
169
+ return handlerFiles.default;
170
+ }
171
+ /**
172
+ * Build a Lambda context object similar to what API Gateway WS
173
+ * Lambdas see. We don't bother filling fields nobody reads —
174
+ * `getRemainingTimeInMillis` returns 30s flat (matches dev
175
+ * server's other invocation paths in `local-server.ts`).
176
+ */
177
+ function buildContext(routeKey, requestId) {
178
+ const fnSlug = `ws-${routeKey.replace(/^\$/, '')}`;
179
+ return {
180
+ callbackWaitsForEmptyEventLoop: true,
181
+ functionName: `${projectName}-${stage}-${fnSlug}`,
182
+ functionVersion: '$LATEST',
183
+ invokedFunctionArn: `arn:aws:lambda:local:000000000000:function:${projectName}-${stage}-${fnSlug}`,
184
+ memoryLimitInMB: '256',
185
+ awsRequestId: requestId,
186
+ logGroupName: `/aws/lambda/${projectName}-${stage}-${fnSlug}`,
187
+ logStreamName: `local/${requestId}`,
188
+ getRemainingTimeInMillis: () => 30000,
189
+ done: () => { },
190
+ fail: () => { },
191
+ succeed: () => { },
192
+ };
193
+ }
194
+ /**
195
+ * Build a synthetic API Gateway WebSocket event. The shape is the
196
+ * subset our user handlers actually read — `connectionId`,
197
+ * `eventType`, `domainName`, `stage`, optionally `body`. Adding
198
+ * fields here is non-breaking; removing them is.
199
+ */
200
+ function buildEvent(routeKey, connectionId, body, headers) {
201
+ const eventType = routeKey === '$connect' ? 'CONNECT' :
202
+ routeKey === '$disconnect' ? 'DISCONNECT' : 'MESSAGE';
203
+ const requestId = crypto.randomUUID();
204
+ return {
205
+ requestContext: {
206
+ routeKey,
207
+ eventType,
208
+ connectionId,
209
+ connectedAt: Date.now(),
210
+ domainName: localDomain,
211
+ apiId: 'local',
212
+ stage,
213
+ requestId,
214
+ identity: {
215
+ sourceIp: '127.0.0.1',
216
+ userAgent: 'local-dev',
217
+ },
218
+ },
219
+ isBase64Encoded: false,
220
+ ...(body !== undefined ? { body } : {}),
221
+ ...(headers !== undefined ? { headers } : {}),
222
+ };
223
+ }
224
+ /**
225
+ * Run a handler with diagnostic logging consistent with the rest
226
+ * of the dev server's invocation paths (queue / cron / fn).
227
+ * Returns the handler's return value, or `null` when there's no
228
+ * handler registered for the route. Errors are swallowed +
229
+ * logged because WS handlers don't have a meaningful response
230
+ * channel back to the client beyond the connection itself.
231
+ */
232
+ async function dispatch(routeKey, event) {
233
+ const handler = await getHandler(routeKey);
234
+ if (!handler)
235
+ return null;
236
+ const start = Date.now();
237
+ const requestId = event.requestContext.requestId;
238
+ const context = buildContext(routeKey, requestId);
239
+ try {
240
+ const result = await handler(event, context);
241
+ const duration = Date.now() - start;
242
+ console.log(chalk.gray(' WS ') +
243
+ chalk.magenta(routeKey) +
244
+ chalk.gray(' → ') +
245
+ chalk.green('OK') +
246
+ chalk.gray(` (${duration}ms)`));
247
+ return result;
248
+ }
249
+ catch (err) {
250
+ const duration = Date.now() - start;
251
+ console.error(chalk.gray(' WS ') +
252
+ chalk.magenta(routeKey) +
253
+ chalk.gray(' → ') +
254
+ chalk.red('ERROR') +
255
+ chalk.gray(` (${duration}ms)`));
256
+ console.error(chalk.red(` ${err instanceof Error ? err.message : err}`));
257
+ return null;
258
+ }
259
+ }
260
+ /**
261
+ * Best-effort encode-and-send. Stale sockets get cleaned up so
262
+ * `getByUser` doesn't keep returning them forever. Returns true
263
+ * iff the bytes hit the wire (or at least went into the OS
264
+ * buffer); false on cleanup.
265
+ */
266
+ function sendOne(connectionId, data) {
267
+ const entry = registry.get(connectionId);
268
+ if (!entry)
269
+ return false;
270
+ if (entry.ws.readyState === WebSocket.OPEN) {
271
+ try {
272
+ const payload = typeof data === 'string' ? data : JSON.stringify(data);
273
+ entry.ws.send(payload);
274
+ return true;
275
+ }
276
+ catch {
277
+ // Treat send failure same as a stale connection — drop it
278
+ // so future sends don't keep tripping over the same socket.
279
+ registry.delete(connectionId);
280
+ return false;
281
+ }
282
+ }
283
+ // Not OPEN. CLOSING / CLOSED entries are stale — drop them so
284
+ // future `getByUser` / `sendToUser` calls don't keep returning
285
+ // them. CONNECTING placeholders, however, belong to the
286
+ // pre-upgrade phase (the `upgrade` handler set a placeholder
287
+ // ws before dispatching `$connect`); the live ws will replace
288
+ // it as soon as `handleUpgrade` resolves. Deleting it here
289
+ // would orphan the upgrade and break the connection lifecycle.
290
+ if (entry.ws.readyState === WebSocket.CLOSING ||
291
+ entry.ws.readyState === WebSocket.CLOSED) {
292
+ registry.delete(connectionId);
293
+ }
294
+ return false;
295
+ }
296
+ /**
297
+ * Wire the WebSocketServer to the caller's HTTP server. We use
298
+ * `noServer: true` + a manual `upgrade` listener so we can
299
+ * coexist with the dev server's HTTP handler (it owns the path
300
+ * `/_dev/*` and every route path; we own `/ws`). Other upgrade
301
+ * targets get an explicit 400.
302
+ */
303
+ function attachToHttpServer(server) {
304
+ if (wss)
305
+ return; // idempotent — ignore re-attach
306
+ wss = new WebSocketServer({ noServer: true });
307
+ // Single async `upgrade` listener for the whole hub. The flow
308
+ // mirrors API Gateway's WebSocket → Lambda contract:
309
+ //
310
+ // 1. Path-gate — anything other than `wsPath` gets HTTP 400.
311
+ // 2. Run `$connect` BEFORE accepting the upgrade. This is the
312
+ // key fix for the race that used to drop close events: if
313
+ // we accept the upgrade first and only THEN attach
314
+ // `ws.on('close', …)` after `await dispatch('$connect')`,
315
+ // a client that immediately calls `ws.close()` can land
316
+ // between the handshake and the listener attach.
317
+ // `EventEmitter.emit` is synchronous, so a close emitted
318
+ // before the listener is attached is silently dropped.
319
+ // 3. If `$connect` returns non-2xx, write the corresponding
320
+ // HTTP error response and destroy the socket — the client
321
+ // sees `error` (matches API Gateway, which never opens the
322
+ // WS for rejected connects).
323
+ // 4. Only after a successful `$connect` do we call
324
+ // `handleUpgrade` and synchronously attach `message`,
325
+ // `close`, `error` listeners inside the upgrade callback.
326
+ // With that ordering, no further async gap exists between
327
+ // the WS becoming OPEN and our listeners being live.
328
+ server.on('upgrade', async (req, socket, head) => {
329
+ const reqUrl = req.url ?? '/';
330
+ const pathOnly = reqUrl.split('?')[0];
331
+ if (pathOnly !== wsPath) {
332
+ socket.write('HTTP/1.1 400 Bad Request\r\n' +
333
+ 'Connection: close\r\n' +
334
+ '\r\n');
335
+ socket.destroy();
336
+ return;
337
+ }
338
+ const connectionId = newConnectionId();
339
+ const now = Date.now();
340
+ // Pre-register a record with a placeholder ws. User code in
341
+ // `$connect` (e.g. `connectionStore.save(connectionId)`) sees
342
+ // this slot via the hub, updates the record, and the live ws
343
+ // is swapped in after `handleUpgrade` resolves below. The
344
+ // placeholder's `readyState: CONNECTING` ensures `sendOne`
345
+ // resolves to false during $connect (no live socket yet).
346
+ registry.set(connectionId, {
347
+ ws: { readyState: WebSocket.CONNECTING },
348
+ record: {
349
+ connectionId,
350
+ authenticated: false,
351
+ connectedAt: now,
352
+ ttl: Math.floor(now / 1000) + AUTH_GRACE_PERIOD_SECONDS,
353
+ },
354
+ });
355
+ console.log(chalk.gray(' WS ') +
356
+ chalk.cyan('connect') +
357
+ chalk.gray(' → ') +
358
+ chalk.gray(`id=${connectionId.slice(0, 8)}…`));
359
+ const connectEvent = buildEvent('$connect', connectionId, undefined, req.headers);
360
+ let connectResult;
361
+ try {
362
+ connectResult = await dispatch('$connect', connectEvent);
363
+ }
364
+ catch {
365
+ registry.delete(connectionId);
366
+ socket.write('HTTP/1.1 500 Internal Server Error\r\n' +
367
+ 'Connection: close\r\n' +
368
+ '\r\n');
369
+ socket.destroy();
370
+ return;
371
+ }
372
+ // Reject the upgrade when `$connect` returns a non-2xx
373
+ // statusCode. We emit a best-effort HTTP status that mirrors
374
+ // the Lambda's return — the client's `'open'` never fires,
375
+ // and the upgrade socket is destroyed.
376
+ if (connectResult &&
377
+ typeof connectResult === 'object' &&
378
+ typeof connectResult.statusCode === 'number' &&
379
+ (connectResult.statusCode < 200 ||
380
+ connectResult.statusCode >= 300)) {
381
+ const code = connectResult.statusCode;
382
+ const text = code === 401 ? 'Unauthorized' : code === 403 ? 'Forbidden' : 'Connection Refused';
383
+ registry.delete(connectionId);
384
+ socket.write(`HTTP/1.1 ${code} ${text}\r\nConnection: close\r\n\r\n`);
385
+ socket.destroy();
386
+ return;
387
+ }
388
+ // Accepted — complete the WebSocket upgrade. Listeners go on
389
+ // synchronously inside this callback so no events are lost.
390
+ wss.handleUpgrade(req, socket, head, (ws) => {
391
+ // Patch the live WS into the registry slot $connect already
392
+ // populated. From this point onward, `postToConnection` /
393
+ // `sendToUser` etc. resolve `entry.ws` to a real socket.
394
+ const entry = registry.get(connectionId);
395
+ if (entry)
396
+ entry.ws = ws;
397
+ ws.on('message', async (raw) => {
398
+ const body = typeof raw === 'string'
399
+ ? raw
400
+ : Buffer.isBuffer(raw)
401
+ ? raw.toString('utf-8')
402
+ : Buffer.from(raw).toString('utf-8');
403
+ const event = buildEvent('$default', connectionId, body);
404
+ await dispatch('$default', event);
405
+ });
406
+ ws.on('close', () => {
407
+ // Always run user's $disconnect (best-effort) BEFORE we
408
+ // delete from the registry, so any final
409
+ // `connectionStore.remove(connectionId)` call inside the
410
+ // handler still finds the row to clean up.
411
+ //
412
+ // The dispatch is wrapped so its promise can be tracked by
413
+ // `stop()`. Without that tracking a client-side `ws.close()`
414
+ // that fires after the test body returns leaks a pending
415
+ // dispatch into the next test's lifecycle — and because
416
+ // user handlers commonly close over describe-scoped state
417
+ // (e.g. test capture arrays), the leaked dispatch ends up
418
+ // mutating the wrong test's state.
419
+ const p = (async () => {
420
+ const event = buildEvent('$disconnect', connectionId);
421
+ await dispatch('$disconnect', event);
422
+ // Defensive cleanup — if the handler didn't call
423
+ // `remove` (or threw), drop the row anyway.
424
+ registry.delete(connectionId);
425
+ console.log(chalk.gray(' WS ') +
426
+ chalk.cyan('disconnect') +
427
+ chalk.gray(' → ') +
428
+ chalk.gray(`id=${connectionId.slice(0, 8)}…`));
429
+ })();
430
+ pendingDisconnects.add(p);
431
+ void p.finally(() => pendingDisconnects.delete(p));
432
+ });
433
+ ws.on('error', (err) => {
434
+ console.error(chalk.gray(' WS ') +
435
+ chalk.cyan('error') +
436
+ chalk.gray(` id=${connectionId.slice(0, 8)}… `) +
437
+ chalk.red(err.message));
438
+ });
439
+ // Emit 'connection' for any external listeners (tests,
440
+ // future hooks) that wait on it. Done last so the listeners
441
+ // above are guaranteed in place by the time anyone reacts.
442
+ wss.emit('connection', ws, req);
443
+ });
444
+ });
445
+ }
446
+ function setHandlerFiles(files) {
447
+ handlerFiles = { ...files };
448
+ // Force re-load on next dispatch — file paths may have changed.
449
+ handlerCache.clear();
450
+ }
451
+ function setHandlerLoader(loader) {
452
+ handlerLoader = loader;
453
+ }
454
+ function clearHandlerCache() {
455
+ handlerCache.clear();
456
+ }
457
+ function connectionCount() {
458
+ return registry.size;
459
+ }
460
+ async function stop() {
461
+ if (stopped) {
462
+ // Still drain anything in flight from a prior call so two
463
+ // back-to-back `await stop()` calls behave the same as one.
464
+ if (pendingDisconnects.size > 0) {
465
+ await Promise.allSettled([...pendingDisconnects]);
466
+ }
467
+ return;
468
+ }
469
+ stopped = true;
470
+ // Snapshot live sockets BEFORE clearing the registry so we can
471
+ // wait for each one's `'close'` event to fire below. Without
472
+ // this snapshot, pre-upgrade placeholder entries (with a fake
473
+ // `{ readyState: CONNECTING }` ws) are skipped — only real
474
+ // sockets that already passed `handleUpgrade` carry the close
475
+ // listener that schedules a `$disconnect` dispatch.
476
+ const liveSockets = [];
477
+ for (const { ws } of registry.values()) {
478
+ if (ws.readyState === WebSocket.OPEN ||
479
+ ws.readyState === WebSocket.CLOSING) {
480
+ liveSockets.push(ws);
481
+ }
482
+ }
483
+ for (const ws of liveSockets) {
484
+ try {
485
+ ws.close(1001, 'server shutdown');
486
+ }
487
+ catch { /* ignore */ }
488
+ }
489
+ registry.clear();
490
+ if (wss) {
491
+ try {
492
+ wss.close();
493
+ }
494
+ catch { /* ignore */ }
495
+ wss = null;
496
+ }
497
+ // Uninstall hub if it still points at us. This MUST run before
498
+ // the await below so the synchronous portion of `stop()` matches
499
+ // its old contract — callers that don't await us still observe
500
+ // the hub uninstalled the moment `stop()` returns.
501
+ const g = globalThis;
502
+ if (g.__VK_LOCAL_WS_HUB__ === hubAsConnectionStore) {
503
+ g.__VK_LOCAL_WS_HUB__ = undefined;
504
+ }
505
+ // Wait for each live socket's `'close'` event to fire. The close
506
+ // listener attached in `handleUpgrade` runs synchronously when
507
+ // `'close'` emits and adds its dispatch promise to
508
+ // `pendingDisconnects` BEFORE its first await — so by the time
509
+ // these per-socket promises resolve, every leaked dispatch is
510
+ // tracked and the next `Promise.allSettled` below will drain it.
511
+ //
512
+ // Without this barrier, a client-initiated `ws.close()` whose
513
+ // server-side `'close'` event hasn't fired yet by the time
514
+ // `stop()` runs would leak a dispatch past `stop()` and
515
+ // contaminate the next hub's lifecycle.
516
+ if (liveSockets.length > 0) {
517
+ await Promise.all(liveSockets.map((ws) => new Promise((resolve) => {
518
+ if (ws.readyState === WebSocket.CLOSED) {
519
+ resolve();
520
+ }
521
+ else {
522
+ ws.once('close', () => resolve());
523
+ }
524
+ })));
525
+ }
526
+ // Drain in-flight `$disconnect` dispatches so they cannot leak
527
+ // past the hub's lifetime. The synchronous teardown above means
528
+ // any user handler that re-enters the hub (e.g. via
529
+ // `getInstalledHub`) sees an uninstalled global and no-ops.
530
+ if (pendingDisconnects.size > 0) {
531
+ await Promise.allSettled([...pendingDisconnects]);
532
+ }
533
+ }
534
+ /**
535
+ * The hub object exposed on `globalThis.__VK_LOCAL_WS_HUB__`.
536
+ * Method names + signatures are byte-identical to
537
+ * `connectionStore` in `@venturekit/runtime/ws`'s `ws.ts`.
538
+ *
539
+ * Kept separate from the public `LocalWsHub` returned to the
540
+ * dev server because the dev server should never need to call
541
+ * these directly — they're for the runtime-side delegation only.
542
+ */
543
+ const hubAsConnectionStore = {
544
+ async save(connectionId) {
545
+ const now = Date.now();
546
+ const existing = registry.get(connectionId);
547
+ if (existing) {
548
+ // Connection already opened the WS — preserve `ws`
549
+ // reference, just refresh the record.
550
+ existing.record = {
551
+ ...existing.record,
552
+ authenticated: false,
553
+ connectedAt: now,
554
+ ttl: Math.floor(now / 1000) + AUTH_GRACE_PERIOD_SECONDS,
555
+ };
556
+ return;
557
+ }
558
+ // Defensive: handler called save() for a connectionId we
559
+ // never saw open. Stash a record-only entry so subsequent
560
+ // `authenticate` etc. don't blow up. The entry has no
561
+ // `ws` so sends will resolve to `false` (stale).
562
+ registry.set(connectionId, {
563
+ // No live WebSocket — see `sendOne`'s readyState check.
564
+ ws: { readyState: WebSocket.CLOSED },
565
+ record: {
566
+ connectionId,
567
+ authenticated: false,
568
+ connectedAt: now,
569
+ ttl: Math.floor(now / 1000) + AUTH_GRACE_PERIOD_SECONDS,
570
+ },
571
+ });
572
+ },
573
+ async authenticate(connectionId, metadata) {
574
+ const entry = registry.get(connectionId);
575
+ if (!entry)
576
+ return; // unknown connection — silent no-op (matches DDB UpdateItem on missing key minus the explicit existence check).
577
+ const { userId, tenantId, email, ...extra } = metadata;
578
+ const now = Date.now();
579
+ entry.record = {
580
+ ...entry.record,
581
+ ...extra,
582
+ authenticated: true,
583
+ userId,
584
+ ...(tenantId !== undefined ? { tenantId } : {}),
585
+ ...(email !== undefined ? { email } : {}),
586
+ authenticatedAt: now,
587
+ ttl: Math.floor(now / 1000) + DEFAULT_TTL_SECONDS,
588
+ };
589
+ },
590
+ async remove(connectionId) {
591
+ registry.delete(connectionId);
592
+ },
593
+ async get(connectionId) {
594
+ return registry.get(connectionId)?.record ?? null;
595
+ },
596
+ async getAll() {
597
+ const out = [];
598
+ for (const { record } of registry.values()) {
599
+ if (record.authenticated)
600
+ out.push(record);
601
+ }
602
+ return out;
603
+ },
604
+ async getByUser(userId) {
605
+ const out = [];
606
+ for (const { record } of registry.values()) {
607
+ if (record.userId === userId)
608
+ out.push(record);
609
+ }
610
+ return out;
611
+ },
612
+ async getByTenant(tenantId) {
613
+ const out = [];
614
+ for (const { record } of registry.values()) {
615
+ if (record.tenantId === tenantId)
616
+ out.push(record);
617
+ }
618
+ return out;
619
+ },
620
+ async postToConnection(_domainName, _stage, connectionId, data) {
621
+ return sendOne(connectionId, data);
622
+ },
623
+ async sendToUser(_domainName, _stage, userId, data) {
624
+ let delivered = 0;
625
+ for (const { record } of registry.values()) {
626
+ if (record.authenticated && record.userId === userId) {
627
+ if (sendOne(record.connectionId, data))
628
+ delivered++;
629
+ }
630
+ }
631
+ return delivered;
632
+ },
633
+ async sendToTenant(_domainName, _stage, tenantId, data) {
634
+ let delivered = 0;
635
+ for (const { record } of registry.values()) {
636
+ if (record.authenticated && record.tenantId === tenantId) {
637
+ if (sendOne(record.connectionId, data))
638
+ delivered++;
639
+ }
640
+ }
641
+ return delivered;
642
+ },
643
+ async broadcast(_domainName, _stage, data) {
644
+ let delivered = 0;
645
+ for (const { record } of registry.values()) {
646
+ if (record.authenticated) {
647
+ if (sendOne(record.connectionId, data))
648
+ delivered++;
649
+ }
650
+ }
651
+ return delivered;
652
+ },
653
+ };
654
+ // Install the hub. The runtime's `connectionStore` looks here on
655
+ // every method call; setting it here means every user handler
656
+ // loaded after this point sees the hub on first invocation.
657
+ globalThis.__VK_LOCAL_WS_HUB__ = hubAsConnectionStore;
658
+ return {
659
+ attachToHttpServer,
660
+ setHandlerFiles,
661
+ setHandlerLoader,
662
+ clearHandlerCache,
663
+ connectionCount,
664
+ stop,
665
+ };
666
+ }
667
+ //# sourceMappingURL=local-ws.js.map