devanvil 0.0.0-stage → 2.1.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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.ar.md +113 -0
  3. package/README.md +272 -2
  4. package/SECURITY.md +49 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +659 -0
  7. package/dist/core/contract-drift.d.ts +49 -0
  8. package/dist/core/contract-drift.js +302 -0
  9. package/dist/core/converters.d.ts +18 -0
  10. package/dist/core/converters.js +981 -0
  11. package/dist/core/cron.d.ts +33 -0
  12. package/dist/core/cron.js +306 -0
  13. package/dist/core/crypto.d.ts +59 -0
  14. package/dist/core/crypto.js +250 -0
  15. package/dist/core/curl.d.ts +17 -0
  16. package/dist/core/curl.js +170 -0
  17. package/dist/core/diff.d.ts +36 -0
  18. package/dist/core/diff.js +148 -0
  19. package/dist/core/encoding.d.ts +3 -0
  20. package/dist/core/encoding.js +143 -0
  21. package/dist/core/importers.d.ts +65 -0
  22. package/dist/core/importers.js +361 -0
  23. package/dist/core/jwt.d.ts +39 -0
  24. package/dist/core/jwt.js +256 -0
  25. package/dist/core/llm-tokens.d.ts +38 -0
  26. package/dist/core/llm-tokens.js +125 -0
  27. package/dist/core/log-analyzer.d.ts +30 -0
  28. package/dist/core/log-analyzer.js +155 -0
  29. package/dist/core/network.d.ts +72 -0
  30. package/dist/core/network.js +185 -0
  31. package/dist/core/oauth-protobuf.d.ts +74 -0
  32. package/dist/core/oauth-protobuf.js +390 -0
  33. package/dist/core/openapi.d.ts +27 -0
  34. package/dist/core/openapi.js +257 -0
  35. package/dist/core/pipeline.d.ts +28 -0
  36. package/dist/core/pipeline.js +154 -0
  37. package/dist/core/regex.d.ts +50 -0
  38. package/dist/core/regex.js +351 -0
  39. package/dist/core/runner.d.ts +53 -0
  40. package/dist/core/runner.js +250 -0
  41. package/dist/core/secrets.d.ts +87 -0
  42. package/dist/core/secrets.js +599 -0
  43. package/dist/core/security.d.ts +34 -0
  44. package/dist/core/security.js +284 -0
  45. package/dist/core/sql-explain.d.ts +50 -0
  46. package/dist/core/sql-explain.js +259 -0
  47. package/dist/core/tls.d.ts +44 -0
  48. package/dist/core/tls.js +166 -0
  49. package/dist/index.d.ts +31 -0
  50. package/dist/index.js +31 -0
  51. package/dist/server/app.d.ts +31 -0
  52. package/dist/server/app.js +348 -0
  53. package/dist/server/http-proxy.d.ts +55 -0
  54. package/dist/server/http-proxy.js +364 -0
  55. package/dist/server/http-utils.d.ts +28 -0
  56. package/dist/server/http-utils.js +106 -0
  57. package/dist/server/load-tester.d.ts +53 -0
  58. package/dist/server/load-tester.js +134 -0
  59. package/dist/server/mcp.d.ts +35 -0
  60. package/dist/server/mcp.js +466 -0
  61. package/dist/server/mock-store.d.ts +38 -0
  62. package/dist/server/mock-store.js +197 -0
  63. package/dist/server/plugin-loader.d.ts +60 -0
  64. package/dist/server/plugin-loader.js +285 -0
  65. package/dist/server/recorder-store.d.ts +35 -0
  66. package/dist/server/recorder-store.js +146 -0
  67. package/dist/server/routes/network-routes.d.ts +3 -0
  68. package/dist/server/routes/network-routes.js +391 -0
  69. package/dist/server/routes/tools-routes.d.ts +3 -0
  70. package/dist/server/routes/tools-routes.js +292 -0
  71. package/dist/server/routes/workspace-routes.d.ts +3 -0
  72. package/dist/server/routes/workspace-routes.js +240 -0
  73. package/dist/server/webhook-store.d.ts +29 -0
  74. package/dist/server/webhook-store.js +90 -0
  75. package/dist/server/workspace-store.d.ts +91 -0
  76. package/dist/server/workspace-store.js +447 -0
  77. package/dist/server/ws-probe.d.ts +34 -0
  78. package/dist/server/ws-probe.js +283 -0
  79. package/dist/ui/app.js +274 -0
  80. package/dist/ui/favicon.svg +14 -0
  81. package/dist/ui/index.html +83 -0
  82. package/dist/ui/logo.png +0 -0
  83. package/dist/ui/styles.css +694 -0
  84. package/dist/ui/tools-data.js +704 -0
  85. package/dist/ui/tools-network.js +727 -0
  86. package/dist/ui/tools-ops.js +295 -0
  87. package/dist/ui/tools-pro.js +500 -0
  88. package/dist/ui/tools-security.js +389 -0
  89. package/dist/ui/tools-v12.js +745 -0
  90. package/dist/ui/tools-v13.js +321 -0
  91. package/dist/ui/tools-v20.js +563 -0
  92. package/dist/ui/tools-v21.js +395 -0
  93. package/package.json +75 -4
