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