cdk-local 0.83.0 → 0.84.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.
@@ -1,1993 +0,0 @@
1
- import { c as getEmbedConfig, s as getLogger, u as setEmbedConfig } from "./docker-cmd-Dqx2YENO.js";
2
- import { Hn as listTargets, Ln as resolveApp, cr as withErrorHandling, fr as appOptions, gr as regionOption, hr as parseContextOptions, lr as applyRoleArnIfSet, mr as contextOptions, pr as commonOptions, zn as Synthesizer } from "./local-list-DBlBRfA-.js";
3
- import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
- import { tmpdir } from "node:os";
5
- import { join } from "node:path";
6
- import { Command, Option } from "commander";
7
- import { spawn } from "node:child_process";
8
- import { connect } from "node:net";
9
- import { createServer as createServer$1, request } from "node:http";
10
- import { EventEmitter } from "node:events";
11
-
12
- //#region src/local/studio-events.ts
13
- /**
14
- * In-process event bus that every studio observation flows through. The
15
- * studio HTTP server subscribes and forwards events to the browser over
16
- * SSE; the dispatch / log-streaming layers emit onto it.
17
- *
18
- * A thin typed wrapper over {@link EventEmitter} so producers and the
19
- * server agree on the event shapes without `any`. Re-exported from
20
- * `cdk-local/internal` so a host CLI embedding studio can subscribe.
21
- */
22
- var StudioEventBus = class {
23
- emitter = new EventEmitter();
24
- constructor() {
25
- this.emitter.setMaxListeners(0);
26
- }
27
- emit(event, ...args) {
28
- this.emitter.emit(event, ...args);
29
- }
30
- on(event, listener) {
31
- this.emitter.on(event, listener);
32
- return this;
33
- }
34
- off(event, listener) {
35
- this.emitter.off(event, listener);
36
- return this;
37
- }
38
- /**
39
- * Number of listeners currently subscribed to `event`. Exposed so the
40
- * SSE server's subscribe / unsubscribe symmetry can be asserted (a
41
- * dropped client must not leak a listener).
42
- */
43
- listenerCount(event) {
44
- return this.emitter.listenerCount(event);
45
- }
46
- };
47
-
48
- //#endregion
49
- //#region src/local/studio-store.ts
50
- /**
51
- * Build the studio store and subscribe it to `bus`. The store merges the
52
- * start/end pair of each invocation (keyed by id) and keeps a ring of log
53
- * lines; both windows evict oldest-first past their caps.
54
- */
55
- function createStudioStore(bus, options = {}) {
56
- const maxInvocations = options.maxInvocations ?? 200;
57
- const maxLogs = options.maxLogs ?? 5e3;
58
- const bindGraceMs = options.bindGraceMs ?? 250;
59
- const invocations = /* @__PURE__ */ new Map();
60
- const logs = [];
61
- const onInvocation = (ev) => {
62
- invocations.set(ev.id, {
63
- ...invocations.get(ev.id),
64
- ...ev
65
- });
66
- if (invocations.size > maxInvocations) {
67
- const oldest = invocations.keys().next().value;
68
- if (oldest !== void 0) invocations.delete(oldest);
69
- }
70
- };
71
- const onLog = (ev) => {
72
- logs.push(ev);
73
- if (logs.length > maxLogs) logs.shift();
74
- };
75
- bus.on("invocation", onInvocation);
76
- bus.on("log", onLog);
77
- let disposed = false;
78
- return {
79
- history: () => ({
80
- invocations: [...invocations.values()],
81
- logs: [...logs]
82
- }),
83
- searchLogs: (query, opts = {}) => {
84
- const needle = query.toLowerCase();
85
- const limit = opts.limit ?? 200;
86
- const matches = [];
87
- for (let i = logs.length - 1; i >= 0 && matches.length < limit; i -= 1) {
88
- const log = logs[i];
89
- if (!log) continue;
90
- if (opts.target !== void 0 && log.target !== opts.target) continue;
91
- if (needle === "" || log.line.toLowerCase().includes(needle)) matches.push(log);
92
- }
93
- return matches;
94
- },
95
- logsForInvocation: (id) => {
96
- const inv = invocations.get(id);
97
- if (!inv) return [];
98
- if (inv.kind === "lambda") return logs.filter((l) => l.containerId === id);
99
- const from = inv.ts;
100
- const to = inv.ts + (inv.durationMs ?? 0) + bindGraceMs;
101
- return logs.filter((l) => l.target === inv.target && l.ts >= from && l.ts <= to);
102
- },
103
- invocation: (id) => invocations.get(id),
104
- dispose: () => {
105
- if (disposed) return;
106
- disposed = true;
107
- bus.off("invocation", onInvocation);
108
- bus.off("log", onLog);
109
- }
110
- };
111
- }
112
-
113
- //#endregion
114
- //#region src/local/studio-ui.ts
115
- /**
116
- * The studio web UI, embedded as a string so it ships inside the
117
- * `cdk-local` npm package (decision D9) with no asset-copy build step —
118
- * `tsdown` bundles this module like any other source file. Served by
119
- * the studio HTTP server (`startStudioServer`) at `GET /`.
120
- *
121
- * 3-pane shell (decision D6), framework-free vanilla JS (decision D7):
122
- * - left = target list (from `GET /api/targets`); each Lambda has an
123
- * [Invoke] button, each API a [Start] / [Stop] serve control with a
124
- * `running ● :port` indicator (slice C1), plus a selected-highlight.
125
- * - center = the WORKSPACE for the selected target: for a Lambda, an
126
- * event composer (textarea + Invoke button) with the latest run's
127
- * Request / Response / Logs shown below; for an API, a Start/Stop
128
- * control with the served endpoints + streaming logs.
129
- * - right = the timeline (history) of every invocation AND every
130
- * captured serve request (slice C2); clicking a Lambda row reloads
131
- * it into the composer, clicking a captured request row opens a
132
- * read-only Request / Response detail.
133
- *
134
- * The center workspace is deliberately adjacent to the left target list
135
- * (short eye-travel: pick a target -> compose right next to it), and is
136
- * the primary surface — the timeline is secondary history.
137
- */
138
- const STUDIO_CSS = `
139
- * { box-sizing: border-box; }
140
- body {
141
- margin: 0; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
142
- color: #e6e6e6; background: #1a1a1a; height: 100vh; overflow: hidden;
143
- }
144
- header {
145
- padding: 8px 14px; background: #111; border-bottom: 1px solid #333;
146
- display: flex; align-items: center; gap: 10px;
147
- }
148
- header .brand { font-weight: 700; color: #fff; }
149
- header .meta { color: #888; font-size: 12px; }
150
- main {
151
- display: grid; grid-template-columns: 280px 5px 1fr 5px 320px;
152
- height: calc(100vh - 38px);
153
- }
154
- .pane { overflow: auto; }
155
- .splitter { background: #2a2a2a; cursor: col-resize; }
156
- .splitter:hover, .splitter.dragging { background: #4ec97a; }
157
- .pane h2 {
158
- margin: 0; padding: 8px 12px; font-size: 11px; text-transform: uppercase;
159
- letter-spacing: 0.5px; color: #888; background: #151515;
160
- position: sticky; top: 0; border-bottom: 1px solid #2a2a2a; z-index: 1;
161
- }
162
- .group-title { padding: 8px 12px 2px; color: #6aa9ff; font-size: 11px; }
163
- .target {
164
- padding: 6px 12px; border-bottom: 1px solid #222; display: flex;
165
- align-items: center; gap: 8px;
166
- }
167
- .target.runnable { cursor: pointer; }
168
- .target.runnable:hover { background: #202020; }
169
- .target.sel { background: #2a3550; }
170
- .target .name { color: #ddd; flex: 1; overflow: hidden; text-overflow: ellipsis; }
171
- .target .kind { color: #777; font-size: 11px; }
172
- .target .invoke-btn {
173
- padding: 2px 10px; font: 11px ui-monospace, Menlo, monospace; font-weight: 700;
174
- color: #0d1f12; background: #4ec97a; border: 0; border-radius: 3px; cursor: pointer;
175
- }
176
- .target .invoke-btn:hover { background: #6fe097; }
177
- .target.sel .invoke-btn { background: #6fe097; }
178
- .target .stop-btn {
179
- padding: 2px 10px; font: 11px ui-monospace, Menlo, monospace; font-weight: 700;
180
- color: #2a0d0d; background: #e0707a; border: 0; border-radius: 3px; cursor: pointer;
181
- }
182
- .target .stop-btn:hover { background: #ec8a92; }
183
- .target .run-dot { color: #7bd88f; font-size: 11px; white-space: nowrap; }
184
- .target .run-dot.starting { color: #e0b54e; }
185
- .empty { padding: 16px 12px; color: #666; }
186
- .row {
187
- padding: 5px 12px; border-bottom: 1px solid #222; cursor: pointer;
188
- display: flex; gap: 8px; white-space: nowrap;
189
- }
190
- .row:hover { background: #222; }
191
- .row.sel { background: #2a3550; }
192
- .row .ts { color: #777; }
193
- .row .label { color: #ddd; flex: 1; overflow: hidden; text-overflow: ellipsis; }
194
- .row .status { color: #7bd88f; }
195
- .row .status.err { color: #e0707a; }
196
- #workspace { padding: 0 0 24px; }
197
- .composer { padding: 10px 12px; border-bottom: 1px solid #2a2a2a; }
198
- .composer .target-name { color: #fff; font-weight: 700; margin-bottom: 6px; }
199
- .composer textarea {
200
- width: 100%; min-height: 130px; resize: vertical; background: #111; color: #ddd;
201
- border: 1px solid #333; border-radius: 3px; padding: 6px;
202
- font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
203
- }
204
- .composer button {
205
- margin-top: 8px; padding: 6px 18px; background: #2a7d46; color: #fff;
206
- border: 0; border-radius: 3px; cursor: pointer; font: inherit; font-weight: 700;
207
- }
208
- .composer button:hover { background: #339152; }
209
- .composer button:disabled { background: #333; color: #888; cursor: default; }
210
- .composer .err { color: #e0707a; margin-top: 6px; min-height: 18px; }
211
- .section { padding: 8px 12px; border-bottom: 1px solid #222; }
212
- .section h3 { margin: 0 0 6px; font-size: 11px; color: #888; text-transform: uppercase; }
213
- .section h3 .ok { color: #7bd88f; }
214
- .section h3 .bad { color: #e0707a; }
215
- .section pre { margin: 0; white-space: pre-wrap; word-break: break-word; color: #cfcfcf; }
216
- .endpoint { display: block; color: #6aa9ff; text-decoration: none; padding: 2px 0; }
217
- .endpoint:hover { text-decoration: underline; }
218
- .searchbar { padding: 6px 10px; border-bottom: 1px solid #2a2a2a; background: #151515;
219
- position: sticky; top: 28px; z-index: 1; }
220
- .searchbar input {
221
- width: 100%; background: #111; color: #ddd; border: 1px solid #333; border-radius: 3px;
222
- padding: 5px 8px; font: 12px ui-monospace, Menlo, monospace;
223
- }
224
- .searchbar input:focus { outline: none; border-color: #4ec97a; }
225
- #log-results { display: none; }
226
- #log-results.active { display: block; }
227
- .log-hit { padding: 4px 12px; border-bottom: 1px solid #222; white-space: pre-wrap;
228
- word-break: break-word; }
229
- .log-hit .lt { color: #777; }
230
- .log-hit .lg { color: #6aa9ff; }
231
- .log-hits-meta { padding: 6px 12px; color: #888; font-size: 11px; }
232
- #conn { font-size: 11px; }
233
- #conn.up { color: #7bd88f; }
234
- #conn.down { color: #e0707a; }
235
- `;
236
- const STUDIO_SCRIPT = `
237
- const KIND_LABEL = { lambda: 'Lambda', api: 'API', alb: 'ALB', ecs: 'ECS', agentcore: 'AgentCore' };
238
- const SERVE_KINDS = ['api', 'alb', 'ecs']; // long-running serve targets
239
- const rowsById = new Map(); // invocationId -> timeline row element
240
- const invById = new Map(); // invocationId -> latest invocation event
241
- const logsById = new Map(); // invocationId / serve targetId -> [log lines]
242
- const targetEls = new Map(); // targetId -> left-pane element
243
- const serveMeta = new Map(); // serve targetId -> { dot, btnSlot } row controls
244
- const serveState = new Map(); // serve targetId -> { status, endpoints }
245
- let active = null; // { id, kind, ta, btn, msg, result }
246
- let shownInvId = null; // lambda invocation whose result is in the workspace
247
- let shownServeId = null; // serve target whose workspace is shown
248
- let shownDetailId = null; // captured request whose read-only detail is shown
249
-
250
- function el(tag, cls, text) {
251
- const e = document.createElement(tag);
252
- if (cls) e.className = cls;
253
- if (text != null) e.textContent = text;
254
- return e;
255
- }
256
-
257
- async function loadTargets() {
258
- const pane = document.getElementById('targets');
259
- try {
260
- const res = await fetch('/api/targets');
261
- const data = await res.json();
262
- pane.querySelectorAll('.group-title,.target,.empty').forEach((n) => n.remove());
263
- let total = 0;
264
- for (const group of data.groups) {
265
- if (!group.entries.length) continue;
266
- pane.appendChild(el('div', 'group-title', group.title));
267
- for (const entry of group.entries) {
268
- total += 1;
269
- // Lambda targets are single-shot invokes; api / alb / ecs are
270
- // long-running serves. Other kinds list but are not yet runnable.
271
- // Within ecs, only services are servable (task defs are run-task).
272
- const isServe = SERVE_KINDS.includes(group.kind) && (group.kind !== 'ecs' || entry.servable === true);
273
- const runnable = group.kind === 'lambda' || isServe;
274
- const t = el('div', runnable ? 'target runnable' : 'target');
275
- const name = el('span', 'name', entry.id);
276
- name.title = entry.id; // full path on hover even when truncated
277
- t.appendChild(name);
278
- t.appendChild(el('span', 'kind', '(' + (KIND_LABEL[group.kind] || group.kind) + ')'));
279
- if (group.kind === 'lambda') {
280
- const btn = el('button', 'invoke-btn', 'Invoke');
281
- btn.onclick = (e) => { e.stopPropagation(); selectTarget(entry.id, 'lambda'); };
282
- t.appendChild(btn);
283
- t.onclick = () => selectTarget(entry.id, 'lambda');
284
- targetEls.set(entry.id, t);
285
- } else if (isServe) {
286
- // A serve target: a running-state dot + a Start/Stop button
287
- // slot, both refreshed by updateServeRow on serve events.
288
- const dot = el('span', 'run-dot');
289
- const btnSlot = el('span', 'btn-slot');
290
- t.appendChild(dot);
291
- t.appendChild(btnSlot);
292
- t.onclick = () => selectTarget(entry.id, group.kind);
293
- targetEls.set(entry.id, t);
294
- serveMeta.set(entry.id, { dot, btnSlot, kind: group.kind });
295
- updateServeRow(entry.id);
296
- }
297
- pane.appendChild(t);
298
- }
299
- }
300
- if (!total) pane.appendChild(el('div', 'empty', 'No runnable targets found.'));
301
- } catch (err) {
302
- pane.appendChild(el('div', 'empty', 'Failed to load targets: ' + err));
303
- }
304
- }
305
-
306
- // Pull any already-running serves (e.g. after a UI reload) so the rows
307
- // and workspace reflect them without waiting for a fresh serve event.
308
- async function loadRunning() {
309
- try {
310
- const res = await fetch('/api/running');
311
- const data = await res.json();
312
- for (const s of (data.running || [])) {
313
- serveState.set(s.targetId, { status: s.status, endpoints: s.endpoints || [] });
314
- updateServeRow(s.targetId);
315
- }
316
- } catch (err) {
317
- /* best-effort; the serve SSE stream still drives live updates */
318
- }
319
- }
320
-
321
- function firstPort(endpoints) {
322
- const u = (endpoints || [])[0];
323
- if (!u) return '';
324
- const m = /:(\\d+)/.exec(u);
325
- return m ? ':' + m[1] : '';
326
- }
327
-
328
- function updateServeRow(id) {
329
- const meta = serveMeta.get(id);
330
- if (!meta) return;
331
- const st = serveState.get(id);
332
- const status = st ? st.status : 'stopped';
333
- const running = status === 'running';
334
- const starting = status === 'starting';
335
- // A serve with a host endpoint shows the dot + :port; a pure-compute
336
- // ecs service has no endpoint, so just the dot + running.
337
- const port = running ? firstPort(st.endpoints) : '';
338
- meta.dot.textContent = running ? (port ? '● ' + port : '● running') : starting ? '○ starting' : '';
339
- meta.dot.className = 'run-dot' + (starting ? ' starting' : '');
340
- meta.btnSlot.innerHTML = '';
341
- const btn = running || starting
342
- ? el('button', 'stop-btn', 'Stop')
343
- : el('button', 'invoke-btn', 'Start');
344
- btn.onclick = (e) => {
345
- e.stopPropagation();
346
- if (running || starting) stopServe(id); else startServe(id);
347
- };
348
- meta.btnSlot.appendChild(btn);
349
- // Refresh the workspace if it is showing this serve.
350
- if (shownServeId === id) renderServeWorkspace(id);
351
- }
352
-
353
- function highlightTarget(id) {
354
- document.querySelectorAll('.target.sel').forEach((n) => n.classList.remove('sel'));
355
- const t = targetEls.get(id);
356
- if (t) t.classList.add('sel');
357
- }
358
-
359
- function selectTarget(id, kind) {
360
- highlightTarget(id);
361
- shownDetailId = null;
362
- if (SERVE_KINDS.includes(kind)) {
363
- shownServeId = id;
364
- shownInvId = null;
365
- active = null;
366
- renderServeWorkspace(id);
367
- } else {
368
- shownServeId = null;
369
- renderComposer(id, kind, '{}');
370
- }
371
- }
372
-
373
- async function startServe(id) {
374
- // The serve kind (api / alb / ecs) drives which headless command the
375
- // server spawns; it is recorded on the row when the target list loads.
376
- const meta = serveMeta.get(id);
377
- const kind = meta ? meta.kind : 'api';
378
- serveState.set(id, { status: 'starting', endpoints: [] });
379
- updateServeRow(id);
380
- try {
381
- const res = await fetch('/api/run', {
382
- method: 'POST',
383
- headers: { 'content-type': 'application/json' },
384
- body: JSON.stringify({ targetId: id, kind }),
385
- });
386
- const data = await res.json();
387
- if (!res.ok) {
388
- // Roll back the optimistic 'starting' on a rejected start.
389
- serveState.set(id, { status: 'error', endpoints: [] });
390
- updateServeRow(id);
391
- if (shownServeId === id) renderServeWorkspace(id, data.error || ('HTTP ' + res.status));
392
- }
393
- // On success the serve SSE 'running' event fills in the endpoints.
394
- } catch (err) {
395
- serveState.set(id, { status: 'error', endpoints: [] });
396
- updateServeRow(id);
397
- if (shownServeId === id) renderServeWorkspace(id, String(err));
398
- }
399
- }
400
-
401
- async function stopServe(id) {
402
- try {
403
- await fetch('/api/stop', {
404
- method: 'POST',
405
- headers: { 'content-type': 'application/json' },
406
- body: JSON.stringify({ targetId: id }),
407
- });
408
- // The serve SSE 'stopped' event clears the running state.
409
- } catch (err) {
410
- /* the stop SSE event (or a later refresh) reconciles state */
411
- }
412
- }
413
-
414
- function renderServeWorkspace(id, errMsg) {
415
- const ws = document.getElementById('workspace');
416
- ws.innerHTML = '';
417
- const st = serveState.get(id) || { status: 'stopped', endpoints: [] };
418
- const running = st.status === 'running';
419
- const starting = st.status === 'starting';
420
-
421
- const head = el('div', 'composer');
422
- head.appendChild(el('div', 'target-name', 'Serve ' + id));
423
- const btn = running || starting
424
- ? el('button', null, 'Stop')
425
- : el('button', null, starting ? 'Starting…' : 'Start');
426
- btn.onclick = () => { if (running || starting) stopServe(id); else startServe(id); };
427
- head.appendChild(btn);
428
- if (errMsg) {
429
- const m = el('div', 'err', errMsg);
430
- head.appendChild(m);
431
- }
432
- ws.appendChild(head);
433
-
434
- const meta = serveMeta.get(id);
435
- const isEcs = meta && meta.kind === 'ecs';
436
- const epSec = el('div', 'section');
437
- epSec.appendChild(el('h3', null, 'Endpoints'));
438
- if (running && st.endpoints.length) {
439
- for (const url of st.endpoints) {
440
- const link = href(url);
441
- epSec.appendChild(link);
442
- }
443
- } else if (running && isEcs) {
444
- // A pure-compute ECS service has no host endpoint — it just runs the
445
- // replicas (reach them container-to-container via Cloud Map).
446
- epSec.appendChild(el('pre', null, '(running — pure compute service, no host endpoint)'));
447
- } else {
448
- epSec.appendChild(el('pre', null, starting ? '(starting…)' : '(not running)'));
449
- }
450
- ws.appendChild(epSec);
451
-
452
- const logs = logsById.get(id) || [];
453
- const logSec = el('div', 'section');
454
- logSec.appendChild(el('h3', null, 'Logs'));
455
- logSec.appendChild(el('pre', null, logs.length ? logs.join('\\n') : '(none)'));
456
- ws.appendChild(logSec);
457
- }
458
-
459
- // Build an <a> that opens an http(s) endpoint in a new tab; ws:// URLs
460
- // are shown as plain text (not navigable in a browser tab).
461
- function href(url) {
462
- if (/^https?:/.test(url)) {
463
- const a = el('a', 'endpoint', url);
464
- a.href = url;
465
- a.target = '_blank';
466
- a.rel = 'noopener';
467
- return a;
468
- }
469
- return el('div', 'endpoint', url);
470
- }
471
-
472
- function renderComposer(id, kind, eventText) {
473
- const ws = document.getElementById('workspace');
474
- ws.innerHTML = '';
475
-
476
- const composer = el('div', 'composer');
477
- composer.appendChild(el('div', 'target-name', 'Invoke ' + id));
478
- const ta = el('textarea');
479
- ta.value = eventText;
480
- ta.spellcheck = false;
481
- composer.appendChild(ta);
482
- composer.appendChild(document.createElement('br'));
483
- const btn = el('button', null, 'Invoke');
484
- const msg = el('div', 'err');
485
- composer.appendChild(btn);
486
- composer.appendChild(msg);
487
-
488
- const result = el('div', 'result');
489
-
490
- ws.appendChild(composer);
491
- ws.appendChild(result);
492
-
493
- active = { id, kind, ta, btn, msg, result };
494
- btn.onclick = () => runInvoke();
495
- shownInvId = null;
496
- shownDetailId = null;
497
- ta.focus();
498
- }
499
-
500
- async function runInvoke() {
501
- if (!active) return;
502
- const { id, kind, ta, btn, msg, result } = active;
503
- let event;
504
- try {
505
- event = ta.value.trim() === '' ? {} : JSON.parse(ta.value);
506
- } catch (err) {
507
- msg.textContent = 'Invalid JSON: ' + err.message;
508
- return;
509
- }
510
- msg.textContent = '';
511
- btn.disabled = true;
512
- btn.textContent = 'Invoking...';
513
- result.innerHTML = '';
514
- try {
515
- const res = await fetch('/api/run', {
516
- method: 'POST',
517
- headers: { 'content-type': 'application/json' },
518
- body: JSON.stringify({ targetId: id, kind, event }),
519
- });
520
- const data = await res.json();
521
- if (data.invocationId) {
522
- shownInvId = data.invocationId;
523
- renderResult(shownInvId);
524
- }
525
- if (!res.ok || data.ok === false) {
526
- msg.textContent = 'Invoke failed: ' + (data.error || ('HTTP ' + res.status));
527
- }
528
- } catch (err) {
529
- msg.textContent = 'Request failed: ' + err;
530
- } finally {
531
- btn.disabled = false;
532
- btn.textContent = 'Invoke';
533
- }
534
- }
535
-
536
- function fmt(body) {
537
- return typeof body === 'string' ? body : JSON.stringify(body, null, 2);
538
- }
539
-
540
- function renderResult(invId) {
541
- if (!active) return;
542
- const result = active.result;
543
- result.innerHTML = '';
544
- const ev = invById.get(invId);
545
- if (!ev) return;
546
-
547
- const reqSec = el('div', 'section');
548
- reqSec.appendChild(el('h3', null, 'Request'));
549
- reqSec.appendChild(el('pre', null, ev.request != null ? fmt(ev.request) : '(none)'));
550
- result.appendChild(reqSec);
551
-
552
- const respSec = el('div', 'section');
553
- const h = el('h3', null, 'Response');
554
- if (ev.status != null) {
555
- const cls = ev.status >= 200 && ev.status < 300 ? 'ok' : 'bad';
556
- const meta = el('span', cls, ' ' + ev.status + (ev.durationMs != null ? ' · ' + ev.durationMs + 'ms' : ''));
557
- h.appendChild(meta);
558
- }
559
- respSec.appendChild(h);
560
- respSec.appendChild(el('pre', null, ev.response != null ? fmt(ev.response) : '(pending…)'));
561
- result.appendChild(respSec);
562
-
563
- const logs = logsById.get(invId) || [];
564
- const logSec = el('div', 'section');
565
- logSec.appendChild(el('h3', null, 'Logs'));
566
- logSec.appendChild(el('pre', null, logs.length ? logs.join('\\n') : '(none)'));
567
- result.appendChild(logSec);
568
- }
569
-
570
- function addInvocation(ev) {
571
- invById.set(ev.id, Object.assign(invById.get(ev.id) || {}, ev));
572
- const timeline = document.getElementById('timeline-rows');
573
- const placeholder = timeline.querySelector('.empty');
574
- if (placeholder) placeholder.remove();
575
-
576
- let row = rowsById.get(ev.id);
577
- if (!row) {
578
- row = el('div', 'row');
579
- row.appendChild(el('span', 'ts'));
580
- row.appendChild(el('span', 'label'));
581
- row.appendChild(el('span', 'status'));
582
- row.onclick = () => loadInvocation(ev.id);
583
- rowsById.set(ev.id, row);
584
- timeline.insertBefore(row, timeline.querySelector('.row')); // newest on top
585
- }
586
- const merged = invById.get(ev.id);
587
- const d = new Date(merged.ts);
588
- row.querySelector('.ts').textContent = d.toLocaleTimeString();
589
- row.querySelector('.label').textContent = (merged.target || '') + ' ' + (merged.label || '');
590
- const statusEl = row.querySelector('.status');
591
- statusEl.textContent =
592
- merged.status != null
593
- ? merged.status + (merged.durationMs != null ? ' ' + merged.durationMs + 'ms' : '')
594
- : '…';
595
- statusEl.className = 'status' + (merged.status != null && (merged.status < 200 || merged.status >= 300) ? ' err' : '');
596
-
597
- // Live-refresh the workspace if it is showing this invocation.
598
- if (shownInvId === ev.id) renderResult(ev.id);
599
- if (shownDetailId === ev.id) renderCapturedDetail(ev.id);
600
- }
601
-
602
- function loadInvocation(id) {
603
- const ev = invById.get(id);
604
- if (!ev) return;
605
- document.querySelectorAll('.row.sel').forEach((n) => n.classList.remove('sel'));
606
- const row = rowsById.get(id);
607
- if (row) row.classList.add('sel');
608
- highlightTarget(ev.target);
609
- if (ev.kind === 'lambda') {
610
- // A Lambda invocation row reloads into the re-invokable composer.
611
- shownDetailId = null;
612
- shownServeId = null;
613
- renderComposer(ev.target, ev.kind, ev.request != null ? fmt(ev.request) : '{}');
614
- shownInvId = id;
615
- renderResult(id);
616
- } else {
617
- // A captured serve request (slice C2) opens a READ-ONLY detail —
618
- // re-invoking a captured request is Phase 3.
619
- shownInvId = null;
620
- shownServeId = null;
621
- active = null;
622
- renderCapturedDetail(id);
623
- }
624
- }
625
-
626
- // Read-only Request / Response detail for a captured serve request.
627
- function renderCapturedDetail(id) {
628
- shownDetailId = id;
629
- const ev = invById.get(id);
630
- const ws = document.getElementById('workspace');
631
- ws.innerHTML = '';
632
- if (!ev) return;
633
-
634
- const head = el('div', 'composer');
635
- head.appendChild(el('div', 'target-name', (ev.label || 'request') + ' — ' + (ev.target || '')));
636
- ws.appendChild(head);
637
-
638
- const reqSec = el('div', 'section');
639
- reqSec.appendChild(el('h3', null, 'Request'));
640
- reqSec.appendChild(el('pre', null, ev.request != null ? fmt(ev.request) : '(none)'));
641
- ws.appendChild(reqSec);
642
-
643
- const respSec = el('div', 'section');
644
- const h = el('h3', null, 'Response');
645
- if (ev.status != null) {
646
- const cls = ev.status >= 200 && ev.status < 300 ? 'ok' : 'bad';
647
- h.appendChild(el('span', cls, ' ' + ev.status + (ev.durationMs != null ? ' · ' + ev.durationMs + 'ms' : '')));
648
- }
649
- respSec.appendChild(h);
650
- respSec.appendChild(el('pre', null, ev.response != null ? fmt(ev.response) : '(pending…)'));
651
- ws.appendChild(respSec);
652
-
653
- // Logs bound to THIS request at CloudWatch granularity (D5), fetched
654
- // from the server store.
655
- const logSec = el('div', 'section');
656
- logSec.appendChild(el('h3', null, 'Logs'));
657
- const logPre = el('pre', null, '(loading…)');
658
- logSec.appendChild(logPre);
659
- ws.appendChild(logSec);
660
- fetchInvocationLogs(id, logPre);
661
- }
662
-
663
- async function fetchInvocationLogs(id, pre) {
664
- try {
665
- const res = await fetch('/api/invocations/' + encodeURIComponent(id) + '/logs');
666
- const data = await res.json();
667
- const lines = (data.logs || []).map((l) => l.line);
668
- if (shownDetailId === id) pre.textContent = lines.length ? lines.join('\\n') : '(none)';
669
- } catch (err) {
670
- if (shownDetailId === id) pre.textContent = '(failed to load logs)';
671
- }
672
- }
673
-
674
- // Full-text log search over the server store. A non-empty query shows
675
- // matching log lines INSTEAD of the timeline rows; clearing restores them.
676
- let searchTimer = null;
677
- function wireLogSearch() {
678
- const input = document.getElementById('log-search');
679
- const rows = document.getElementById('timeline-rows');
680
- const results = document.getElementById('log-results');
681
- input.addEventListener('input', () => {
682
- if (searchTimer) clearTimeout(searchTimer);
683
- searchTimer = setTimeout(() => runLogSearch(input.value.trim(), rows, results), 180);
684
- });
685
- }
686
-
687
- async function runLogSearch(query, rows, results) {
688
- if (query === '') {
689
- results.classList.remove('active');
690
- rows.style.display = '';
691
- results.innerHTML = '';
692
- return;
693
- }
694
- rows.style.display = 'none';
695
- results.classList.add('active');
696
- try {
697
- const res = await fetch('/api/logs?q=' + encodeURIComponent(query));
698
- const data = await res.json();
699
- const hits = data.logs || [];
700
- results.innerHTML = '';
701
- results.appendChild(el('div', 'log-hits-meta', hits.length + ' match' + (hits.length === 1 ? '' : 'es')));
702
- for (const h of hits) {
703
- const row = el('div', 'log-hit');
704
- row.appendChild(el('span', 'lt', new Date(h.ts).toLocaleTimeString() + ' '));
705
- row.appendChild(el('span', 'lg', (h.target || '') + ' '));
706
- row.appendChild(document.createTextNode(h.line));
707
- results.appendChild(row);
708
- }
709
- } catch (err) {
710
- results.innerHTML = '';
711
- results.appendChild(el('div', 'log-hits-meta', 'Search failed: ' + err));
712
- }
713
- }
714
-
715
- // Pull retained history on (re)connect so the timeline + logs reflect the
716
- // whole session, not just events since this page loaded.
717
- async function loadHistory() {
718
- try {
719
- const res = await fetch('/api/history');
720
- const data = await res.json();
721
- for (const log of (data.logs || [])) {
722
- const arr = logsById.get(log.containerId) || [];
723
- arr.push(log.line);
724
- logsById.set(log.containerId, arr);
725
- }
726
- for (const inv of (data.invocations || [])) addInvocation(inv);
727
- } catch (err) {
728
- /* live SSE still drives the timeline; history is best-effort */
729
- }
730
- }
731
-
732
- function connect() {
733
- const conn = document.getElementById('conn');
734
- const es = new EventSource('/api/events');
735
- es.addEventListener('open', () => { conn.textContent = '● live'; conn.className = 'up'; });
736
- es.addEventListener('error', () => { conn.textContent = '● disconnected'; conn.className = 'down'; });
737
- es.addEventListener('invocation', (e) => addInvocation(JSON.parse(e.data)));
738
- es.addEventListener('serve', (e) => onServeEvent(JSON.parse(e.data)));
739
- es.addEventListener('log', (e) => {
740
- const ev = JSON.parse(e.data);
741
- const arr = logsById.get(ev.containerId) || [];
742
- arr.push(ev.line);
743
- logsById.set(ev.containerId, arr);
744
- if (shownInvId === ev.containerId) renderResult(ev.containerId);
745
- if (shownServeId === ev.containerId) renderServeWorkspace(ev.containerId);
746
- });
747
- }
748
-
749
- function onServeEvent(ev) {
750
- // A 'stopped' / 'error' transition clears the running state; otherwise
751
- // record the latest status + endpoints for the row + workspace.
752
- if (ev.status === 'stopped' || ev.status === 'error') {
753
- serveState.set(ev.target, { status: ev.status, endpoints: [] });
754
- } else {
755
- serveState.set(ev.target, { status: ev.status, endpoints: ev.endpoints || [] });
756
- }
757
- updateServeRow(ev.target);
758
- }
759
-
760
- function initSplitters() {
761
- const main = document.querySelector('main');
762
- let left = 280, right = 320;
763
- const apply = () => {
764
- main.style.gridTemplateColumns = left + 'px 5px 1fr 5px ' + right + 'px';
765
- };
766
- const wire = (splitterId, onMove) => {
767
- const s = document.getElementById(splitterId);
768
- s.addEventListener('mousedown', (e) => {
769
- e.preventDefault();
770
- const startX = e.clientX;
771
- const l0 = left, r0 = right;
772
- s.classList.add('dragging');
773
- document.body.style.userSelect = 'none';
774
- const move = (ev) => { onMove(ev.clientX - startX, l0, r0); apply(); };
775
- const up = () => {
776
- s.classList.remove('dragging');
777
- document.body.style.userSelect = '';
778
- document.removeEventListener('mousemove', move);
779
- document.removeEventListener('mouseup', up);
780
- };
781
- document.addEventListener('mousemove', move);
782
- document.addEventListener('mouseup', up);
783
- });
784
- };
785
- const clamp = (v) => Math.max(160, Math.min(760, v));
786
- wire('split-left', (dx, l0) => { left = clamp(l0 + dx); });
787
- wire('split-right', (dx, l0, r0) => { right = clamp(r0 - dx); });
788
- }
789
-
790
- loadTargets().then(loadRunning);
791
- loadHistory();
792
- connect();
793
- initSplitters();
794
- wireLogSearch();
795
- `;
796
- /**
797
- * Render the full studio HTML document. `appLabel` is shown in the
798
- * header (the CDK app / stack context); `cliName` brands the title for
799
- * host CLIs that rebrand `cdkl`.
800
- */
801
- function renderStudioHtml(appLabel, cliName) {
802
- const safeApp = escapeHtml(appLabel);
803
- const safeCli = escapeHtml(cliName);
804
- return `<!doctype html>
805
- <html lang="en">
806
- <head>
807
- <meta charset="utf-8" />
808
- <meta name="viewport" content="width=device-width, initial-scale=1" />
809
- <title>${safeCli} studio</title>
810
- <style>${STUDIO_CSS}</style>
811
- </head>
812
- <body>
813
- <header>
814
- <span class="brand">${safeCli} studio</span>
815
- <span class="meta">${safeApp}</span>
816
- <span id="conn" class="down">● connecting</span>
817
- </header>
818
- <main>
819
- <section class="pane" id="targets"><h2>Targets</h2></section>
820
- <div class="splitter" id="split-left"></div>
821
- <section class="pane" id="workspace"><div class="empty">Pick a Lambda to invoke, or an API to serve, on the left.</div></section>
822
- <div class="splitter" id="split-right"></div>
823
- <section class="pane" id="timeline">
824
- <h2>Timeline</h2>
825
- <div class="searchbar"><input id="log-search" type="search" placeholder="Search logs…" autocomplete="off" spellcheck="false" /></div>
826
- <div id="timeline-rows"><div class="empty">No requests yet.</div></div>
827
- <div id="log-results"></div>
828
- </section>
829
- </main>
830
- <script>${STUDIO_SCRIPT}<\/script>
831
- </body>
832
- </html>`;
833
- }
834
- /** Minimal HTML-escape for the few interpolated text values. */
835
- function escapeHtml(s) {
836
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
837
- }
838
-
839
- //#endregion
840
- //#region src/local/studio-server.ts
841
- /**
842
- * Project a {@link TargetListing} (the same enumeration `cdkl list`
843
- * prints) into the grouped shape the studio UI renders. ECS services and
844
- * task definitions are folded into one `ecs` group; everything else maps
845
- * one category to one group. Exported so a unit test can assert the
846
- * projection without booting the server.
847
- */
848
- function toStudioTargetGroups(listing) {
849
- const map = (entries, opts = {}) => entries.map((e) => {
850
- const t = {
851
- id: e.displayPath ?? e.qualifiedId,
852
- qualifiedId: e.qualifiedId
853
- };
854
- if (e.kind) t.surface = e.kind;
855
- if (opts.servable !== void 0) t.servable = opts.servable;
856
- return t;
857
- });
858
- return [
859
- {
860
- kind: "lambda",
861
- title: "Lambda Functions",
862
- entries: map(listing.lambdas)
863
- },
864
- {
865
- kind: "api",
866
- title: "APIs",
867
- entries: map(listing.apis)
868
- },
869
- {
870
- kind: "ecs",
871
- title: "ECS Services / Tasks",
872
- entries: [...map(listing.ecsServices, { servable: true }), ...map(listing.ecsTaskDefinitions, { servable: false })]
873
- },
874
- {
875
- kind: "agentcore",
876
- title: "AgentCore Runtimes",
877
- entries: map(listing.agentCoreRuntimes)
878
- },
879
- {
880
- kind: "alb",
881
- title: "Load Balancers",
882
- entries: map(listing.loadBalancers)
883
- }
884
- ];
885
- }
886
- const SSE_HEARTBEAT_MS = 15e3;
887
- /**
888
- * Boot the studio HTTP server: serves the embedded UI at `/`, the target
889
- * list at `/api/targets`, and a Server-Sent-Events stream of the bus's
890
- * `invocation` / `log` events at `/api/events`. Localhost-only by
891
- * default. Resolves once the socket is listening.
892
- */
893
- async function startStudioServer(options) {
894
- const host = options.host ?? "127.0.0.1";
895
- const maxBump = options.maxPortBump ?? 20;
896
- const html = renderStudioHtml(options.appLabel, options.cliName);
897
- const targetsJson = JSON.stringify({ groups: options.targetGroups });
898
- const server = createServer$1((req, res) => handleRequest(req, res, options.bus, html, targetsJson, options));
899
- const boundPort = await listenWithBump(server, host, options.port, maxBump);
900
- return {
901
- url: `http://${host}:${boundPort}`,
902
- port: boundPort,
903
- close: () => new Promise((resolveClose, reject) => {
904
- server.close((err) => err ? reject(err) : resolveClose());
905
- server.closeAllConnections?.();
906
- })
907
- };
908
- }
909
- function handleRequest(req, res, bus, html, targetsJson, options) {
910
- const url = req.url ?? "/";
911
- const path = url.split("?")[0];
912
- if (req.method === "GET" && (path === "/" || path === "/index.html")) {
913
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
914
- res.end(html);
915
- return;
916
- }
917
- if (req.method === "GET" && path === "/api/targets") {
918
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
919
- res.end(targetsJson);
920
- return;
921
- }
922
- if (req.method === "GET" && path === "/api/running") {
923
- const running = options.getRunning ? options.getRunning() : { running: [] };
924
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
925
- res.end(JSON.stringify(running));
926
- return;
927
- }
928
- if (req.method === "GET" && path === "/api/history") {
929
- const history = options.store ? options.store.history() : {
930
- invocations: [],
931
- logs: []
932
- };
933
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
934
- res.end(JSON.stringify(history));
935
- return;
936
- }
937
- if (req.method === "GET" && path === "/api/logs") {
938
- const params = new URLSearchParams(url.split("?")[1] ?? "");
939
- const query = params.get("q") ?? "";
940
- const target = params.get("target") || void 0;
941
- const logs = options.store ? options.store.searchLogs(query, target !== void 0 ? { target } : {}) : [];
942
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
943
- res.end(JSON.stringify({ logs }));
944
- return;
945
- }
946
- const invLogsMatch = /^\/api\/invocations\/([^/]+)\/logs$/.exec(path ?? "");
947
- if (req.method === "GET" && invLogsMatch) {
948
- const id = decodeURIComponent(invLogsMatch[1] ?? "");
949
- const logs = options.store ? options.store.logsForInvocation(id) : [];
950
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
951
- res.end(JSON.stringify({ logs }));
952
- return;
953
- }
954
- if (req.method === "GET" && path === "/api/events") {
955
- serveSse(req, res, bus);
956
- return;
957
- }
958
- if (req.method === "POST" && path === "/api/run") {
959
- handleDispatch(req, res, options.onRun);
960
- return;
961
- }
962
- if (req.method === "POST" && path === "/api/stop") {
963
- handleDispatch(req, res, options.onStop);
964
- return;
965
- }
966
- res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
967
- res.end("Not found");
968
- }
969
- const MAX_RUN_BODY_BYTES = 5 * 1024 * 1024;
970
- /**
971
- * Reply to a JSON POST endpoint (`/api/run` / `/api/stop`): parse the
972
- * bounded JSON body and dispatch via `handler`. 501 when no handler is
973
- * wired (the observe-only shell), 400 on a malformed body, 500 when the
974
- * handler throws.
975
- */
976
- async function handleDispatch(req, res, handler) {
977
- const sendJson = (statusCode, payload) => {
978
- res.writeHead(statusCode, { "content-type": "application/json; charset=utf-8" });
979
- res.end(JSON.stringify(payload));
980
- };
981
- if (!handler) {
982
- sendJson(501, { error: "Running targets is not supported by this studio server." });
983
- return;
984
- }
985
- let body;
986
- try {
987
- body = await readJsonBody(req);
988
- } catch (err) {
989
- sendJson(400, { error: err instanceof Error ? err.message : String(err) });
990
- return;
991
- }
992
- try {
993
- sendJson(200, await handler(body));
994
- } catch (err) {
995
- sendJson(500, { error: err instanceof Error ? err.message : String(err) });
996
- }
997
- }
998
- /** Read + JSON-parse a request body, bounded to {@link MAX_RUN_BODY_BYTES}. */
999
- function readJsonBody(req) {
1000
- return new Promise((resolveBody, reject) => {
1001
- let raw = "";
1002
- let bytes = 0;
1003
- let done = false;
1004
- const settle = (fn) => {
1005
- if (done) return;
1006
- done = true;
1007
- fn();
1008
- };
1009
- req.setEncoding("utf8");
1010
- req.on("data", (chunk) => {
1011
- if (done) return;
1012
- bytes += Buffer.byteLength(chunk);
1013
- if (bytes > MAX_RUN_BODY_BYTES) {
1014
- settle(() => reject(/* @__PURE__ */ new Error("Request body too large.")));
1015
- req.destroy();
1016
- return;
1017
- }
1018
- raw += chunk;
1019
- });
1020
- req.on("end", () => {
1021
- settle(() => {
1022
- if (raw.trim() === "") {
1023
- resolveBody(void 0);
1024
- return;
1025
- }
1026
- try {
1027
- resolveBody(JSON.parse(raw));
1028
- } catch {
1029
- reject(/* @__PURE__ */ new Error("Invalid JSON body."));
1030
- }
1031
- });
1032
- });
1033
- req.on("error", (err) => settle(() => reject(err)));
1034
- });
1035
- }
1036
- function serveSse(req, res, bus) {
1037
- res.writeHead(200, {
1038
- "content-type": "text/event-stream; charset=utf-8",
1039
- "cache-control": "no-cache, no-transform",
1040
- connection: "keep-alive"
1041
- });
1042
- let closed = false;
1043
- const heartbeat = setInterval(() => safeWrite(":hb\n\n"), SSE_HEARTBEAT_MS);
1044
- heartbeat.unref?.();
1045
- const onInvocation = (ev) => {
1046
- safeWrite(`event: invocation\ndata: ${JSON.stringify(ev)}\n\n`);
1047
- };
1048
- const onLog = (ev) => {
1049
- safeWrite(`event: log\ndata: ${JSON.stringify(ev)}\n\n`);
1050
- };
1051
- const onServe = (ev) => {
1052
- safeWrite(`event: serve\ndata: ${JSON.stringify(ev)}\n\n`);
1053
- };
1054
- function cleanup() {
1055
- if (closed) return;
1056
- closed = true;
1057
- clearInterval(heartbeat);
1058
- bus.off("invocation", onInvocation);
1059
- bus.off("log", onLog);
1060
- bus.off("serve", onServe);
1061
- }
1062
- function safeWrite(chunk) {
1063
- if (closed || res.writableEnded || res.destroyed) {
1064
- cleanup();
1065
- return;
1066
- }
1067
- res.write(chunk);
1068
- }
1069
- bus.on("invocation", onInvocation);
1070
- bus.on("log", onLog);
1071
- bus.on("serve", onServe);
1072
- req.on("close", cleanup);
1073
- res.on("close", cleanup);
1074
- res.on("error", cleanup);
1075
- safeWrite(":ok\n\n");
1076
- }
1077
- /**
1078
- * Listen on `port`, retrying `port+1`, `port+2`, ... on `EADDRINUSE` up
1079
- * to `maxBump` extra attempts. Resolves with the bound port.
1080
- */
1081
- function listenWithBump(server, host, port, maxBump) {
1082
- return new Promise((resolveListen, reject) => {
1083
- let attempt = 0;
1084
- const tryListen = (p) => {
1085
- const onError = (err) => {
1086
- if (err.code === "EADDRINUSE" && attempt < maxBump) {
1087
- attempt += 1;
1088
- server.removeListener("error", onError);
1089
- tryListen(p + 1);
1090
- return;
1091
- }
1092
- reject(err);
1093
- };
1094
- server.once("error", onError);
1095
- server.listen(p, host, () => {
1096
- server.removeListener("error", onError);
1097
- resolveListen(server.address().port);
1098
- });
1099
- };
1100
- tryListen(port);
1101
- });
1102
- }
1103
-
1104
- //#endregion
1105
- //#region src/local/studio-dispatch.ts
1106
- let idCounter = 0;
1107
- /**
1108
- * Build the studio run dispatcher. Slice B drives a single-shot Lambda
1109
- * invoke by spawning the SAME `cdkl invoke` the headless command runs —
1110
- * studio is a control plane over the CLI, so re-using the whole command
1111
- * (rather than re-wiring its internals) guarantees byte-for-byte parity
1112
- * and keeps all of `cdkl invoke`'s process-global behavior
1113
- * (`process.exit`, env mutation, stdin) isolated in a child process.
1114
- *
1115
- * The child's stdout is the Lambda response payload; its stderr (status
1116
- * + container logs) is streamed line-by-line onto the bus as `log`
1117
- * events. An `invocation` start event is emitted before spawn and an end
1118
- * event (with response + status + duration) after exit, both keyed by
1119
- * the same correlation id so the UI threads them into one timeline row.
1120
- */
1121
- function createStudioDispatcher(config) {
1122
- const spawnFn = config.spawnFn ?? spawn;
1123
- const nodeBin = config.nodeBin ?? process.execPath;
1124
- const clock = config.clock ?? Date.now;
1125
- const idFactory = config.idFactory ?? (() => {
1126
- idCounter += 1;
1127
- return `inv-${clock()}-${idCounter}`;
1128
- });
1129
- async function run(req) {
1130
- const invocationId = idFactory();
1131
- const startedAt = clock();
1132
- if (req.kind !== "lambda") {
1133
- const error = `Running '${req.kind}' targets from studio is not supported yet (Lambda only).`;
1134
- config.bus.emit("invocation", {
1135
- id: invocationId,
1136
- ts: startedAt,
1137
- target: req.targetId,
1138
- kind: req.kind,
1139
- label: "invoke",
1140
- request: req.event,
1141
- response: error,
1142
- status: 501,
1143
- durationMs: clock() - startedAt
1144
- });
1145
- return {
1146
- invocationId,
1147
- ok: false,
1148
- status: 501,
1149
- error,
1150
- durationMs: clock() - startedAt
1151
- };
1152
- }
1153
- config.bus.emit("invocation", {
1154
- id: invocationId,
1155
- ts: startedAt,
1156
- target: req.targetId,
1157
- kind: req.kind,
1158
- label: "invoke",
1159
- request: req.event
1160
- });
1161
- let dir;
1162
- try {
1163
- dir = mkdtempSync(join(tmpdir(), "cdkl-studio-run-"));
1164
- const eventFile = join(dir, "event.json");
1165
- writeFileSync(eventFile, JSON.stringify(req.event ?? {}));
1166
- const args = [
1167
- "invoke",
1168
- req.targetId,
1169
- "--event",
1170
- eventFile
1171
- ];
1172
- if (config.app) args.push("--app", config.app);
1173
- if (config.profile) args.push("--profile", config.profile);
1174
- if (config.region) args.push("--region", config.region);
1175
- for (const [k, v] of Object.entries(config.context ?? {})) args.push("-c", `${k}=${v}`);
1176
- const { code, stdout, stderr } = await runChild(spawnFn, nodeBin, [config.cliEntry, ...args], config.cwd ?? process.cwd(), invocationId, req.targetId, config.bus, clock);
1177
- const durationMs = clock() - startedAt;
1178
- const ok = code === 0;
1179
- const failure = stderr.trim() || `cdkl invoke exited ${code}`;
1180
- const stdoutLines = stdout.split("\n").map((l) => l.replace(/\r$/, "").trimEnd()).filter((l) => l.trim().length > 0);
1181
- let responseIdx = -1;
1182
- let response;
1183
- if (ok) {
1184
- for (let i = stdoutLines.length - 1; i >= 0; i -= 1) {
1185
- const parsed = tryParseJson(stdoutLines[i] ?? "");
1186
- if (parsed.ok) {
1187
- responseIdx = i;
1188
- response = parsed.value;
1189
- break;
1190
- }
1191
- }
1192
- if (responseIdx === -1 && stdoutLines.length > 0) {
1193
- responseIdx = stdoutLines.length - 1;
1194
- response = stdoutLines[responseIdx];
1195
- }
1196
- } else response = failure;
1197
- stdoutLines.forEach((line, i) => {
1198
- if (i === responseIdx) return;
1199
- config.bus.emit("log", {
1200
- ts: clock(),
1201
- containerId: invocationId,
1202
- target: req.targetId,
1203
- line,
1204
- stream: "stdout"
1205
- });
1206
- });
1207
- const raw = responseIdx >= 0 ? stdoutLines[responseIdx] ?? "" : "";
1208
- const status = ok ? 200 : 500;
1209
- config.bus.emit("invocation", {
1210
- id: invocationId,
1211
- ts: startedAt,
1212
- target: req.targetId,
1213
- kind: req.kind,
1214
- label: "invoke",
1215
- request: req.event,
1216
- response,
1217
- status,
1218
- durationMs
1219
- });
1220
- const result = {
1221
- invocationId,
1222
- ok,
1223
- status,
1224
- durationMs
1225
- };
1226
- if (raw) result.raw = raw;
1227
- if (response !== void 0) result.response = response;
1228
- if (!ok) result.error = failure;
1229
- return result;
1230
- } finally {
1231
- if (dir) rmSync(dir, {
1232
- recursive: true,
1233
- force: true
1234
- });
1235
- }
1236
- }
1237
- return { run };
1238
- }
1239
- /**
1240
- * Spawn the child invoke, accumulate stdout, and stream stderr to the
1241
- * bus line-by-line as `log` events. Resolves on process close.
1242
- */
1243
- function runChild(spawnFn, nodeBin, argv, cwd, invocationId, target, bus, clock) {
1244
- return new Promise((resolve, reject) => {
1245
- let child;
1246
- try {
1247
- child = spawnFn(nodeBin, argv, { cwd });
1248
- } catch (err) {
1249
- reject(err instanceof Error ? err : new Error(String(err)));
1250
- return;
1251
- }
1252
- let stdout = "";
1253
- let stderr = "";
1254
- let lineBuf = "";
1255
- child.stdout.setEncoding("utf8");
1256
- child.stderr.setEncoding("utf8");
1257
- child.stdout.on("data", (chunk) => {
1258
- stdout += chunk;
1259
- });
1260
- child.stderr.on("data", (chunk) => {
1261
- stderr += chunk;
1262
- lineBuf += chunk;
1263
- let nl = lineBuf.indexOf("\n");
1264
- while (nl !== -1) {
1265
- const line = lineBuf.slice(0, nl);
1266
- lineBuf = lineBuf.slice(nl + 1);
1267
- if (line.length > 0) bus.emit("log", {
1268
- ts: clock(),
1269
- containerId: invocationId,
1270
- target,
1271
- line,
1272
- stream: "stderr"
1273
- });
1274
- nl = lineBuf.indexOf("\n");
1275
- }
1276
- });
1277
- child.on("error", (err) => reject(err));
1278
- child.on("close", (code) => {
1279
- if (lineBuf.length > 0) bus.emit("log", {
1280
- ts: clock(),
1281
- containerId: invocationId,
1282
- target,
1283
- line: lineBuf,
1284
- stream: "stderr"
1285
- });
1286
- resolve({
1287
- code,
1288
- stdout,
1289
- stderr
1290
- });
1291
- });
1292
- });
1293
- }
1294
- /** Try to JSON-parse `raw`; `ok` distinguishes a parsed value from a failure. */
1295
- function tryParseJson(raw) {
1296
- if (raw === "") return {
1297
- ok: false,
1298
- value: void 0
1299
- };
1300
- try {
1301
- return {
1302
- ok: true,
1303
- value: JSON.parse(raw)
1304
- };
1305
- } catch {
1306
- return {
1307
- ok: false,
1308
- value: void 0
1309
- };
1310
- }
1311
- }
1312
-
1313
- //#endregion
1314
- //#region src/local/studio-proxy.ts
1315
- let proxyIdCounter = 0;
1316
- /**
1317
- * Start a capturing reverse proxy in front of a studio serve target
1318
- * (decision D4a: because every request to the served port flows through
1319
- * `cdkl studio`, the timeline observes them regardless of source —
1320
- * browser, curl, or the in-UI pad alike).
1321
- *
1322
- * Each HTTP request is forwarded to `upstream` and, in parallel,
1323
- * captured (method / path / headers / bounded body) and emitted as an
1324
- * `invocation` start event; when the upstream response completes, an end
1325
- * event carries the status / headers / bounded body / duration. The full
1326
- * bodies stream through untouched — only the captured copies are bounded.
1327
- * `Upgrade` (WebSocket) requests are bridged raw to the upstream without
1328
- * capture so they keep working.
1329
- *
1330
- * Studio is a control plane over the CLI, so this proxy sits in front of
1331
- * the long-running `cdkl start-api` child the serve manager spawned; it
1332
- * does NOT re-implement any routing — it forwards verbatim.
1333
- */
1334
- function startStudioProxy(config) {
1335
- const host = config.host ?? "127.0.0.1";
1336
- const clock = config.clock ?? Date.now;
1337
- const maxCapture = config.maxCaptureBytes ?? 64 * 1024;
1338
- const idFactory = config.idFactory ?? (() => {
1339
- proxyIdCounter += 1;
1340
- return `req-${clock()}-${proxyIdCounter}`;
1341
- });
1342
- const upstreamUrl = new URL(config.upstream);
1343
- const upstreamHost = upstreamUrl.hostname;
1344
- const upstreamPort = Number(upstreamUrl.port) || 80;
1345
- const server = createServer$1((clientReq, clientRes) => {
1346
- const id = idFactory();
1347
- const startedAt = clock();
1348
- const path = clientReq.url ?? "/";
1349
- const method = clientReq.method ?? "GET";
1350
- const label = `${method} ${path.split("?")[0]}`;
1351
- const reqBody = boundedCollector(maxCapture);
1352
- config.bus.emit("invocation", {
1353
- id,
1354
- ts: startedAt,
1355
- target: config.target,
1356
- kind: config.kind,
1357
- label,
1358
- request: {
1359
- method,
1360
- path,
1361
- headers: { ...clientReq.headers }
1362
- }
1363
- });
1364
- let ended = false;
1365
- const emitEnd = (status, response) => {
1366
- if (ended) return;
1367
- ended = true;
1368
- config.bus.emit("invocation", {
1369
- id,
1370
- ts: startedAt,
1371
- target: config.target,
1372
- kind: config.kind,
1373
- label,
1374
- request: {
1375
- method,
1376
- path,
1377
- headers: { ...clientReq.headers },
1378
- body: reqBody.text()
1379
- },
1380
- response,
1381
- status,
1382
- durationMs: clock() - startedAt
1383
- });
1384
- };
1385
- const upstreamReq = request({
1386
- host: upstreamHost,
1387
- port: upstreamPort,
1388
- method,
1389
- path,
1390
- headers: clientReq.headers
1391
- }, (upstreamRes) => {
1392
- const respBody = boundedCollector(maxCapture);
1393
- clientRes.writeHead(upstreamRes.statusCode ?? 502, stripHopByHop(upstreamRes.headers));
1394
- upstreamRes.on("data", (chunk) => respBody.push(chunk));
1395
- upstreamRes.pipe(clientRes);
1396
- upstreamRes.on("end", () => emitEnd(upstreamRes.statusCode ?? 502, {
1397
- status: upstreamRes.statusCode,
1398
- headers: { ...upstreamRes.headers },
1399
- body: respBody.text()
1400
- }));
1401
- upstreamRes.on("error", () => {
1402
- if (!clientRes.writableEnded) clientRes.destroy();
1403
- emitEnd(502, "upstream response stream error");
1404
- });
1405
- });
1406
- upstreamReq.on("error", (err) => {
1407
- if (!clientRes.headersSent) clientRes.writeHead(502, { "content-type": "text/plain" });
1408
- clientRes.end(`studio proxy: upstream error: ${err.message}`);
1409
- emitEnd(502, `upstream error: ${err.message}`);
1410
- });
1411
- clientReq.on("data", (chunk) => reqBody.push(chunk));
1412
- clientReq.on("error", () => {
1413
- upstreamReq.destroy();
1414
- emitEnd(499, "client aborted the request");
1415
- });
1416
- clientReq.pipe(upstreamReq);
1417
- });
1418
- const upgradeSockets = /* @__PURE__ */ new Set();
1419
- server.on("upgrade", (req, clientSocket, head) => {
1420
- const sock = clientSocket;
1421
- upgradeSockets.add(sock);
1422
- sock.on("close", () => upgradeSockets.delete(sock));
1423
- bridgeUpgrade(req, sock, head, upstreamHost, upstreamPort);
1424
- });
1425
- return new Promise((resolve, reject) => {
1426
- server.once("error", reject);
1427
- server.listen(0, host, () => {
1428
- server.removeListener("error", reject);
1429
- const port = server.address().port;
1430
- resolve({
1431
- url: `http://${host}:${port}`,
1432
- port,
1433
- close: () => new Promise((resolveClose, rejectClose) => {
1434
- for (const sock of upgradeSockets) sock.destroy();
1435
- upgradeSockets.clear();
1436
- server.close((err) => err ? rejectClose(err) : resolveClose());
1437
- server.closeAllConnections?.();
1438
- })
1439
- });
1440
- });
1441
- });
1442
- }
1443
- /** RFC 7230 hop-by-hop headers — never forwarded across a proxy. */
1444
- const HOP_BY_HOP = new Set([
1445
- "connection",
1446
- "keep-alive",
1447
- "proxy-authenticate",
1448
- "proxy-authorization",
1449
- "te",
1450
- "trailer",
1451
- "transfer-encoding",
1452
- "upgrade"
1453
- ]);
1454
- /** Copy `headers` without the hop-by-hop ones (which describe one connection). */
1455
- function stripHopByHop(headers) {
1456
- const out = {};
1457
- for (const [k, v] of Object.entries(headers)) if (!HOP_BY_HOP.has(k.toLowerCase())) out[k] = v;
1458
- return out;
1459
- }
1460
- /** A bounded byte collector that decodes to a (possibly truncated) utf8 string. */
1461
- function boundedCollector(maxBytes) {
1462
- const chunks = [];
1463
- let size = 0;
1464
- let truncated = false;
1465
- return {
1466
- push: (c) => {
1467
- if (size >= maxBytes) {
1468
- truncated = true;
1469
- return;
1470
- }
1471
- const room = maxBytes - size;
1472
- if (c.length > room) {
1473
- chunks.push(c.subarray(0, room));
1474
- size = maxBytes;
1475
- truncated = true;
1476
- } else {
1477
- chunks.push(c);
1478
- size += c.length;
1479
- }
1480
- },
1481
- text: () => {
1482
- const s = Buffer.concat(chunks).toString("utf8");
1483
- return truncated ? `${s}… (truncated)` : s;
1484
- }
1485
- };
1486
- }
1487
- /** Raw-bridge an `Upgrade` request (e.g. WebSocket) to the upstream. */
1488
- function bridgeUpgrade(req, clientSocket, head, upstreamHost, upstreamPort) {
1489
- const upstream = connect(upstreamPort, upstreamHost, () => {
1490
- let raw = `${req.method} ${req.url} HTTP/1.1\r\n`;
1491
- for (let i = 0; i < req.rawHeaders.length; i += 2) raw += `${req.rawHeaders[i]}: ${req.rawHeaders[i + 1]}\r\n`;
1492
- raw += "\r\n";
1493
- upstream.write(raw);
1494
- if (head && head.length > 0) upstream.write(head);
1495
- clientSocket.pipe(upstream);
1496
- upstream.pipe(clientSocket);
1497
- });
1498
- const teardown = () => {
1499
- clientSocket.destroy();
1500
- upstream.destroy();
1501
- };
1502
- upstream.on("error", teardown);
1503
- upstream.on("close", teardown);
1504
- clientSocket.on("error", teardown);
1505
- clientSocket.on("close", teardown);
1506
- }
1507
-
1508
- //#endregion
1509
- //#region src/local/studio-serve-manager.ts
1510
- /**
1511
- * The serve lifecycle per kind. `api` + `alb` expose host HTTP endpoints
1512
- * the studio capture proxy fronts; `ecs` (start-service) is pure compute
1513
- * with no host port, so it has no endpoint and no capture — studio just
1514
- * runs the replicas + streams their logs.
1515
- */
1516
- const SERVE_SPECS = {
1517
- api: {
1518
- command: "start-api",
1519
- portArgs: [
1520
- "--port",
1521
- "0",
1522
- "--host",
1523
- "127.0.0.1"
1524
- ],
1525
- readyRe: /Server listening on (\S+)/,
1526
- capturesHttp: true
1527
- },
1528
- alb: {
1529
- command: "start-alb",
1530
- portArgs: [],
1531
- readyRe: /ALB front-door: (https?:\/\/\S+)/,
1532
- capturesHttp: true
1533
- },
1534
- ecs: {
1535
- command: "start-service",
1536
- portArgs: [],
1537
- readyRe: /Service\(s\) running:/,
1538
- capturesHttp: false
1539
- }
1540
- };
1541
- /**
1542
- * Build the studio serve manager. Slice C1 drives a long-running
1543
- * `cdkl start-api <target>` child — studio is a control plane over the
1544
- * CLI (the same pattern as the single-shot invoke dispatcher), so it
1545
- * spawns the SAME headless serve command rather than re-wiring its
1546
- * internals. This preserves byte-for-byte parity and isolates the
1547
- * server's process-global behavior in a child.
1548
- *
1549
- * `start()` spawns the child with `--port 0` (OS-assigned, collision
1550
- * free), streams its stdout/stderr onto the bus as `log` events keyed by
1551
- * the target id, and resolves once the child prints its first
1552
- * `Server listening on <url>` line — emitting a `serve` `running` event
1553
- * with the discovered endpoints. `stop()` SIGTERMs the child (SIGKILL
1554
- * after a grace window) and emits `stopped`.
1555
- *
1556
- * Slice C2 fronts each HTTP serve endpoint with a capture proxy
1557
- * ({@link startStudioProxy}) so every request to the served port lands
1558
- * on the studio timeline (decision D4a); the `endpoints` the UI is
1559
- * handed are the proxy URLs. The serve-kinds slice generalized this to a
1560
- * per-kind {@link ServeKindSpec}: `api` (`start-api`) + `alb`
1561
- * (`start-alb`) expose host HTTP endpoints the proxy captures, while
1562
- * `ecs` (`start-service`) is pure compute — no host port, no capture,
1563
- * just the running replicas + their streamed logs.
1564
- */
1565
- function createStudioServeManager(config) {
1566
- const spawnFn = config.spawnFn ?? spawn;
1567
- const nodeBin = config.nodeBin ?? process.execPath;
1568
- const clock = config.clock ?? Date.now;
1569
- const readyTimeoutMs = config.readyTimeoutMs ?? 12e4;
1570
- const stopGraceMs = config.stopGraceMs ?? 45e3;
1571
- const setTimeoutFn = config.setTimeoutFn ?? setTimeout;
1572
- const clearTimeoutFn = config.clearTimeoutFn ?? clearTimeout;
1573
- const cwd = config.cwd ?? process.cwd();
1574
- const proxyFactory = config.proxyFactory ?? startStudioProxy;
1575
- const captureRequests = config.captureRequests ?? true;
1576
- const entries = /* @__PURE__ */ new Map();
1577
- /** Close every capture proxy fronting `e` (best-effort; idempotent). */
1578
- async function closeProxies(e) {
1579
- const proxies = e.proxies.splice(0);
1580
- await Promise.all(proxies.map((p) => p.close().catch(() => void 0)));
1581
- }
1582
- function publicState(e) {
1583
- const s = {
1584
- targetId: e.targetId,
1585
- kind: e.kind,
1586
- status: e.status,
1587
- endpoints: [...e.endpoints],
1588
- startedAt: e.startedAt
1589
- };
1590
- if (e.pid !== void 0) s.pid = e.pid;
1591
- return s;
1592
- }
1593
- function emitServe(e, message) {
1594
- const ev = {
1595
- ts: clock(),
1596
- target: e.targetId,
1597
- kind: e.kind,
1598
- status: e.status,
1599
- endpoints: [...e.endpoints]
1600
- };
1601
- if (e.pid !== void 0) ev.pid = e.pid;
1602
- if (message !== void 0) ev.message = message;
1603
- config.bus.emit("serve", ev);
1604
- }
1605
- function buildArgs(targetId, spec) {
1606
- const args = [
1607
- spec.command,
1608
- targetId,
1609
- ...spec.portArgs
1610
- ];
1611
- if (config.app) args.push("--app", config.app);
1612
- if (config.profile) args.push("--profile", config.profile);
1613
- if (config.region) args.push("--region", config.region);
1614
- for (const [k, v] of Object.entries(config.context ?? {})) args.push("-c", `${k}=${v}`);
1615
- return args;
1616
- }
1617
- async function start(req) {
1618
- const spec = SERVE_SPECS[req.kind];
1619
- if (!spec) throw new Error(`Serving '${req.kind}' targets from studio is not supported (serve kinds: ${Object.keys(SERVE_SPECS).join(", ")}).`);
1620
- const existing = entries.get(req.targetId);
1621
- if (existing && existing.status !== "stopped" && existing.status !== "error") throw new Error(`'${req.targetId}' is already running.`);
1622
- const startedAt = clock();
1623
- let child;
1624
- try {
1625
- child = spawnFn(nodeBin, [config.cliEntry, ...buildArgs(req.targetId, spec)], { cwd });
1626
- } catch (err) {
1627
- throw err instanceof Error ? err : new Error(String(err));
1628
- }
1629
- const entry = {
1630
- targetId: req.targetId,
1631
- kind: req.kind,
1632
- status: "starting",
1633
- endpoints: [],
1634
- startedAt,
1635
- child,
1636
- proxies: []
1637
- };
1638
- if (child.pid !== void 0) entry.pid = child.pid;
1639
- entries.set(req.targetId, entry);
1640
- emitServe(entry);
1641
- return new Promise((resolve, reject) => {
1642
- let settled = false;
1643
- child.stdout.setEncoding("utf8");
1644
- child.stderr.setEncoding("utf8");
1645
- const timer = setTimeoutFn(() => {
1646
- if (settled) return;
1647
- settled = true;
1648
- entry.status = "error";
1649
- emitServe(entry, `Timed out after ${readyTimeoutMs}ms waiting for the serve to be ready.`);
1650
- stopChild(child, stopGraceMs, setTimeoutFn, clearTimeoutFn);
1651
- closeProxies(entry);
1652
- entries.delete(req.targetId);
1653
- reject(/* @__PURE__ */ new Error(`'${req.targetId}' did not start within ${readyTimeoutMs}ms.`));
1654
- }, readyTimeoutMs);
1655
- timer.unref?.();
1656
- const becomeRunning = () => {
1657
- if (settled) return;
1658
- settled = true;
1659
- clearTimeoutFn(timer);
1660
- entry.status = "running";
1661
- emitServe(entry);
1662
- resolve(publicState(entry));
1663
- };
1664
- const onReady = async (childUrl) => {
1665
- let endpoint = childUrl;
1666
- if (childUrl && spec.capturesHttp && captureRequests && /^https?:/i.test(childUrl)) try {
1667
- const proxy = await proxyFactory({
1668
- bus: config.bus,
1669
- target: req.targetId,
1670
- kind: req.kind,
1671
- upstream: childUrl
1672
- });
1673
- entry.proxies.push(proxy);
1674
- endpoint = proxy.url;
1675
- } catch {
1676
- endpoint = childUrl;
1677
- }
1678
- if (entry.stopping || settled && !entries.has(req.targetId)) {
1679
- await closeProxies(entry);
1680
- return;
1681
- }
1682
- if (endpoint && !entry.endpoints.includes(endpoint)) entry.endpoints.push(endpoint);
1683
- if (settled) emitServe(entry);
1684
- else becomeRunning();
1685
- };
1686
- streamLines(child.stdout, (line) => {
1687
- const m = spec.readyRe.exec(line);
1688
- if (m) onReady(m[1]);
1689
- emitLog(config.bus, clock, req.targetId, line, "stdout");
1690
- });
1691
- streamLines(child.stderr, (line) => {
1692
- emitLog(config.bus, clock, req.targetId, line, "stderr");
1693
- });
1694
- child.on("error", (err) => {
1695
- if (settled) {
1696
- entry.status = "error";
1697
- emitServe(entry, err.message);
1698
- closeProxies(entry);
1699
- entries.delete(req.targetId);
1700
- return;
1701
- }
1702
- settled = true;
1703
- clearTimeoutFn(timer);
1704
- entry.status = "error";
1705
- emitServe(entry, err.message);
1706
- closeProxies(entry);
1707
- entries.delete(req.targetId);
1708
- reject(err);
1709
- });
1710
- child.on("close", (code) => {
1711
- if (!settled) {
1712
- settled = true;
1713
- clearTimeoutFn(timer);
1714
- if (entry.stopping) {
1715
- reject(/* @__PURE__ */ new Error(`'${req.targetId}' was stopped before it finished starting.`));
1716
- return;
1717
- }
1718
- entry.status = "error";
1719
- const msg = `Server exited before listening (code ${code ?? "null"}).`;
1720
- emitServe(entry, msg);
1721
- closeProxies(entry);
1722
- entries.delete(req.targetId);
1723
- reject(new Error(msg));
1724
- return;
1725
- }
1726
- if (entries.get(req.targetId) === entry && entry.status === "running") {
1727
- entry.status = "stopped";
1728
- emitServe(entry, `Server process exited (code ${code ?? "null"}).`);
1729
- closeProxies(entry);
1730
- entries.delete(req.targetId);
1731
- }
1732
- });
1733
- });
1734
- }
1735
- async function stop(req) {
1736
- const entry = entries.get(req.targetId);
1737
- if (!entry) throw new Error(`'${req.targetId}' is not running.`);
1738
- entry.stopping = true;
1739
- entries.delete(req.targetId);
1740
- await Promise.all([closeProxies(entry), stopChild(entry.child, stopGraceMs, setTimeoutFn, clearTimeoutFn)]);
1741
- entry.status = "stopped";
1742
- emitServe(entry);
1743
- }
1744
- function list() {
1745
- return [...entries.values()].map(publicState);
1746
- }
1747
- async function stopAll() {
1748
- const targets = [...entries.keys()];
1749
- await Promise.all(targets.map((targetId) => stop({ targetId }).catch(() => void 0)));
1750
- }
1751
- return {
1752
- start,
1753
- stop,
1754
- list,
1755
- stopAll
1756
- };
1757
- }
1758
- /** Emit one container log line onto the bus, keyed by the serve target id. */
1759
- function emitLog(bus, clock, target, line, stream) {
1760
- bus.emit("log", {
1761
- ts: clock(),
1762
- containerId: target,
1763
- target,
1764
- line,
1765
- stream
1766
- });
1767
- }
1768
- /**
1769
- * Line-buffer a child stream and invoke `onLine` per complete line
1770
- * (trailing newline stripped, blank lines dropped). Flushes any partial
1771
- * final line on stream end.
1772
- */
1773
- function streamLines(stream, onLine) {
1774
- let buf = "";
1775
- stream.on("data", (chunk) => {
1776
- buf += chunk;
1777
- let nl = buf.indexOf("\n");
1778
- while (nl !== -1) {
1779
- const line = buf.slice(0, nl).replace(/\r$/, "");
1780
- buf = buf.slice(nl + 1);
1781
- if (line.length > 0) onLine(line);
1782
- nl = buf.indexOf("\n");
1783
- }
1784
- });
1785
- stream.on("end", () => {
1786
- const line = buf.replace(/\r$/, "");
1787
- if (line.length > 0) onLine(line);
1788
- buf = "";
1789
- });
1790
- }
1791
- /**
1792
- * SIGTERM a child and resolve once it exits, escalating to SIGKILL after
1793
- * `graceMs`. Resolves immediately if the child has already exited.
1794
- */
1795
- function stopChild(child, graceMs, setTimeoutFn, clearTimeoutFn) {
1796
- return new Promise((resolve) => {
1797
- let done = false;
1798
- let kill;
1799
- const finish = () => {
1800
- if (done) return;
1801
- done = true;
1802
- if (kill) clearTimeoutFn(kill);
1803
- resolve();
1804
- };
1805
- child.once("close", finish);
1806
- if (child.exitCode !== null || child.signalCode !== null) {
1807
- finish();
1808
- return;
1809
- }
1810
- kill = setTimeoutFn(() => {
1811
- if (!done) child.kill("SIGKILL");
1812
- }, graceMs);
1813
- kill.unref?.();
1814
- child.kill("SIGTERM");
1815
- });
1816
- }
1817
-
1818
- //#endregion
1819
- //#region src/cli/commands/local-studio.ts
1820
- const STUDIO_TARGET_KINDS = [
1821
- "lambda",
1822
- "api",
1823
- "alb",
1824
- "ecs",
1825
- "agentcore"
1826
- ];
1827
- /**
1828
- * Validate + narrow the untyped `POST /api/run` body into a
1829
- * {@link StudioRunRequest}. Throws (→ 400 from the server) on a malformed
1830
- * body so a bad UI / curl payload fails loudly rather than spawning an
1831
- * `invoke` for an empty target.
1832
- */
1833
- function coerceRunRequest(body) {
1834
- if (typeof body !== "object" || body === null) throw new Error("Request body must be a JSON object.");
1835
- const { targetId, kind, event } = body;
1836
- if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("Request body must include a non-empty \"targetId\" string.");
1837
- if (typeof kind !== "string" || !STUDIO_TARGET_KINDS.includes(kind)) throw new Error(`Request body "kind" must be one of: ${STUDIO_TARGET_KINDS.join(", ")}.`);
1838
- return {
1839
- targetId,
1840
- kind,
1841
- event
1842
- };
1843
- }
1844
- /**
1845
- * Validate + narrow the untyped `POST /api/stop` body into a
1846
- * {@link StudioStopRequest}. Throws (→ 400 from the server) on a missing
1847
- * / empty target id.
1848
- */
1849
- function coerceStopRequest(body) {
1850
- if (typeof body !== "object" || body === null) throw new Error("Request body must be a JSON object.");
1851
- const { targetId } = body;
1852
- if (typeof targetId !== "string" || targetId.trim() === "") throw new Error("Request body must include a non-empty \"targetId\" string.");
1853
- return { targetId };
1854
- }
1855
- const DEFAULT_STUDIO_PORT = 9999;
1856
- /**
1857
- * Parse + validate the `--studio-port` value. Accepts `0` (OS-assigned)
1858
- * through `65535`. Exported so a unit test can assert the bounds without
1859
- * driving the full command. Throws on anything out of range / non-numeric.
1860
- */
1861
- function parseStudioPort(raw) {
1862
- const port = raw.trim() === "" ? NaN : Number(raw);
1863
- if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`--studio-port must be 0..65535 (got ${raw}).`);
1864
- return port;
1865
- }
1866
- async function localStudioCommand(options) {
1867
- const logger = getLogger();
1868
- if (options.verbose) logger.setLevel("debug");
1869
- const port = parseStudioPort(options.studioPort);
1870
- await applyRoleArnIfSet({
1871
- roleArn: options.roleArn,
1872
- region: void 0,
1873
- profile: options.profile
1874
- });
1875
- const appCmd = resolveApp(options.app);
1876
- if (!appCmd) throw new Error(`No CDK app specified. Pass --app, set ${getEmbedConfig().envPrefix}_APP, or add "app" to cdk.json.`);
1877
- logger.info("Synthesizing CDK app...");
1878
- const synthesizer = new Synthesizer();
1879
- const context = parseContextOptions(options.context);
1880
- const synthOpts = {
1881
- app: appCmd,
1882
- output: options.output,
1883
- ...options.profile && { profile: options.profile },
1884
- ...Object.keys(context).length > 0 && { context }
1885
- };
1886
- const { stacks } = await synthesizer.synthesize(synthOpts);
1887
- const targetGroups = toStudioTargetGroups(listTargets(stacks));
1888
- const appLabel = stacks.map((s) => s.stackName).join(", ") || appCmd;
1889
- const servableEcs = new Set(targetGroups.filter((g) => g.kind === "ecs").flatMap((g) => g.entries.filter((e) => e.servable).map((e) => e.id)));
1890
- const bus = new StudioEventBus();
1891
- const childConfig = {
1892
- cliEntry: process.argv[1] ?? "",
1893
- bus,
1894
- cwd: process.cwd(),
1895
- ...appCmd ? { app: appCmd } : {},
1896
- ...options.profile ? { profile: options.profile } : {},
1897
- ...options.region ? { region: options.region } : {},
1898
- ...Object.keys(context).length > 0 ? { context } : {}
1899
- };
1900
- const dispatcher = createStudioDispatcher(childConfig);
1901
- const serveManager = createStudioServeManager(childConfig);
1902
- const store = createStudioStore(bus);
1903
- const server = await startStudioServer({
1904
- port,
1905
- bus,
1906
- targetGroups,
1907
- appLabel,
1908
- cliName: getEmbedConfig().cliName,
1909
- store,
1910
- onRun: (body) => {
1911
- const req = coerceRunRequest(body);
1912
- if (req.kind === "lambda") return dispatcher.run(req);
1913
- if (req.kind === "ecs" && !servableEcs.has(req.targetId)) return Promise.reject(/* @__PURE__ */ new Error(`'${req.targetId}' is not a servable ECS service (an ECS task definition runs via run-task, not start-service).`));
1914
- return serveManager.start(req);
1915
- },
1916
- onStop: async (body) => {
1917
- const req = coerceStopRequest(body);
1918
- await serveManager.stop(req);
1919
- return { stopped: req.targetId };
1920
- },
1921
- getRunning: () => ({ running: serveManager.list() })
1922
- });
1923
- const cliName = getEmbedConfig().cliName;
1924
- logger.info(`${cliName} studio is running at ${server.url}`);
1925
- logger.info("Press Ctrl-C to stop.");
1926
- if (options.open && process.stdout.isTTY) openBrowser(server.url);
1927
- await blockUntilShutdown(server, serveManager, store, cliName);
1928
- }
1929
- /** Best-effort cross-platform browser open. Failures are non-fatal. */
1930
- function openBrowser(url) {
1931
- const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1932
- try {
1933
- const child = spawn(cmd, [url], {
1934
- stdio: "ignore",
1935
- detached: true,
1936
- shell: process.platform === "win32"
1937
- });
1938
- child.on("error", () => void 0);
1939
- child.unref();
1940
- } catch {}
1941
- }
1942
- /**
1943
- * Block until SIGINT / SIGTERM, then stop every running serve child,
1944
- * close the studio server, and resolve. Mirrors the long-running serve
1945
- * commands' graceful-shutdown contract — the serve children are killed
1946
- * BEFORE the server closes so their RIE containers are torn down rather
1947
- * than orphaned.
1948
- */
1949
- function blockUntilShutdown(server, serveManager, store, cliName) {
1950
- return new Promise((resolveShutdown) => {
1951
- let shuttingDown = false;
1952
- const shutdown = (signal) => {
1953
- if (shuttingDown) return;
1954
- shuttingDown = true;
1955
- getLogger().info(`Received ${signal}; stopping ${cliName} studio...`);
1956
- store.dispose();
1957
- serveManager.stopAll().catch((err) => getLogger().warn(`Error stopping serve targets: ${String(err)}`)).then(() => server.close()).catch((err) => getLogger().warn(`Error stopping studio server: ${String(err)}`)).finally(() => resolveShutdown());
1958
- };
1959
- process.on("SIGINT", () => shutdown("SIGINT"));
1960
- process.on("SIGTERM", () => shutdown("SIGTERM"));
1961
- });
1962
- }
1963
- function createLocalStudioCommand(opts = {}) {
1964
- setEmbedConfig(opts.embedConfig);
1965
- const cmd = new Command("studio").description("Open the local studio: a web console that lists the synthesized CDK app's runnable targets and lets you invoke / serve them from the browser while watching all activity in one timeline. The interactive counterpart to the headless invoke / start-* commands.").action(withErrorHandling(async (options) => {
1966
- await localStudioCommand(options);
1967
- }));
1968
- addStudioSpecificOptions(cmd);
1969
- [
1970
- ...commonOptions(),
1971
- ...appOptions(),
1972
- ...contextOptions
1973
- ].forEach((opt) => cmd.addOption(opt));
1974
- cmd.addOption(regionOption);
1975
- return cmd;
1976
- }
1977
- /**
1978
- * Register the option block `cdkl studio` adds on top of the shared
1979
- * common / app / context option helpers. Kept in a named helper (not
1980
- * inline in {@link createLocalStudioCommand}) so a host CLI embedding
1981
- * this factory inherits new studio flags without a duplicate
1982
- * `.addOption(...)` block, matching every other `add<Cmd>SpecificOptions`
1983
- * extraction. Chainable: returns `cmd`.
1984
- */
1985
- function addStudioSpecificOptions(cmd) {
1986
- cmd.addOption(new Option("--studio-port <port>", "Preferred port for the studio web server (bumps to the next free port on collision)").default(String(DEFAULT_STUDIO_PORT)));
1987
- cmd.addOption(new Option("--no-open", "Do not auto-open the browser when studio starts (TTY only)"));
1988
- return cmd;
1989
- }
1990
-
1991
- //#endregion
1992
- export { createStudioServeManager as a, startStudioServer as c, createStudioStore as d, StudioEventBus as f, createLocalStudioCommand as i, toStudioTargetGroups as l, coerceRunRequest as n, startStudioProxy as o, coerceStopRequest as r, createStudioDispatcher as s, addStudioSpecificOptions as t, renderStudioHtml as u };
1993
- //# sourceMappingURL=local-studio-8r3jr9nj.js.map