@@ -0,0 +1,727 @@
1
+ (function () {
2
+ 'use strict';
3
+ const { h, api, toast, copyText, registerTool, openInApiStudio, consumePendingApiRequest } = window.DevAnvil;
4
+
5
+ // ───────────────────────────────────────────────────────────────────────────
6
+ // 1. CORS-Free API Studio
7
+ // ───────────────────────────────────────────────────────────────────────────
8
+ registerTool({
9
+ id: 'api-studio',
10
+ group: 'Network & API',
11
+ name: 'API Studio',
12
+ icon: '⚡',
13
+ subtitle: 'CORS-free HTTP client with timings, cURL import & multi-language codegen',
14
+ keywords: ['http', 'rest', 'postman', 'curl', 'fetch', 'request', 'proxy', 'api'],
15
+ render(root) {
16
+ const pending = consumePendingApiRequest ? consumePendingApiRequest() : null;
17
+ let method = pending?.method || 'GET';
18
+ let respTab = 'body';
19
+ let codeLang = 'curl';
20
+ let lastResponse = null;
21
+ let lastSnippets = null;
22
+
23
+ function loadHistory() {
24
+ try {
25
+ return JSON.parse(localStorage.getItem('devanvil.apiHistory') || '[]');
26
+ } catch {
27
+ return [];
28
+ }
29
+ }
30
+ function saveHistory(entry) {
31
+ const list = loadHistory().filter((x) => !(x.method === entry.method && x.url === entry.url));
32
+ list.unshift(entry);
33
+ localStorage.setItem('devanvil.apiHistory', JSON.stringify(list.slice(0, 12)));
34
+ renderHistory();
35
+ }
36
+
37
+ const methodSel = h(
38
+ 'select',
39
+ { style: { width: '115px', flexShrink: '0', fontFamily: 'var(--font-mono)', fontWeight: '700' }, onChange: (e) => { method = e.target.value; } },
40
+ ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].map((m) => h('option', { value: m, selected: m === method }, m)),
41
+ );
42
+ const urlInput = h('input', {
43
+ type: 'text',
44
+ value: pending?.url || 'https://httpbin.org/json',
45
+ placeholder: 'https://api.example.com/v1/resource or {{BASE_URL}}/mock/users',
46
+ class: 'mono',
47
+ style: { flex: '1' },
48
+ });
49
+ const sendBtn = h('button', { type: 'button', class: 'btn btn-primary', onClick: sendRequest }, 'Send Request');
50
+ const sseBtn = h('button', { type: 'button', class: 'btn btn-sm', onClick: sendSseStream }, 'SSE Stream (TTFT)');
51
+ const recordMockChk = h('input', { type: 'checkbox' });
52
+ const envSelect = h('select', { style: { width: '160px' }, onChange: async (e) => {
53
+ if (!e.target.value) return;
54
+ await api('/api/workspace/environments/active', { body: { id: e.target.value } });
55
+ toast('Active environment switched', 'ok');
56
+ } });
57
+
58
+ async function loadEnvironments() {
59
+ try {
60
+ const data = await api('/api/workspace');
61
+ const ws = data.workspace;
62
+ envSelect.textContent = '';
63
+ for (const env of ws.environments || []) {
64
+ envSelect.appendChild(h('option', { value: env.id, selected: env.id === ws.activeEnvironmentId }, `Env: ${env.name}`));
65
+ }
66
+ } catch { /* ignore */ }
67
+ }
68
+
69
+ async function saveToCollection() {
70
+ try {
71
+ await api('/api/workspace/collections', {
72
+ body: {
73
+ request: {
74
+ name: `${method} ${urlInput.value.trim().slice(0, 40)}`,
75
+ method,
76
+ url: urlInput.value.trim(),
77
+ headers: buildEffectiveHeaders(),
78
+ body: bodyArea.value,
79
+ },
80
+ },
81
+ });
82
+ toast('Saved request to Workspace Collection!', 'ok');
83
+ } catch (err) {
84
+ toast(err.message, 'err');
85
+ }
86
+ }
87
+
88
+ const initialHeadersText = pending?.headers
89
+ ? Object.entries(pending.headers).map(([k, v]) => `${k}: ${v}`).join('\n')
90
+ : 'Accept: application/json\nUser-Agent: DevAnvil/1.1';
91
+
92
+ const headersArea = h('textarea', {
93
+ rows: 5,
94
+ value: initialHeadersText,
95
+ placeholder: 'Header-Name: value (one per line)',
96
+ });
97
+ const bodyArea = h('textarea', {
98
+ rows: 6,
99
+ value: pending?.body !== undefined ? pending.body : '{\n "tool": "DevAnvil",\n "offline": true\n}',
100
+ placeholder: 'Request body (JSON, text, form data)…',
101
+ });
102
+ const curlImportInput = h('input', {
103
+ type: 'text',
104
+ class: 'mono',
105
+ placeholder: 'Paste a curl command to import… e.g. curl -X POST https://httpbin.org/post -H "Content-Type: application/json" -d \'{"ok":1}\'',
106
+ });
107
+
108
+ // Auth helper bar
109
+ const authTypeSel = h(
110
+ 'select',
111
+ { style: { width: '140px' } },
112
+ [
113
+ ['none', 'Auth: None'],
114
+ ['bearer', 'Bearer Token'],
115
+ ['apikey', 'X-API-Key'],
116
+ ['basic', 'Basic Auth (u:p)'],
117
+ ].map(([v, l]) => h('option', { value: v }, l)),
118
+ );
119
+ const authValInput = h('input', { type: 'password', class: 'mono', placeholder: 'Token, API key, or user:pass (injected into request headers)', style: { flex: '1' } });
120
+ const historyRow = h('div', { class: 'row' });
121
+
122
+ function renderHistory() {
123
+ const list = loadHistory();
124
+ historyRow.textContent = '';
125
+ if (!list.length) {
126
+ historyRow.appendChild(h('span', { style: { fontSize: '11.5px', color: 'var(--text-dim)' } }, 'No recent requests yet'));
127
+ return;
128
+ }
129
+ for (const item of list.slice(0, 6)) {
130
+ historyRow.appendChild(
131
+ h(
132
+ 'button',
133
+ {
134
+ type: 'button',
135
+ class: 'btn btn-ghost btn-xs mono',
136
+ onClick: () => {
137
+ method = item.method;
138
+ methodSel.value = item.method;
139
+ urlInput.value = item.url;
140
+ headersArea.value = item.headers || '';
141
+ bodyArea.value = item.body || '';
142
+ void refreshCodegen();
143
+ },
144
+ },
145
+ `${item.method} ${item.url.replace(/^https?:\/\//, '').slice(0, 28)}`,
146
+ ),
147
+ );
148
+ }
149
+ }
150
+
151
+ function buildEffectiveHeaders() {
152
+ const hdrs = parseHeadersText(headersArea.value);
153
+ const aType = authTypeSel.value;
154
+ const aVal = authValInput.value.trim();
155
+ if (aType === 'bearer' && aVal) hdrs['Authorization'] = `Bearer ${aVal}`;
156
+ else if (aType === 'apikey' && aVal) hdrs['X-API-Key'] = aVal;
157
+ else if (aType === 'basic' && aVal) hdrs['Authorization'] = `Basic ${btoa(aVal)}`;
158
+ return hdrs;
159
+ }
160
+
161
+ const statusMeta = h('div', { class: 'row' });
162
+ const responseContent = h('pre', { class: 'code-box' }, 'Send a request to inspect status, headers, response body & timings.');
163
+ const codeOutput = h('pre', { class: 'code-box' }, '');
164
+
165
+ function parseHeadersText(text) {
166
+ const out = {};
167
+ for (const line of text.split('\n')) {
168
+ const idx = line.indexOf(':');
169
+ if (idx > 0) out[line.slice(0, idx).trim()] = line.slice(idx + 1).trim();
170
+ }
171
+ return out;
172
+ }
173
+
174
+ async function refreshCodegen() {
175
+ try {
176
+ lastSnippets = await api('/api/curl/generate', {
177
+ body: { method, url: urlInput.value, headers: buildEffectiveHeaders(), body: bodyArea.value },
178
+ });
179
+ codeOutput.textContent = lastSnippets[codeLang] || '';
180
+ } catch (err) {
181
+ codeOutput.textContent = `Error: ${err.message}`;
182
+ }
183
+ }
184
+
185
+ function renderResponseView() {
186
+ if (!lastResponse) return;
187
+ statusMeta.textContent = '';
188
+ const ok = lastResponse.status >= 200 && lastResponse.status < 300;
189
+ const warn = lastResponse.status >= 300 && lastResponse.status < 400;
190
+ statusMeta.appendChild(
191
+ h('span', { class: `badge ${ok ? 'badge-ok' : warn ? 'badge-warn' : 'badge-err'}` }, `${lastResponse.status} ${lastResponse.statusText}`),
192
+ );
193
+ statusMeta.appendChild(h('span', { class: 'badge badge-subtle' }, `Total ${lastResponse.timings.totalMs}ms`));
194
+ statusMeta.appendChild(h('span', { class: 'badge badge-subtle' }, `TTFB ${lastResponse.timings.ttfbMs}ms`));
195
+ statusMeta.appendChild(h('span', { class: 'badge badge-subtle' }, `${lastResponse.sizeBytes.toLocaleString()} B`));
196
+ if (lastResponse.redirects > 0) {
197
+ statusMeta.appendChild(h('span', { class: 'badge badge-info' }, `${lastResponse.redirects} redirect(s)`));
198
+ }
199
+
200
+ if (respTab === 'headers') {
201
+ responseContent.textContent = Object.entries(lastResponse.headers)
202
+ .map(([k, v]) => `${k}: ${v}`)
203
+ .join('\n');
204
+ } else if (respTab === 'timings') {
205
+ responseContent.textContent = JSON.stringify(
206
+ { finalUrl: lastResponse.finalUrl, contentType: lastResponse.contentType, sizeBytes: lastResponse.sizeBytes, timings: lastResponse.timings },
207
+ null,
208
+ 2,
209
+ );
210
+ } else {
211
+ try {
212
+ const parsed = JSON.parse(lastResponse.body);
213
+ responseContent.textContent = JSON.stringify(parsed, null, 2);
214
+ } catch {
215
+ responseContent.textContent = lastResponse.body || '(empty response body)';
216
+ }
217
+ }
218
+ }
219
+
220
+ async function sendRequest() {
221
+ sendBtn.disabled = true;
222
+ sendBtn.textContent = 'Sending…';
223
+ try {
224
+ lastResponse = await api('/api/proxy', {
225
+ body: {
226
+ method,
227
+ url: urlInput.value.trim(),
228
+ headers: buildEffectiveHeaders(),
229
+ body: bodyArea.value,
230
+ useEnvironment: true,
231
+ recordAsMock: recordMockChk.checked,
232
+ },
233
+ });
234
+ saveHistory({ method, url: urlInput.value.trim(), headers: headersArea.value, body: bodyArea.value });
235
+ renderResponseView();
236
+ await refreshCodegen();
237
+ if (lastResponse.recordedMockPath) {
238
+ toast(`Recorded live mock at ${lastResponse.recordedMockPath}!`, 'ok');
239
+ } else {
240
+ toast(`Received HTTP ${lastResponse.status} in ${lastResponse.timings.totalMs}ms`, 'ok');
241
+ }
242
+ } catch (err) {
243
+ statusMeta.textContent = '';
244
+ statusMeta.appendChild(h('span', { class: 'badge badge-err' }, 'Request Blocked / Failed'));
245
+ responseContent.textContent = err.message;
246
+ toast(err.message, 'err');
247
+ } finally {
248
+ sendBtn.disabled = false;
249
+ sendBtn.textContent = 'Send Request';
250
+ }
251
+ }
252
+
253
+ async function sendSseStream() {
254
+ sseBtn.disabled = true;
255
+ sseBtn.textContent = 'Streaming…';
256
+ try {
257
+ const res = await api('/api/proxy/sse', {
258
+ body: {
259
+ method,
260
+ url: urlInput.value.trim(),
261
+ headers: buildEffectiveHeaders(),
262
+ body: bodyArea.value,
263
+ useEnvironment: true,
264
+ maxEvents: 30,
265
+ maxDurationMs: 6000,
266
+ },
267
+ });
268
+ statusMeta.textContent = '';
269
+ statusMeta.appendChild(h('span', { class: 'badge badge-ok' }, `SSE HTTP ${res.status}`));
270
+ statusMeta.appendChild(h('span', { class: 'badge badge-info' }, `TTFT ${res.ttfbMs}ms`));
271
+ statusMeta.appendChild(h('span', { class: 'badge badge-subtle' }, `${res.eventCount} event(s) · ${res.totalMs}ms`));
272
+ statusMeta.appendChild(h('span', { class: 'badge badge-subtle' }, `stop: ${res.stoppedReason}`));
273
+ responseContent.textContent = res.events.length
274
+ ? res.events.map((e) => `#${e.index} [+${e.deltaMs}ms] (${e.event}) ${e.data}`).join('\n')
275
+ : '(stream closed with 0 SSE data frames)';
276
+ toast(`Captured ${res.eventCount} SSE event(s) · TTFT ${res.ttfbMs}ms`, 'ok');
277
+ } catch (err) {
278
+ statusMeta.textContent = '';
279
+ statusMeta.appendChild(h('span', { class: 'badge badge-err' }, 'SSE Stream Failed'));
280
+ responseContent.textContent = err.message;
281
+ toast(err.message, 'err');
282
+ } finally {
283
+ sseBtn.disabled = false;
284
+ sseBtn.textContent = 'SSE Stream (TTFT)';
285
+ }
286
+ }
287
+
288
+ async function importCurl() {
289
+ if (!curlImportInput.value.trim()) return;
290
+ try {
291
+ const parsed = await api('/api/curl/parse', { body: { command: curlImportInput.value } });
292
+ method = parsed.method;
293
+ methodSel.value = parsed.method;
294
+ urlInput.value = parsed.url;
295
+ headersArea.value = Object.entries(parsed.headers || {})
296
+ .map(([k, v]) => `${k}: ${v}`)
297
+ .join('\n');
298
+ bodyArea.value = parsed.body || '';
299
+ await refreshCodegen();
300
+ toast('Imported cURL request', 'ok');
301
+ } catch (err) {
302
+ toast(err.message, 'err');
303
+ }
304
+ }
305
+
306
+ const respTabs = h('div', { class: 'tabs' });
307
+ ['body', 'headers', 'timings'].forEach((t) => {
308
+ const btn = h(
309
+ 'button',
310
+ {
311
+ type: 'button',
312
+ class: `tab-btn ${respTab === t ? 'active' : ''}`,
313
+ onClick: () => {
314
+ respTab = t;
315
+ Array.from(respTabs.children).forEach((el) => el.classList.remove('active'));
316
+ btn.classList.add('active');
317
+ renderResponseView();
318
+ },
319
+ },
320
+ t.toUpperCase(),
321
+ );
322
+ respTabs.appendChild(btn);
323
+ });
324
+
325
+ const langTabs = h('div', { class: 'tabs' });
326
+ [
327
+ ['curl', 'cURL'],
328
+ ['fetch', 'JS Fetch'],
329
+ ['python', 'Python'],
330
+ ['go', 'Go'],
331
+ ].forEach(([id, label]) => {
332
+ const btn = h(
333
+ 'button',
334
+ {
335
+ type: 'button',
336
+ class: `tab-btn ${codeLang === id ? 'active' : ''}`,
337
+ onClick: () => {
338
+ codeLang = id;
339
+ Array.from(langTabs.children).forEach((el) => el.classList.remove('active'));
340
+ btn.classList.add('active');
341
+ if (lastSnippets) codeOutput.textContent = lastSnippets[codeLang] || '';
342
+ else void refreshCodegen();
343
+ },
344
+ },
345
+ label,
346
+ );
347
+ langTabs.appendChild(btn);
348
+ });
349
+
350
+ const layout = h(
351
+ 'div',
352
+ { class: 'stack' },
353
+ h(
354
+ 'div',
355
+ { class: 'card' },
356
+ h('div', { class: 'row' }, methodSel, urlInput, sendBtn, sseBtn),
357
+ h(
358
+ 'div',
359
+ { class: 'row-between' },
360
+ h(
361
+ 'div',
362
+ { class: 'row' },
363
+ envSelect,
364
+ h('label', { class: 'row', style: { fontSize: '12px' } }, recordMockChk, 'Record response -> Live /mock/*'),
365
+ ),
366
+ h(
367
+ 'div',
368
+ { class: 'row' },
369
+ h('button', { type: 'button', class: 'btn btn-sm', onClick: saveToCollection }, 'Save to Collection'),
370
+ h('button', { type: 'button', class: 'btn btn-ghost btn-sm', onClick: refreshCodegen }, 'Generate Code'),
371
+ ),
372
+ ),
373
+ h(
374
+ 'div',
375
+ { class: 'row' },
376
+ curlImportInput,
377
+ h('button', { type: 'button', class: 'btn btn-sm', onClick: importCurl }, 'Import cURL'),
378
+ ),
379
+ h('div', { class: 'row' }, authTypeSel, authValInput),
380
+ h('div', { class: 'row' }, h('span', { style: { fontSize: '11.5px', color: 'var(--text-dim)' } }, 'Recent:'), historyRow),
381
+ ),
382
+ h(
383
+ 'div',
384
+ { class: 'grid-2' },
385
+ h(
386
+ 'div',
387
+ { class: 'card' },
388
+ h('h2', { class: 'card-title' }, 'Request Headers & Body'),
389
+ h('div', {}, h('label', { class: 'field-label' }, 'Headers (Key: Value per line)'), headersArea),
390
+ h('div', {}, h('label', { class: 'field-label' }, 'Payload Body'), bodyArea),
391
+ ),
392
+ h(
393
+ 'div',
394
+ { class: 'card' },
395
+ h(
396
+ 'div',
397
+ { class: 'row-between' },
398
+ h('h2', { class: 'card-title' }, 'Response'),
399
+ h('div', { class: 'row' }, respTabs, h('button', { type: 'button', class: 'btn btn-ghost btn-xs', onClick: () => copyText(responseContent.textContent) }, 'Copy')),
400
+ ),
401
+ statusMeta,
402
+ responseContent,
403
+ ),
404
+ ),
405
+ h(
406
+ 'div',
407
+ { class: 'card' },
408
+ h(
409
+ 'div',
410
+ { class: 'row-between' },
411
+ h('h2', { class: 'card-title' }, 'Code Snippet Generator'),
412
+ h('div', { class: 'row' }, langTabs, h('button', { type: 'button', class: 'btn btn-ghost btn-xs', onClick: () => copyText(codeOutput.textContent) }, 'Copy Snippet')),
413
+ ),
414
+ codeOutput,
415
+ ),
416
+ );
417
+
418
+ root.appendChild(layout);
419
+ renderHistory();
420
+ void loadEnvironments();
421
+ void refreshCodegen();
422
+ },
423
+ });
424
+
425
+ // ───────────────────────────────────────────────────────────────────────────
426
+ // 2. Live Mock API Server & Real-Time SSE Webhook Catcher
427
+ // ───────────────────────────────────────────────────────────────────────────
428
+ registerTool({
429
+ id: 'mock-webhook',
430
+ group: 'Network & API',
431
+ name: 'Mock & Webhooks',
432
+ icon: '🛰',
433
+ subtitle: 'Instant dynamic Mock API endpoints (/mock/*) + live SSE Webhook Catcher (/hook/*)',
434
+ keywords: ['mock', 'server', 'webhook', 'sse', 'stub', 'endpoint', 'ngrok'],
435
+ render(root) {
436
+ let sseSource = null;
437
+ let activeChannel = 'default';
438
+
439
+ // --- Mock API Builder ---
440
+ const mockMethod = h(
441
+ 'select',
442
+ { style: { width: '105px' } },
443
+ ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'ANY'].map((m) => h('option', { value: m }, m)),
444
+ );
445
+ const mockPath = h('input', { type: 'text', class: 'mono', value: '/orders/:id', placeholder: '/users/:id' });
446
+ const mockStatus = h('input', { type: 'number', value: '200', min: '100', max: '599', style: { width: '90px' } });
447
+ const mockDelay = h('input', { type: 'number', value: '0', min: '0', max: '5000', style: { width: '100px' }, title: 'Simulated latency ms' });
448
+ const mockBody = h('textarea', {
449
+ rows: 5,
450
+ value: '{\n "orderId": "{{param.id}}",\n "status": "shipped",\n "generatedAt": "{{timestamp}}",\n "traceId": "{{uuid}}"\n}',
451
+ });
452
+ const mockList = h('div', { class: 'stack' });
453
+ const mockPreview = h('pre', { class: 'code-box' }, 'Click "Test" on any mock route to call it live.');
454
+
455
+ async function loadMocks() {
456
+ try {
457
+ const { routes } = await api('/api/mocks');
458
+ mockList.textContent = '';
459
+ if (!routes.length) {
460
+ mockList.appendChild(h('div', { style: { color: 'var(--text-dim)' } }, 'No mock routes yet. Add one above.'));
461
+ return;
462
+ }
463
+ for (const r of routes) {
464
+ const samplePath = `/mock${r.path.replace(/:([a-zA-Z0-9_]+)/g, '42')}`;
465
+ const item = h(
466
+ 'div',
467
+ { class: 'list-item' },
468
+ h(
469
+ 'div',
470
+ { class: 'row-between' },
471
+ h(
472
+ 'div',
473
+ { class: 'row' },
474
+ h('span', { class: 'badge badge-info' }, r.method),
475
+ h('span', { class: 'mono', style: { fontWeight: '600' } }, `/mock${r.path}`),
476
+ h('span', { class: `badge ${r.status < 300 ? 'badge-ok' : r.status < 400 ? 'badge-warn' : 'badge-err'}` }, String(r.status)),
477
+ h('span', { class: 'badge badge-subtle' }, `${r.hits} hits`),
478
+ ),
479
+ h(
480
+ 'div',
481
+ { class: 'row' },
482
+ h(
483
+ 'button',
484
+ {
485
+ type: 'button',
486
+ class: 'btn btn-xs',
487
+ onClick: async () => {
488
+ const testMethod = r.method === 'ANY' ? 'GET' : r.method;
489
+ const resp = await fetch(samplePath, {
490
+ method: testMethod,
491
+ headers: testMethod !== 'GET' && testMethod !== 'HEAD' ? { 'Content-Type': 'application/json' } : {},
492
+ body: testMethod !== 'GET' && testMethod !== 'HEAD' ? '{"sample":true}' : undefined,
493
+ });
494
+ const txt = await resp.text();
495
+ mockPreview.textContent = `${testMethod} ${samplePath} -> HTTP ${resp.status}\n\n${txt}`;
496
+ await loadMocks();
497
+ },
498
+ },
499
+ 'Test Live',
500
+ ),
501
+ h(
502
+ 'button',
503
+ {
504
+ type: 'button',
505
+ class: 'btn btn-ghost btn-xs',
506
+ onClick: () => copyText(`${window.location.origin}${samplePath}`, 'Copied mock URL'),
507
+ },
508
+ 'Copy URL',
509
+ ),
510
+ h(
511
+ 'button',
512
+ {
513
+ type: 'button',
514
+ class: 'btn btn-danger btn-xs',
515
+ onClick: async () => {
516
+ await api(`/api/mocks/${r.id}`, { method: 'DELETE' });
517
+ toast('Mock route removed', 'ok');
518
+ await loadMocks();
519
+ },
520
+ },
521
+ 'Delete',
522
+ ),
523
+ ),
524
+ ),
525
+ );
526
+ mockList.appendChild(item);
527
+ }
528
+ } catch (err) {
529
+ toast(err.message, 'err');
530
+ }
531
+ }
532
+
533
+ async function createMock() {
534
+ try {
535
+ await api('/api/mocks', {
536
+ body: {
537
+ method: mockMethod.value,
538
+ path: mockPath.value,
539
+ status: Number(mockStatus.value),
540
+ delayMs: Number(mockDelay.value),
541
+ body: mockBody.value,
542
+ headers: { 'Content-Type': 'application/json' },
543
+ },
544
+ });
545
+ toast('Mock route registered live', 'ok');
546
+ await loadMocks();
547
+ } catch (err) {
548
+ toast(err.message, 'err');
549
+ }
550
+ }
551
+
552
+ // --- Live SSE Webhook Catcher ---
553
+ const channelInput = h('input', { type: 'text', class: 'mono', value: activeChannel, style: { width: '160px' } });
554
+ const hookUrlBox = h('code', { class: 'mono', style: { color: 'var(--accent)', fontSize: '12px' } });
555
+ const sseBadge = h('span', { class: 'badge badge-subtle' }, 'Connecting…');
556
+ const webhookFeed = h('div', { class: 'stack' });
557
+ const webhookDetail = h('pre', { class: 'code-box' }, 'Trigger a webhook or click "Send Test Webhook" to inspect live payloads.');
558
+
559
+ function updateHookUrl() {
560
+ hookUrlBox.textContent = `${window.location.origin}/hook/${activeChannel}`;
561
+ }
562
+
563
+ function renderWebhookEvents(events) {
564
+ webhookFeed.textContent = '';
565
+ if (!events.length) {
566
+ webhookFeed.appendChild(h('div', { style: { color: 'var(--text-dim)', fontSize: '12.5px' } }, 'Listening for incoming HTTP requests on this channel…'));
567
+ return;
568
+ }
569
+ for (const ev of events) {
570
+ const row = h(
571
+ 'div',
572
+ { class: 'list-item', style: { cursor: 'pointer' }, onClick: () => {
573
+ webhookDetail.textContent = JSON.stringify(ev, null, 2);
574
+ } },
575
+ h(
576
+ 'div',
577
+ { class: 'row-between' },
578
+ h('div', { class: 'row' }, h('span', { class: 'badge badge-ok' }, ev.method), h('span', { class: 'mono' }, ev.path), h('span', { class: 'badge badge-subtle' }, `${ev.sizeBytes} B`)),
579
+ h(
580
+ 'div',
581
+ { class: 'row' },
582
+ h(
583
+ 'button',
584
+ {
585
+ type: 'button',
586
+ class: 'btn btn-ghost btn-xs',
587
+ onClick: (e) => {
588
+ e.stopPropagation();
589
+ const cleanHeaders = {};
590
+ for (const [hk, hv] of Object.entries(ev.headers || {})) {
591
+ if (!['host', 'content-length', 'connection'].includes(hk.toLowerCase())) cleanHeaders[hk] = hv;
592
+ }
593
+ openInApiStudio({
594
+ method: ev.method,
595
+ url: `${window.location.origin}/hook/${activeChannel}${ev.path}`,
596
+ headers: cleanHeaders,
597
+ body: ev.body || '',
598
+ });
599
+ },
600
+ },
601
+ 'Replay -> API Studio',
602
+ ),
603
+ h('span', { class: 'mono', style: { fontSize: '11px', color: 'var(--text-dim)' } }, ev.receivedAt.slice(11, 23) + 'Z'),
604
+ ),
605
+ ),
606
+ );
607
+ webhookFeed.appendChild(row);
608
+ }
609
+ webhookDetail.textContent = JSON.stringify(events[0], null, 2);
610
+ }
611
+
612
+ async function connectChannel(ch) {
613
+ activeChannel = ch.trim() || 'default';
614
+ updateHookUrl();
615
+ if (sseSource) {
616
+ sseSource.close();
617
+ sseSource = null;
618
+ }
619
+ try {
620
+ const data = await api(`/api/webhooks/${encodeURIComponent(activeChannel)}`);
621
+ renderWebhookEvents(data.events || []);
622
+ sseSource = new EventSource(`/api/webhooks/${encodeURIComponent(activeChannel)}/stream`);
623
+ sseSource.addEventListener('connected', () => {
624
+ sseBadge.textContent = 'SSE Live';
625
+ sseBadge.className = 'badge badge-ok';
626
+ });
627
+ sseSource.addEventListener('webhook', async () => {
628
+ const refreshed = await api(`/api/webhooks/${encodeURIComponent(activeChannel)}`);
629
+ renderWebhookEvents(refreshed.events || []);
630
+ });
631
+ sseSource.addEventListener('cleared', () => {
632
+ renderWebhookEvents([]);
633
+ webhookDetail.textContent = 'Channel cleared.';
634
+ });
635
+ sseSource.onerror = () => {
636
+ sseBadge.textContent = 'Reconnecting…';
637
+ sseBadge.className = 'badge badge-warn';
638
+ };
639
+ } catch (err) {
640
+ toast(err.message, 'err');
641
+ }
642
+ }
643
+
644
+ async function sendTestWebhook() {
645
+ await fetch(`/hook/${encodeURIComponent(activeChannel)}/stripe-demo?env=staging`, {
646
+ method: 'POST',
647
+ headers: { 'Content-Type': 'application/json', 'X-Webhook-Signature': 't=1700000000,v1=demo_sig' },
648
+ body: JSON.stringify({ event: 'invoice.paid', amount: 4900, currency: 'usd', liveTest: true }),
649
+ });
650
+ toast('Captured test webhook live!', 'ok');
651
+ }
652
+
653
+ const layout = h(
654
+ 'div',
655
+ { class: 'grid-2' },
656
+ h(
657
+ 'div',
658
+ { class: 'stack' },
659
+ h(
660
+ 'div',
661
+ { class: 'card' },
662
+ h('h2', { class: 'card-title' }, 'Create Live Mock Endpoint (/mock/*)'),
663
+ h('div', { class: 'row' }, mockMethod, h('div', { style: { flex: '1' } }, mockPath), mockStatus, mockDelay),
664
+ h('div', {}, h('label', { class: 'field-label' }, 'Response Body (supports {{param.id}}, {{query.x}}, {{timestamp}}, {{uuid}})'), mockBody),
665
+ h('div', { class: 'row' }, h('button', { type: 'button', class: 'btn btn-primary', onClick: createMock }, 'Add Mock Route')),
666
+ ),
667
+ h(
668
+ 'div',
669
+ { class: 'card' },
670
+ h(
671
+ 'div',
672
+ { class: 'row-between' },
673
+ h('h2', { class: 'card-title' }, 'Active Mock Routes'),
674
+ h(
675
+ 'button',
676
+ {
677
+ type: 'button',
678
+ class: 'btn btn-ghost btn-xs',
679
+ onClick: async () => {
680
+ const data = await api('/api/mocks');
681
+ await copyText(JSON.stringify(data.routes, null, 2), 'Exported mock routes JSON to clipboard');
682
+ },
683
+ },
684
+ 'Export JSON',
685
+ ),
686
+ ),
687
+ mockList,
688
+ ),
689
+ h('div', { class: 'card' }, h('h2', { class: 'card-title' }, 'Live Mock Test Output'), mockPreview),
690
+ ),
691
+ h(
692
+ 'div',
693
+ { class: 'stack' },
694
+ h(
695
+ 'div',
696
+ { class: 'card' },
697
+ h('div', { class: 'row-between' }, h('h2', { class: 'card-title' }, 'Live Webhook Inspector (SSE)'), sseBadge),
698
+ h(
699
+ 'div',
700
+ { class: 'row' },
701
+ channelInput,
702
+ h('button', { type: 'button', class: 'btn btn-sm', onClick: () => connectChannel(channelInput.value) }, 'Switch Channel'),
703
+ h('button', { type: 'button', class: 'btn btn-primary btn-sm', onClick: sendTestWebhook }, 'Send Test Webhook'),
704
+ h('button', { type: 'button', class: 'btn btn-ghost btn-sm', onClick: () => api(`/api/webhooks/${encodeURIComponent(activeChannel)}`, { method: 'DELETE' }) }, 'Clear'),
705
+ ),
706
+ h(
707
+ 'div',
708
+ { class: 'row-between', style: { padding: '8px 10px', borderRadius: '7px', background: 'var(--bg-input)', border: '1px solid var(--border)' } },
709
+ hookUrlBox,
710
+ h('button', { type: 'button', class: 'btn btn-ghost btn-xs', onClick: () => copyText(hookUrlBox.textContent, 'Copied webhook URL') }, 'Copy'),
711
+ ),
712
+ webhookFeed,
713
+ ),
714
+ h('div', { class: 'card' }, h('h2', { class: 'card-title' }, 'Selected Event Inspector'), webhookDetail),
715
+ ),
716
+ );
717
+
718
+ root.appendChild(layout);
719
+ void loadMocks();
720
+ void connectChannel(activeChannel);
721
+
722
+ return () => {
723
+ if (sseSource) sseSource.close();
724
+ };
725
+ },
726
+ });
727
+ })();