@revenexx/integrations-node-devkit 0.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.
package/dist/cli.cjs ADDED
@@ -0,0 +1,1967 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_node_fs3 = require("fs");
28
+ var import_node_http2 = require("http");
29
+ var import_node_module = require("module");
30
+ var import_node_path3 = require("path");
31
+ var import_node_url2 = require("url");
32
+
33
+ // src/errors.ts
34
+ var DevApiError = class extends Error {
35
+ constructor(status, message, errors) {
36
+ super(message);
37
+ this.status = status;
38
+ this.errors = errors;
39
+ this.name = "DevApiError";
40
+ }
41
+ status;
42
+ errors;
43
+ };
44
+
45
+ // src/loader.ts
46
+ var import_node_url = require("url");
47
+ var import_integrations_node_sdk = require("@revenexx/integrations-node-sdk");
48
+ function resolveExports(mod) {
49
+ if (!Array.isArray(mod.NODES)) {
50
+ throw new Error("Package entry does not export a `NODES` array. Export `NODES: INode[]`.");
51
+ }
52
+ if (mod.CREDENTIALS !== void 0 && !Array.isArray(mod.CREDENTIALS)) {
53
+ throw new Error("Package entry exports `CREDENTIALS` but it is not an array.");
54
+ }
55
+ if (mod.TEMPLATES !== void 0 && !Array.isArray(mod.TEMPLATES)) {
56
+ throw new Error("Package entry exports `TEMPLATES` but it is not an array.");
57
+ }
58
+ const nodes = mod.NODES;
59
+ const credentials = mod.CREDENTIALS ?? [];
60
+ const templates = mod.TEMPLATES ?? [];
61
+ return {
62
+ nodes,
63
+ credentials,
64
+ templates,
65
+ manifest: (0, import_integrations_node_sdk.buildManifest)(nodes, credentials, templates)
66
+ };
67
+ }
68
+ var tsxRegistered = false;
69
+ async function ensureTsxRegistered() {
70
+ if (tsxRegistered) {
71
+ return;
72
+ }
73
+ const { register } = await import("tsx/esm/api");
74
+ register();
75
+ tsxRegistered = true;
76
+ }
77
+ async function importFresh(entryPath) {
78
+ if (/\.[cm]?tsx?$/.test(entryPath)) {
79
+ await ensureTsxRegistered();
80
+ }
81
+ const href = `${(0, import_node_url.pathToFileURL)(entryPath).href}?t=${Date.now()}`;
82
+ return await import(href);
83
+ }
84
+ async function loadPackageFromEntry(entryPath) {
85
+ return resolveExports(await importFresh(entryPath));
86
+ }
87
+
88
+ // src/persistence.ts
89
+ var import_node_fs = require("fs");
90
+ var import_node_path = require("path");
91
+
92
+ // src/store.ts
93
+ var import_node_crypto = require("crypto");
94
+ var DEV_TENANT_ID = "dev-tenant";
95
+ var STORE_SCHEMA_VERSION = 1;
96
+ function now() {
97
+ return (/* @__PURE__ */ new Date()).toISOString();
98
+ }
99
+ var DevStore = class {
100
+ /**
101
+ * @param onChange fired after any mutation so a caller (the CLI) can persist
102
+ * the session to `.revenexx-dev/state.json`.
103
+ */
104
+ constructor(onChange) {
105
+ this.onChange = onChange;
106
+ }
107
+ onChange;
108
+ credentials = /* @__PURE__ */ new Map();
109
+ secrets = /* @__PURE__ */ new Map();
110
+ workflows = /* @__PURE__ */ new Map();
111
+ triggers = /* @__PURE__ */ new Map();
112
+ nextWorkflowId = 1;
113
+ /** (Re)wire the post-mutation callback — e.g. attach it only after seeding. */
114
+ setOnMutation(onChange) {
115
+ this.onChange = onChange;
116
+ }
117
+ touch() {
118
+ this.onChange?.();
119
+ }
120
+ // ------------------------------------------------------------- credentials
121
+ listCredentials(typeSlug) {
122
+ const all = [...this.credentials.values()];
123
+ return typeSlug ? all.filter((c) => c.credentialTypeSlug === typeSlug) : all;
124
+ }
125
+ getCredential(id) {
126
+ return this.credentials.get(id);
127
+ }
128
+ createCredential(input) {
129
+ const ts = now();
130
+ const record = {
131
+ id: input.id ?? (0, import_node_crypto.randomUUID)(),
132
+ tenantId: DEV_TENANT_ID,
133
+ credentialTypeSlug: input.credentialTypeSlug,
134
+ name: input.name,
135
+ status: input.status ?? "active",
136
+ config: input.config,
137
+ durableCreds: input.durableCreds ?? null,
138
+ createdAt: ts,
139
+ updatedAt: ts
140
+ };
141
+ this.credentials.set(record.id, record);
142
+ this.touch();
143
+ return record;
144
+ }
145
+ updateCredential(id, patch) {
146
+ const record = this.credentials.get(id);
147
+ if (!record) {
148
+ return void 0;
149
+ }
150
+ if (patch.name !== void 0) {
151
+ record.name = patch.name;
152
+ }
153
+ if (patch.config !== void 0) {
154
+ record.config = patch.config;
155
+ }
156
+ if (patch.status !== void 0) {
157
+ record.status = patch.status;
158
+ }
159
+ if (patch.durableCreds !== void 0) {
160
+ record.durableCreds = patch.durableCreds;
161
+ }
162
+ record.updatedAt = now();
163
+ this.touch();
164
+ return record;
165
+ }
166
+ deleteCredential(id) {
167
+ const deleted = this.credentials.delete(id);
168
+ if (deleted) {
169
+ this.touch();
170
+ }
171
+ return deleted;
172
+ }
173
+ // ----------------------------------------------------------------- secrets
174
+ listSecrets() {
175
+ return [...this.secrets.values()];
176
+ }
177
+ getSecret(key) {
178
+ return this.secrets.get(key);
179
+ }
180
+ setSecret(key, value) {
181
+ const existing = this.secrets.get(key);
182
+ const ts = now();
183
+ const record = {
184
+ key,
185
+ value,
186
+ createdAt: existing?.createdAt ?? ts,
187
+ updatedAt: ts
188
+ };
189
+ this.secrets.set(key, record);
190
+ this.touch();
191
+ return record;
192
+ }
193
+ deleteSecret(key) {
194
+ const deleted = this.secrets.delete(key);
195
+ if (deleted) {
196
+ this.touch();
197
+ }
198
+ return deleted;
199
+ }
200
+ // --------------------------------------------------------------- workflows
201
+ listWorkflows() {
202
+ return [...this.workflows.values()];
203
+ }
204
+ getWorkflow(id) {
205
+ return this.workflows.get(id);
206
+ }
207
+ createWorkflow(input) {
208
+ const ts = now();
209
+ const record = {
210
+ id: this.nextWorkflowId++,
211
+ name: input.name,
212
+ definition: input.definition,
213
+ buildStatus: "ready",
214
+ createdAt: ts,
215
+ updatedAt: ts
216
+ };
217
+ this.workflows.set(record.id, record);
218
+ this.touch();
219
+ return record;
220
+ }
221
+ updateWorkflow(id, patch) {
222
+ const record = this.workflows.get(id);
223
+ if (!record) {
224
+ return void 0;
225
+ }
226
+ Object.assign(record, patch, { updatedAt: now() });
227
+ this.touch();
228
+ return record;
229
+ }
230
+ deleteWorkflow(id) {
231
+ for (const trigger of this.triggers.values()) {
232
+ if (trigger.workflowId === id) {
233
+ this.triggers.delete(trigger.id);
234
+ }
235
+ }
236
+ const deleted = this.workflows.delete(id);
237
+ if (deleted) {
238
+ this.touch();
239
+ }
240
+ return deleted;
241
+ }
242
+ // ---------------------------------------------------------------- triggers
243
+ listTriggers(workflowId) {
244
+ return [...this.triggers.values()].filter((t) => t.workflowId === workflowId);
245
+ }
246
+ getTrigger(id) {
247
+ return this.triggers.get(id);
248
+ }
249
+ createTrigger(input) {
250
+ const ts = now();
251
+ const record = {
252
+ id: input.id ?? (0, import_node_crypto.randomUUID)(),
253
+ workflowId: input.workflowId,
254
+ type: input.type,
255
+ name: input.name ?? null,
256
+ config: input.config ?? {},
257
+ active: input.active ?? true,
258
+ createdAt: ts,
259
+ updatedAt: ts
260
+ };
261
+ this.triggers.set(record.id, record);
262
+ this.touch();
263
+ return record;
264
+ }
265
+ replaceTrigger(id, input) {
266
+ const record = this.triggers.get(id);
267
+ if (!record) {
268
+ return void 0;
269
+ }
270
+ record.type = input.type;
271
+ record.name = input.name ?? null;
272
+ record.config = input.config ?? {};
273
+ record.active = input.active ?? true;
274
+ record.updatedAt = now();
275
+ this.touch();
276
+ return record;
277
+ }
278
+ deleteTrigger(id) {
279
+ const deleted = this.triggers.delete(id);
280
+ if (deleted) {
281
+ this.touch();
282
+ }
283
+ return deleted;
284
+ }
285
+ // ------------------------------------------------------------- persistence
286
+ toSnapshot() {
287
+ return {
288
+ schemaVersion: STORE_SCHEMA_VERSION,
289
+ credentials: [...this.credentials.values()],
290
+ secrets: [...this.secrets.values()],
291
+ workflows: [...this.workflows.values()],
292
+ triggers: [...this.triggers.values()],
293
+ nextWorkflowId: this.nextWorkflowId
294
+ };
295
+ }
296
+ loadSnapshot(snapshot) {
297
+ this.credentials = new Map(snapshot.credentials.map((c) => [c.id, c]));
298
+ this.secrets = new Map(snapshot.secrets.map((s) => [s.key, s]));
299
+ this.workflows = new Map(snapshot.workflows.map((w) => [w.id, w]));
300
+ this.triggers = new Map(snapshot.triggers.map((t) => [t.id, t]));
301
+ this.nextWorkflowId = snapshot.nextWorkflowId ?? Math.max(0, ...snapshot.workflows.map((w) => w.id)) + 1;
302
+ }
303
+ /**
304
+ * Overlays a snapshot on top of the current contents (upsert by id/key), used
305
+ * to layer the persisted `.revenexx-dev/state.json` session over the freshly
306
+ * applied committed seeds. State entries win over seed entries with the same
307
+ * id/key; seed-only entries are preserved.
308
+ */
309
+ mergeSnapshot(snapshot) {
310
+ for (const c of snapshot.credentials) {
311
+ this.credentials.set(c.id, c);
312
+ }
313
+ for (const s of snapshot.secrets) {
314
+ this.secrets.set(s.key, s);
315
+ }
316
+ for (const w of snapshot.workflows) {
317
+ this.workflows.set(w.id, w);
318
+ }
319
+ for (const t of snapshot.triggers) {
320
+ this.triggers.set(t.id, t);
321
+ }
322
+ this.nextWorkflowId = Math.max(this.nextWorkflowId, snapshot.nextWorkflowId ?? 0, ...snapshot.workflows.map((w) => w.id + 1));
323
+ }
324
+ };
325
+
326
+ // src/persistence.ts
327
+ var ENV_REF = /\$\{([A-Z0-9_]+)\}/g;
328
+ function interpolateEnv(value, env = process.env) {
329
+ if (typeof value === "string") {
330
+ return value.replace(ENV_REF, (_match, name) => {
331
+ const resolved = env[name];
332
+ if (resolved === void 0) {
333
+ throw new Error(`Seed references \${${name}} but that environment variable is not set (add it to your .env).`);
334
+ }
335
+ return resolved;
336
+ });
337
+ }
338
+ if (Array.isArray(value)) {
339
+ return value.map((item) => interpolateEnv(item, env));
340
+ }
341
+ if (value && typeof value === "object") {
342
+ const out = {};
343
+ for (const [key, val] of Object.entries(value)) {
344
+ out[key] = interpolateEnv(val, env);
345
+ }
346
+ return out;
347
+ }
348
+ return value;
349
+ }
350
+ function applySeeds(store, seeds, env = process.env) {
351
+ for (const secret of seeds.secrets ?? []) {
352
+ const { key, value } = interpolateEnv(secret, env);
353
+ store.setSecret(key, value);
354
+ }
355
+ for (const credential of seeds.credentials ?? []) {
356
+ const resolved = interpolateEnv(credential, env);
357
+ store.createCredential({
358
+ credentialTypeSlug: resolved.credentialTypeSlug,
359
+ name: resolved.name,
360
+ config: resolved.config,
361
+ id: resolved.id,
362
+ status: resolved.status,
363
+ durableCreds: resolved.durableCreds ?? null
364
+ });
365
+ }
366
+ for (const workflow of seeds.workflows ?? []) {
367
+ store.createWorkflow(interpolateEnv(workflow, env));
368
+ }
369
+ }
370
+ function loadState(file, log = console.warn) {
371
+ if (!(0, import_node_fs.existsSync)(file)) {
372
+ return null;
373
+ }
374
+ let parsed;
375
+ try {
376
+ parsed = JSON.parse((0, import_node_fs.readFileSync)(file, "utf-8"));
377
+ } catch {
378
+ log(`Ignoring ${file}: not valid JSON.`);
379
+ return null;
380
+ }
381
+ if (parsed.schemaVersion !== STORE_SCHEMA_VERSION) {
382
+ log(`Ignoring ${file}: schemaVersion ${parsed.schemaVersion} != ${STORE_SCHEMA_VERSION} (discarded, seeds are the source of truth).`);
383
+ return null;
384
+ }
385
+ return parsed;
386
+ }
387
+ function saveState(file, snapshot) {
388
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(file), { recursive: true });
389
+ (0, import_node_fs.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
390
+ }
391
+ var SEED_ENTRY_CANDIDATES = ["index.ts", "index.mjs", "index.js", "seeds.ts", "seeds.js"];
392
+ async function loadSeedsFromDir(dir) {
393
+ for (const candidate of SEED_ENTRY_CANDIDATES) {
394
+ const path = (0, import_node_path.resolve)(dir, candidate);
395
+ if ((0, import_node_fs.existsSync)(path)) {
396
+ const mod = await importFresh(path);
397
+ return mod.default ?? mod.seeds ?? {};
398
+ }
399
+ }
400
+ return {};
401
+ }
402
+
403
+ // src/resolve.ts
404
+ var import_integrations_node_sdk2 = require("@revenexx/integrations-node-sdk");
405
+ var noopLogger = {
406
+ info() {
407
+ },
408
+ warn() {
409
+ },
410
+ error() {
411
+ }
412
+ };
413
+ function compareSemver(a, b) {
414
+ const pa = a.split(".").map((n) => Number.parseInt(n, 10) || 0);
415
+ const pb = b.split(".").map((n) => Number.parseInt(n, 10) || 0);
416
+ for (let i = 0; i < 3; i++) {
417
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
418
+ if (diff !== 0) {
419
+ return diff;
420
+ }
421
+ }
422
+ return 0;
423
+ }
424
+ function nodeVersions(loaded, slug) {
425
+ return loaded.nodes.filter((n) => n.description.slug === slug).map((n) => n.description.version).sort((a, b) => compareSemver(b, a));
426
+ }
427
+ function findNode(loaded, slug, version) {
428
+ const matches = loaded.nodes.filter((n) => n.description.slug === slug);
429
+ if (matches.length === 0) {
430
+ throw new DevApiError(404, `Node '${slug}' not found.`);
431
+ }
432
+ if (!version || version === "latest") {
433
+ return [...matches].sort((a, b) => compareSemver(b.description.version, a.description.version))[0];
434
+ }
435
+ const exact = matches.find((n) => n.description.version === version);
436
+ if (!exact) {
437
+ throw new DevApiError(404, `Node '${slug}' has no version '${version}'.`);
438
+ }
439
+ return exact;
440
+ }
441
+ function findCredential(loaded, slug) {
442
+ const cred = loaded.credentials.find((c) => c.description.slug === slug);
443
+ if (!cred) {
444
+ throw new DevApiError(404, `Credential type '${slug}' not found.`);
445
+ }
446
+ return cred;
447
+ }
448
+ function findCredentialType(loaded, slug) {
449
+ return findCredential(loaded, slug).description;
450
+ }
451
+ function credentialContext(store, credentialId) {
452
+ return {
453
+ signal: new AbortController().signal,
454
+ logger: noopLogger,
455
+ persistDurableCreds: credentialId ? async (durableCreds) => {
456
+ store.updateCredential(credentialId, { durableCreds });
457
+ } : void 0
458
+ };
459
+ }
460
+ async function resolveCredentialInstance(loaded, store, credentialId) {
461
+ const instance = store.getCredential(credentialId);
462
+ if (!instance) {
463
+ throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);
464
+ }
465
+ const cred = findCredential(loaded, instance.credentialTypeSlug);
466
+ const ctx = credentialContext(store, credentialId);
467
+ return cred.resolve(ctx, instance.config, instance.durableCreds);
468
+ }
469
+ function authorContext(loaded, store, config, locale) {
470
+ return {
471
+ signal: new AbortController().signal,
472
+ logger: noopLogger,
473
+ config,
474
+ secrets: {
475
+ async get(key) {
476
+ const secret = store.getSecret(key);
477
+ if (!secret) {
478
+ throw new DevApiError(404, `Secret '${key}' not found.`);
479
+ }
480
+ return secret.value;
481
+ }
482
+ },
483
+ credentials: {
484
+ async get(id) {
485
+ return (await resolveCredentialInstance(loaded, store, id)).credentials;
486
+ }
487
+ },
488
+ locale
489
+ };
490
+ }
491
+ async function resolveNodeConfig(loaded, store, input) {
492
+ const node = findNode(loaded, input.slug, input.version);
493
+ const ctx = authorContext(loaded, store, input.config ?? {}, input.locale);
494
+ try {
495
+ if (input.target === "outputs") {
496
+ if (!node.resolveOutputs) {
497
+ return { outputs: [] };
498
+ }
499
+ return { outputs: await node.resolveOutputs(ctx) };
500
+ }
501
+ if (input.target === "*") {
502
+ const result = {};
503
+ if (node.resolveConfigSchema) {
504
+ result.fields = await node.resolveConfigSchema(ctx);
505
+ }
506
+ if (node.resolveOutputs) {
507
+ result.outputs = await node.resolveOutputs(ctx);
508
+ }
509
+ return result;
510
+ }
511
+ const field = node.description.config?.find((f) => f.key === input.target);
512
+ if (field?.type === "dynamic-schema") {
513
+ if (!node.resolveConfigSchema) {
514
+ return { fields: [] };
515
+ }
516
+ return { fields: await node.resolveConfigSchema(ctx) };
517
+ }
518
+ if (!node.loadOptions) {
519
+ return { options: [] };
520
+ }
521
+ return { options: await node.loadOptions(ctx, input.target) };
522
+ } catch (err) {
523
+ if (err instanceof DevApiError) {
524
+ throw err;
525
+ }
526
+ throw new DevApiError(502, `Node resolve failed: ${err.message}`);
527
+ }
528
+ }
529
+ function isProvided(value) {
530
+ if (value === void 0 || value === null) {
531
+ return false;
532
+ }
533
+ if (typeof value === "string") {
534
+ return value.trim().length > 0;
535
+ }
536
+ if (Array.isArray(value)) {
537
+ return value.length > 0;
538
+ }
539
+ return true;
540
+ }
541
+ function isExpression(value) {
542
+ return typeof value === "string" && (value.startsWith("=") || value.includes("${{"));
543
+ }
544
+ function validateField(field, value, errors) {
545
+ const push = (msg) => {
546
+ (errors[field.key] ??= []).push(msg);
547
+ };
548
+ const provided = isProvided(value);
549
+ if (field.required && !provided) {
550
+ push("This field is required.");
551
+ return;
552
+ }
553
+ if (!provided || isExpression(value)) {
554
+ return;
555
+ }
556
+ switch (field.type) {
557
+ case "string":
558
+ case "secret-ref":
559
+ case "expression":
560
+ if (typeof value !== "string") {
561
+ push("Expected a string.");
562
+ }
563
+ break;
564
+ case "number":
565
+ if (typeof value !== "number" || Number.isNaN(value)) {
566
+ push("Expected a number.");
567
+ }
568
+ break;
569
+ case "boolean":
570
+ if (typeof value !== "boolean") {
571
+ push("Expected a boolean.");
572
+ }
573
+ break;
574
+ case "select":
575
+ if (!field.dynamic && field.options && !field.options.some((o) => o.value === value)) {
576
+ push("Not one of the allowed options.");
577
+ }
578
+ break;
579
+ case "multiselect":
580
+ if (!Array.isArray(value)) {
581
+ push("Expected an array.");
582
+ } else if (!field.dynamic && field.options) {
583
+ const allowed = new Set(field.options.map((o) => o.value));
584
+ for (const v2 of value) {
585
+ if (!allowed.has(v2)) {
586
+ push(`Value '${String(v2)}' is not an allowed option.`);
587
+ }
588
+ }
589
+ }
590
+ break;
591
+ case "array":
592
+ if (!Array.isArray(value)) {
593
+ push("Expected an array.");
594
+ }
595
+ break;
596
+ case "object":
597
+ if (typeof value !== "object" || Array.isArray(value)) {
598
+ push("Expected an object.");
599
+ }
600
+ break;
601
+ }
602
+ const v = field.validation;
603
+ if (v) {
604
+ if (typeof value === "string") {
605
+ if (v.pattern !== void 0 && !new RegExp(v.pattern).test(value)) {
606
+ push(`Does not match pattern ${v.pattern}.`);
607
+ }
608
+ if (v.minLength !== void 0 && value.length < v.minLength) {
609
+ push(`Must be at least ${v.minLength} characters.`);
610
+ }
611
+ if (v.maxLength !== void 0 && value.length > v.maxLength) {
612
+ push(`Must be at most ${v.maxLength} characters.`);
613
+ }
614
+ }
615
+ if (typeof value === "number") {
616
+ if (v.min !== void 0 && value < v.min) {
617
+ push(`Must be >= ${v.min}.`);
618
+ }
619
+ if (v.max !== void 0 && value > v.max) {
620
+ push(`Must be <= ${v.max}.`);
621
+ }
622
+ }
623
+ if (Array.isArray(value)) {
624
+ if (v.minLength !== void 0 && value.length < v.minLength) {
625
+ push(`Must have at least ${v.minLength} items.`);
626
+ }
627
+ if (v.maxLength !== void 0 && value.length > v.maxLength) {
628
+ push(`Must have at most ${v.maxLength} items.`);
629
+ }
630
+ }
631
+ }
632
+ }
633
+ async function validateNodeConfig(loaded, store, input) {
634
+ const node = findNode(loaded, input.slug, input.version);
635
+ const config = input.config ?? {};
636
+ const errors = {};
637
+ const fields = node.description.config ?? [];
638
+ for (const field of fields) {
639
+ if (field.type === "dynamic-schema") {
640
+ continue;
641
+ }
642
+ validateField(field, config[field.key], errors);
643
+ }
644
+ if (fields.some((f) => f.type === "dynamic-schema") && node.resolveConfigSchema) {
645
+ const ctx = authorContext(loaded, store, config, input.locale);
646
+ let children;
647
+ try {
648
+ children = await node.resolveConfigSchema(ctx);
649
+ } catch (err) {
650
+ if (err instanceof DevApiError) {
651
+ throw err;
652
+ }
653
+ throw new DevApiError(502, `Node resolve failed: ${err.message}`);
654
+ }
655
+ for (const child of children) {
656
+ validateField(child, config[child.key], errors);
657
+ }
658
+ }
659
+ return { valid: Object.keys(errors).length === 0, errors };
660
+ }
661
+ async function testCredentialConfig(loaded, store, typeSlug, config) {
662
+ const cred = findCredential(loaded, typeSlug);
663
+ return cred.test(credentialContext(store), config);
664
+ }
665
+ async function testCredentialInstance(loaded, store, credentialId) {
666
+ const instance = store.getCredential(credentialId);
667
+ if (!instance) {
668
+ throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);
669
+ }
670
+ const cred = findCredential(loaded, instance.credentialTypeSlug);
671
+ return cred.test(credentialContext(store, credentialId), instance.config);
672
+ }
673
+ async function buildOAuthAuthorizeUrl(loaded, store, credentialId, params) {
674
+ const instance = store.getCredential(credentialId);
675
+ if (!instance) {
676
+ throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);
677
+ }
678
+ const cred = findCredential(loaded, instance.credentialTypeSlug);
679
+ if (!(0, import_integrations_node_sdk2.isOAuthAuthorizeCredential)(cred)) {
680
+ throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);
681
+ }
682
+ return cred.buildAuthorizeUrl(credentialContext(store, credentialId), instance.config, params);
683
+ }
684
+ async function exchangeOAuthCode(loaded, store, credentialId, params) {
685
+ const instance = store.getCredential(credentialId);
686
+ if (!instance) {
687
+ throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);
688
+ }
689
+ const cred = findCredential(loaded, instance.credentialTypeSlug);
690
+ if (!(0, import_integrations_node_sdk2.isOAuthAuthorizeCredential)(cred)) {
691
+ throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);
692
+ }
693
+ const out = await cred.exchangeCode(credentialContext(store, credentialId), instance.config, params);
694
+ store.updateCredential(credentialId, { durableCreds: out.durableCreds, status: "active" });
695
+ return out;
696
+ }
697
+
698
+ // src/server.ts
699
+ var import_node_http = __toESM(require("http"), 1);
700
+
701
+ // src/http.ts
702
+ function sendJson(res, status, body) {
703
+ const payload = JSON.stringify(body);
704
+ res.writeHead(status, {
705
+ "Content-Type": "application/json",
706
+ "Access-Control-Allow-Origin": "*",
707
+ "Access-Control-Allow-Headers": "*",
708
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
709
+ });
710
+ res.end(payload);
711
+ }
712
+ function sendError(res, err) {
713
+ if (err instanceof DevApiError) {
714
+ sendJson(res, err.status, err.errors ? { message: err.message, errors: err.errors } : { message: err.message });
715
+ return;
716
+ }
717
+ sendJson(res, 500, { message: err?.message ?? "Internal error" });
718
+ }
719
+ async function readBody(req) {
720
+ let body = "";
721
+ for await (const chunk of req) {
722
+ body += chunk;
723
+ }
724
+ return body;
725
+ }
726
+ async function readJson(req) {
727
+ const raw = await readBody(req);
728
+ if (raw.trim() === "") {
729
+ return {};
730
+ }
731
+ try {
732
+ return JSON.parse(raw);
733
+ } catch {
734
+ throw new DevApiError(400, "Invalid JSON body.");
735
+ }
736
+ }
737
+
738
+ // src/projections.ts
739
+ var import_integrations_node_sdk3 = require("@revenexx/integrations-node-sdk");
740
+ function hasDynamicOptions(desc) {
741
+ return (desc.config ?? []).some((f) => f.dynamic === true);
742
+ }
743
+ function hasDynamicSchema(desc) {
744
+ return (desc.config ?? []).some((f) => f.type === "dynamic-schema");
745
+ }
746
+ function hasDynamicOutputs(desc) {
747
+ return (desc.outputs ?? []).some((o) => o.resolveOutputs === true);
748
+ }
749
+ function nodeToApi(desc) {
750
+ const [namespace] = desc.slug.split(":");
751
+ return {
752
+ name: desc.name,
753
+ namespace: namespace ?? null,
754
+ slug: desc.slug,
755
+ version: desc.version,
756
+ manifest_version: import_integrations_node_sdk3.MANIFEST_VERSION,
757
+ manifest: desc,
758
+ has_dynamic_options: hasDynamicOptions(desc),
759
+ has_dynamic_schema: hasDynamicSchema(desc),
760
+ has_dynamic_outputs: hasDynamicOutputs(desc),
761
+ created_at: null,
762
+ updated_at: null
763
+ };
764
+ }
765
+ function credentialTypeToApi(desc) {
766
+ return {
767
+ slug: desc.slug,
768
+ version: desc.version,
769
+ name: desc.name,
770
+ description: desc.description ?? null,
771
+ icon: desc.icon ?? null,
772
+ auth_kind: desc.authKind,
773
+ fields: desc.fields
774
+ };
775
+ }
776
+ function credentialInstanceToApi(record, type) {
777
+ const secretKeys = new Set((type?.fields ?? []).filter((f) => f.type === "secret").map((f) => f.key));
778
+ const knownKeys = new Set((type?.fields ?? []).map((f) => f.key));
779
+ const publicConfig = {};
780
+ for (const [key, value] of Object.entries(record.config)) {
781
+ if (knownKeys.has(key) && !secretKeys.has(key)) {
782
+ publicConfig[key] = value;
783
+ }
784
+ }
785
+ return {
786
+ id: record.id,
787
+ tenant_id: record.tenantId,
788
+ credential_type_slug: record.credentialTypeSlug,
789
+ name: record.name,
790
+ status: record.status,
791
+ public_config: publicConfig,
792
+ created_at: record.createdAt,
793
+ updated_at: record.updatedAt
794
+ };
795
+ }
796
+ function secretToApi(record) {
797
+ return {
798
+ key: record.key,
799
+ created_at: record.createdAt,
800
+ updated_at: record.updatedAt
801
+ };
802
+ }
803
+ function workflowToApi(record) {
804
+ return {
805
+ id: record.id,
806
+ name: record.name,
807
+ definition: record.definition,
808
+ build_status: record.buildStatus,
809
+ created_at: record.createdAt,
810
+ updated_at: record.updatedAt
811
+ };
812
+ }
813
+ function triggerToApi(record) {
814
+ return {
815
+ handle: record.id,
816
+ id: record.id,
817
+ workflow_id: record.workflowId,
818
+ type: record.type,
819
+ name: record.name,
820
+ config: record.config,
821
+ active: record.active,
822
+ created_at: record.createdAt,
823
+ updated_at: record.updatedAt
824
+ };
825
+ }
826
+ function templateSummaryToApi(t) {
827
+ return {
828
+ slug: t.slug,
829
+ version: t.version,
830
+ category: t.category,
831
+ level: t.level,
832
+ name: t.name,
833
+ shortDescription: t.shortDescription ?? null,
834
+ description: t.description ?? null,
835
+ icon: t.icon ?? null,
836
+ industries: t.industries ?? [],
837
+ vendors: t.vendors ?? [],
838
+ triggerTypes: (t.triggers ?? []).map((tr) => tr.type)
839
+ };
840
+ }
841
+ function templateFullToApi(t) {
842
+ return {
843
+ ...templateSummaryToApi(t),
844
+ blobVersion: t.blobVersion,
845
+ definition: t.definition,
846
+ triggers: t.triggers ?? []
847
+ };
848
+ }
849
+
850
+ // src/server.ts
851
+ var SEGMENT = (s) => decodeURIComponent(s ?? "");
852
+ function createRequestListener(deps) {
853
+ return (req, res) => {
854
+ handle(req, res, deps).catch((err) => sendError(res, err));
855
+ };
856
+ }
857
+ async function handle(req, res, deps) {
858
+ const method = (req.method ?? "GET").toUpperCase();
859
+ if (method === "OPTIONS") {
860
+ sendJson(res, 204, {});
861
+ return;
862
+ }
863
+ const url = new URL(req.url ?? "/", "http://localhost");
864
+ let pathname = url.pathname;
865
+ if (pathname.startsWith("/api/v1")) {
866
+ pathname = pathname.slice("/api/v1".length);
867
+ }
868
+ const seg = pathname.split("/").filter(Boolean).map(SEGMENT);
869
+ const loaded = deps.getPackage();
870
+ const store = deps.store;
871
+ switch (seg[0]) {
872
+ case void 0:
873
+ case "health":
874
+ return void sendJson(res, 200, { status: "ok" });
875
+ case "me":
876
+ return void sendJson(res, 200, {
877
+ id: "dev-user",
878
+ name: "Dev User",
879
+ email: "dev@revenexx.test",
880
+ tenant_id: DEV_TENANT_ID
881
+ });
882
+ case "schemas":
883
+ return handleSchemas(res, deps, seg);
884
+ case "nodes":
885
+ return handleNodes(req, res, method, loaded, store, seg);
886
+ case "credential-types":
887
+ return handleCredentialTypes(res, loaded, seg);
888
+ case "credentials":
889
+ return handleCredentials(req, res, method, loaded, store, seg, url);
890
+ case "secrets":
891
+ return handleSecrets(req, res, method, store, seg);
892
+ case "templates":
893
+ return handleTemplates(req, res, method, loaded, store, seg);
894
+ case "workflows":
895
+ return handleWorkflows(req, res, method, store, seg);
896
+ default:
897
+ return void sendJson(res, 404, { message: `No route for /${seg.join("/")}` });
898
+ }
899
+ }
900
+ function handleSchemas(res, deps, seg) {
901
+ const domain = seg[1];
902
+ const version = seg[2];
903
+ if (!domain) {
904
+ throw new DevApiError(404, "Schema domain required.");
905
+ }
906
+ const schemas = deps.schemas ?? {};
907
+ const schema = version && schemas[`${domain}/${version}`] || schemas[domain];
908
+ if (!schema) {
909
+ throw new DevApiError(404, `No schema for '${domain}${version ? `/${version}` : ""}'. Vendor it into assets/schemas.`);
910
+ }
911
+ sendJson(res, 200, schema);
912
+ }
913
+ async function handleNodes(req, res, method, loaded, store, seg) {
914
+ if (seg.length === 1 && method === "GET") {
915
+ return void sendJson(res, 200, { data: loaded.manifest.nodes.map(nodeToApi) });
916
+ }
917
+ const slug = seg[1];
918
+ if (!slug) {
919
+ throw new DevApiError(404, "Node slug required.");
920
+ }
921
+ if (seg[2] === "versions" && method === "GET") {
922
+ const versions = nodeVersions(loaded, slug);
923
+ if (versions.length === 0) {
924
+ throw new DevApiError(404, `Node '${slug}' not found.`);
925
+ }
926
+ return void sendJson(res, 200, { data: versions });
927
+ }
928
+ const version = seg[2];
929
+ if (!version) {
930
+ throw new DevApiError(404, "Node version required.");
931
+ }
932
+ if (seg[3] === "config:resolve" && method === "POST") {
933
+ const body = await readJson(req);
934
+ if (!body.target) {
935
+ throw new DevApiError(422, "Field `target` is required.", { target: ["The target field is required."] });
936
+ }
937
+ const result = await resolveNodeConfig(loaded, store, {
938
+ slug,
939
+ version,
940
+ target: body.target,
941
+ config: body.config ?? {},
942
+ locale: body.locale
943
+ });
944
+ return void sendJson(res, 200, result);
945
+ }
946
+ if (seg[3] === "config:validate" && method === "POST") {
947
+ const body = await readJson(req);
948
+ const result = await validateNodeConfig(loaded, store, {
949
+ slug,
950
+ version,
951
+ config: body.config ?? {},
952
+ locale: body.locale
953
+ });
954
+ return void sendJson(res, 200, result);
955
+ }
956
+ if (seg.length === 3 && method === "GET") {
957
+ const node = loaded.manifest.nodes.find((n) => n.slug === slug && (version === "latest" || n.version === version));
958
+ if (!node) {
959
+ throw new DevApiError(404, `Node '${slug}@${version}' not found.`);
960
+ }
961
+ return void sendJson(res, 200, nodeToApi(node));
962
+ }
963
+ throw new DevApiError(404, `No route for nodes/${seg.slice(1).join("/")}`);
964
+ }
965
+ function handleCredentialTypes(res, loaded, seg) {
966
+ if (seg.length === 1) {
967
+ return void sendJson(res, 200, {
968
+ data: (loaded.manifest.credentials ?? []).map(credentialTypeToApi)
969
+ });
970
+ }
971
+ const slug = seg[1];
972
+ const type = findCredentialType(loaded, slug);
973
+ sendJson(res, 200, { data: credentialTypeToApi(type) });
974
+ }
975
+ async function handleCredentials(req, res, method, loaded, store, seg, url) {
976
+ const typeOf = (slug) => {
977
+ try {
978
+ return findCredentialType(loaded, slug);
979
+ } catch {
980
+ return void 0;
981
+ }
982
+ };
983
+ if (seg.length === 1) {
984
+ if (method === "GET") {
985
+ const filter = url.searchParams.get("type") ?? void 0;
986
+ const data = store.listCredentials(filter).map((c) => credentialInstanceToApi(c, typeOf(c.credentialTypeSlug)));
987
+ return void sendJson(res, 200, { data });
988
+ }
989
+ if (method === "POST") {
990
+ const body = await readJson(req);
991
+ if (!body.credential_type_slug || !body.name) {
992
+ throw new DevApiError(422, "Fields `credential_type_slug` and `name` are required.");
993
+ }
994
+ findCredential(loaded, body.credential_type_slug);
995
+ const record = store.createCredential({
996
+ credentialTypeSlug: body.credential_type_slug,
997
+ name: body.name,
998
+ config: body.config ?? {}
999
+ });
1000
+ return void sendJson(res, 201, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));
1001
+ }
1002
+ }
1003
+ if (seg[1] === "test" && method === "POST") {
1004
+ const body = await readJson(req);
1005
+ if (!body.credential_type_slug) {
1006
+ throw new DevApiError(422, "Field `credential_type_slug` is required.");
1007
+ }
1008
+ const result = await testCredentialConfig(loaded, store, body.credential_type_slug, body.config ?? {});
1009
+ return void sendJson(res, 200, result);
1010
+ }
1011
+ if (seg[1] === "oauth" && seg[2] === "callback" && method === "GET") {
1012
+ const code = url.searchParams.get("code");
1013
+ const state = url.searchParams.get("state");
1014
+ if (!code || !state) {
1015
+ throw new DevApiError(422, "OAuth callback requires `code` and `state`.");
1016
+ }
1017
+ const credentialId = state;
1018
+ const redirectUri = `${url.origin}/api/v1/credentials/oauth/callback`;
1019
+ await exchangeOAuthCode(loaded, store, credentialId, { code, redirectUri });
1020
+ return void sendJson(res, 200, { status: "connected", credential_id: credentialId });
1021
+ }
1022
+ const id = seg[1];
1023
+ if (!id) {
1024
+ throw new DevApiError(404, "Credential id required.");
1025
+ }
1026
+ if (seg[2] === "test" && method === "POST") {
1027
+ const result = await testCredentialInstance(loaded, store, id);
1028
+ return void sendJson(res, 200, result);
1029
+ }
1030
+ if (seg[2] === "oauth" && seg[3] === "authorize-url" && method === "POST") {
1031
+ const redirectUri = "http://localhost/api/v1/credentials/oauth/callback";
1032
+ const result = await buildOAuthAuthorizeUrl(loaded, store, id, { redirectUri, state: id });
1033
+ return void sendJson(res, 200, { authorize_url: result.authorizeUrl });
1034
+ }
1035
+ if (seg.length === 2) {
1036
+ const record = store.getCredential(id);
1037
+ if (method === "GET") {
1038
+ if (!record) {
1039
+ throw new DevApiError(404, `Credential '${id}' not found.`);
1040
+ }
1041
+ return void sendJson(res, 200, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));
1042
+ }
1043
+ if (method === "PATCH") {
1044
+ if (!record) {
1045
+ throw new DevApiError(404, `Credential '${id}' not found.`);
1046
+ }
1047
+ const body = await readJson(req);
1048
+ const updated = store.updateCredential(id, { name: body.name, config: body.config });
1049
+ return void sendJson(res, 200, credentialInstanceToApi(updated, typeOf(updated.credentialTypeSlug)));
1050
+ }
1051
+ if (method === "DELETE") {
1052
+ store.deleteCredential(id);
1053
+ return void sendJson(res, 200, { deleted: true });
1054
+ }
1055
+ }
1056
+ throw new DevApiError(404, `No route for credentials/${seg.slice(1).join("/")}`);
1057
+ }
1058
+ async function handleSecrets(req, res, method, store, seg) {
1059
+ if (seg.length === 1) {
1060
+ if (method === "GET") {
1061
+ return void sendJson(res, 200, { data: store.listSecrets().map(secretToApi) });
1062
+ }
1063
+ if (method === "POST") {
1064
+ const body = await readJson(req);
1065
+ if (!body.key || body.value === void 0) {
1066
+ throw new DevApiError(422, "Fields `key` and `value` are required.");
1067
+ }
1068
+ const record = store.setSecret(body.key, body.value);
1069
+ return void sendJson(res, 201, secretToApi(record));
1070
+ }
1071
+ }
1072
+ const key = seg[1];
1073
+ if (key) {
1074
+ if (method === "PATCH") {
1075
+ const body = await readJson(req);
1076
+ if (body.value === void 0) {
1077
+ throw new DevApiError(422, "Field `value` is required.");
1078
+ }
1079
+ return void sendJson(res, 200, secretToApi(store.setSecret(key, body.value)));
1080
+ }
1081
+ if (method === "DELETE") {
1082
+ store.deleteSecret(key);
1083
+ return void sendJson(res, 200, { deleted: true });
1084
+ }
1085
+ }
1086
+ throw new DevApiError(404, `No route for secrets/${seg.slice(1).join("/")}`);
1087
+ }
1088
+ async function handleTemplates(req, res, method, loaded, store, seg) {
1089
+ const templates = loaded.manifest.templates ?? [];
1090
+ if (seg.length === 1 && method === "GET") {
1091
+ return void sendJson(res, 200, { data: templates.map(templateSummaryToApi) });
1092
+ }
1093
+ const slug = seg[1];
1094
+ const template = templates.find((t) => t.slug === slug);
1095
+ if (!template) {
1096
+ throw new DevApiError(404, `Template '${slug}' not found.`);
1097
+ }
1098
+ if (seg.length === 2 && method === "GET") {
1099
+ return void sendJson(res, 200, templateFullToApi(template));
1100
+ }
1101
+ if (seg[2] === "requirements" && method === "GET") {
1102
+ return void sendJson(res, 200, { data: { credentials: [], secrets: [] } });
1103
+ }
1104
+ if (seg[2] === "instantiate" && method === "POST") {
1105
+ const body = await readJson(req);
1106
+ const workflow = store.createWorkflow({
1107
+ name: body.name ?? String(template.name),
1108
+ definition: template.definition
1109
+ });
1110
+ for (const trigger of template.triggers ?? []) {
1111
+ store.createTrigger({
1112
+ workflowId: workflow.id,
1113
+ type: trigger.type,
1114
+ name: trigger.name ?? null,
1115
+ config: trigger.config ?? {},
1116
+ active: trigger.active ?? true,
1117
+ id: trigger.handle
1118
+ });
1119
+ }
1120
+ return void sendJson(res, 201, workflowToApi(workflow));
1121
+ }
1122
+ throw new DevApiError(404, `No route for templates/${seg.slice(1).join("/")}`);
1123
+ }
1124
+ async function handleWorkflows(req, res, method, store, seg) {
1125
+ if (seg.length === 1) {
1126
+ if (method === "GET") {
1127
+ return void sendJson(res, 200, { data: store.listWorkflows().map(workflowToApi) });
1128
+ }
1129
+ if (method === "POST") {
1130
+ const body = await readJson(req);
1131
+ const workflow = store.createWorkflow({
1132
+ name: body.name ?? "Untitled workflow",
1133
+ definition: body.definition ?? {}
1134
+ });
1135
+ return void sendJson(res, 201, workflowToApi(workflow));
1136
+ }
1137
+ }
1138
+ if (seg[1] === "used-credentials" && method === "GET") {
1139
+ return void sendJson(res, 200, { data: [] });
1140
+ }
1141
+ if (seg[1] === "used-credential-types" && method === "GET") {
1142
+ return void sendJson(res, 200, { data: [] });
1143
+ }
1144
+ const id = Number.parseInt(seg[1] ?? "", 10);
1145
+ if (Number.isNaN(id)) {
1146
+ throw new DevApiError(404, `No route for workflows/${seg.slice(1).join("/")}`);
1147
+ }
1148
+ if (seg[2] === "triggers") {
1149
+ if (seg.length === 3 && method === "GET") {
1150
+ return void sendJson(res, 200, { data: store.listTriggers(id).map(triggerToApi) });
1151
+ }
1152
+ if (seg.length === 3 && method === "POST") {
1153
+ const body = await readJson(req);
1154
+ if (!body.type) {
1155
+ throw new DevApiError(422, "Field `type` is required.");
1156
+ }
1157
+ const trigger = store.createTrigger({ workflowId: id, type: body.type, name: body.name, config: body.config, active: body.active });
1158
+ return void sendJson(res, 201, triggerToApi(trigger));
1159
+ }
1160
+ const triggerId = seg[3];
1161
+ if (triggerId && method === "PUT") {
1162
+ const body = await readJson(req);
1163
+ if (!body.type) {
1164
+ throw new DevApiError(422, "Field `type` is required.");
1165
+ }
1166
+ const trigger = store.replaceTrigger(triggerId, { type: body.type, name: body.name, config: body.config, active: body.active });
1167
+ if (!trigger) {
1168
+ throw new DevApiError(404, `Trigger '${triggerId}' not found.`);
1169
+ }
1170
+ return void sendJson(res, 200, triggerToApi(trigger));
1171
+ }
1172
+ if (triggerId && method === "DELETE") {
1173
+ store.deleteTrigger(triggerId);
1174
+ return void sendJson(res, 200, { deleted: true });
1175
+ }
1176
+ }
1177
+ if (seg.length === 2) {
1178
+ const record = store.getWorkflow(id);
1179
+ if (method === "GET") {
1180
+ if (!record) {
1181
+ throw new DevApiError(404, `Workflow '${id}' not found.`);
1182
+ }
1183
+ return void sendJson(res, 200, workflowToApi(record));
1184
+ }
1185
+ if (method === "PUT") {
1186
+ const body = await readJson(req);
1187
+ const updated = store.updateWorkflow(id, { name: body.name, definition: body.definition });
1188
+ if (!updated) {
1189
+ throw new DevApiError(404, `Workflow '${id}' not found.`);
1190
+ }
1191
+ return void sendJson(res, 200, workflowToApi(updated));
1192
+ }
1193
+ if (method === "DELETE") {
1194
+ store.deleteWorkflow(id);
1195
+ return void sendJson(res, 200, { deleted: true });
1196
+ }
1197
+ }
1198
+ if ((seg[2] === "credentials" || seg[2] === "credential-types") && method === "GET") {
1199
+ return void sendJson(res, 200, { data: [] });
1200
+ }
1201
+ throw new DevApiError(404, `No route for workflows/${seg.slice(1).join("/")}`);
1202
+ }
1203
+
1204
+ // src/index.ts
1205
+ var DEVKIT_VERSION = "0.1.0";
1206
+
1207
+ // src/preview/scaffold.ts
1208
+ var import_node_fs2 = require("fs");
1209
+ var import_node_path2 = require("path");
1210
+
1211
+ // src/preview/templates.ts
1212
+ var VERSIONS = {
1213
+ nuxt: "^4.0.0",
1214
+ vue: "^3.5.0",
1215
+ studio: "^0.1.3",
1216
+ studioShared: "^0.2.0",
1217
+ studioIntegrations: "^0.5.1",
1218
+ vueFlowCore: "^1.48.2",
1219
+ vueFlowBackground: "^1.3.2",
1220
+ vueFlowControls: "^1.1.3",
1221
+ vueFlowMinimap: "^1.5.4",
1222
+ vueFlowNodeToolbar: "^1.1.1",
1223
+ dagre: "^3.0.0",
1224
+ lucide: "^1.0.0",
1225
+ solarIcons: "^1.2.1",
1226
+ // studio-integrations 0.5.x embeds a TipTap rich-text editor and vue-sonner toasts.
1227
+ tiptap: "^3.28.0",
1228
+ vueSonner: "^2.0.0",
1229
+ tailwindVite: "^4.0.0",
1230
+ tailwind: "^4.0.0"
1231
+ };
1232
+ var PACKAGE_JSON = `{
1233
+ "name": "integrations-preview-host",
1234
+ "private": true,
1235
+ "type": "module",
1236
+ "scripts": {
1237
+ "dev": "nuxt dev",
1238
+ "build": "nuxt build"
1239
+ },
1240
+ "dependencies": {
1241
+ "@revenexx/studio": "${VERSIONS.studio}",
1242
+ "@revenexx/studio-integrations": "${VERSIONS.studioIntegrations}",
1243
+ "@revenexx/studio-shared": "${VERSIONS.studioShared}",
1244
+ "@solar-icons/nuxt": "${VERSIONS.solarIcons}",
1245
+ "@dagrejs/dagre": "${VERSIONS.dagre}",
1246
+ "@tiptap/core": "${VERSIONS.tiptap}",
1247
+ "@tiptap/extension-document": "${VERSIONS.tiptap}",
1248
+ "@tiptap/extension-history": "${VERSIONS.tiptap}",
1249
+ "@tiptap/extension-paragraph": "${VERSIONS.tiptap}",
1250
+ "@tiptap/extension-text": "${VERSIONS.tiptap}",
1251
+ "@tiptap/pm": "${VERSIONS.tiptap}",
1252
+ "@tiptap/vue-3": "${VERSIONS.tiptap}",
1253
+ "@vue-flow/background": "${VERSIONS.vueFlowBackground}",
1254
+ "@vue-flow/controls": "${VERSIONS.vueFlowControls}",
1255
+ "@vue-flow/core": "${VERSIONS.vueFlowCore}",
1256
+ "@vue-flow/minimap": "${VERSIONS.vueFlowMinimap}",
1257
+ "@vue-flow/node-toolbar": "${VERSIONS.vueFlowNodeToolbar}",
1258
+ "lucide-vue-next": "${VERSIONS.lucide}",
1259
+ "nuxt": "${VERSIONS.nuxt}",
1260
+ "vue": "${VERSIONS.vue}",
1261
+ "vue-sonner": "${VERSIONS.vueSonner}"
1262
+ },
1263
+ "devDependencies": {
1264
+ "@tailwindcss/vite": "${VERSIONS.tailwindVite}",
1265
+ "tailwindcss": "${VERSIONS.tailwind}"
1266
+ }
1267
+ }
1268
+ `;
1269
+ var NUXT_CONFIG = `import tailwindcss from '@tailwindcss/vite';
1270
+
1271
+ // Minimal preview host for local integration-node development.
1272
+ // Generated by \`integrations-devkit init-preview\` \u2014 safe to edit or delete
1273
+ // (it lives under the gitignored .revenexx-dev/).
1274
+ export default defineNuxtConfig({
1275
+ compatibilityDate: '2025-01-01',
1276
+ // SPA: no SSR, so the studio's browser-only composables (localStorage etc.)
1277
+ // behave exactly as in the real cockpit, and boot is fast.
1278
+ ssr: false,
1279
+ // studio-shared 0.2.x ships as a Nuxt MODULE (not a layer) \u2014 it must be
1280
+ // registered in 'modules', before studio-integrations which builds on it.
1281
+ // @solar-icons/nuxt provides the #solar-icons alias the studio components import.
1282
+ modules: ['@revenexx/studio-shared', '@solar-icons/nuxt', '@revenexx/studio-integrations'],
1283
+ css: ['~/assets/css/main.css'],
1284
+ vite: { plugins: [tailwindcss()] },
1285
+ runtimeConfig: {
1286
+ public: {
1287
+ // Overridden at runtime by NUXT_PUBLIC_* env (see .env / the preview command).
1288
+ integrationsApi: '',
1289
+ devToken: '',
1290
+ devTenant: '',
1291
+ },
1292
+ },
1293
+ });
1294
+ `;
1295
+ var MAIN_CSS = `@import "tailwindcss";
1296
+ @import "@revenexx/studio/tokens";
1297
+ @import "@revenexx/studio/fonts";
1298
+
1299
+ @source "../../node_modules/@revenexx/studio/dist";
1300
+ @source "../../node_modules/@revenexx/studio-shared/components";
1301
+ @source "../../node_modules/@revenexx/studio-integrations/dist/runtime";
1302
+
1303
+ /* Phase 1: workflow EXECUTION is not wired up in the devkit preview yet, so the
1304
+ Workflows surface is hidden until phase 2. This hides the sidebar nav entry
1305
+ and any deep links to the workflow editor; the routes are also redirected by
1306
+ middleware/hide-workflows.global.ts. */
1307
+ a[href^="/integrations/workflows"] { display: none !important; }
1308
+ li:has(> a[href^="/integrations/workflows"]) { display: none !important; }
1309
+ `;
1310
+ var APP_VUE = `<script setup lang="ts">
1311
+ import { Toaster } from '@revenexx/studio'
1312
+
1313
+ useHead({ title: 'Integration Studio \u2014 devkit preview' })
1314
+ </script>
1315
+
1316
+ <template>
1317
+ <div class="flex h-svh flex-col overflow-hidden bg-[#f3f1fa] text-foreground">
1318
+ <NuxtLoadingIndicator color="var(--color-primary, #620DFF)" :height="3" />
1319
+ <div class="min-h-0 flex-1 pt-3">
1320
+ <NuxtPage />
1321
+ </div>
1322
+ <Toaster rich-colors position="bottom-right" :duration="3500" close-button />
1323
+ </div>
1324
+ </template>
1325
+ `;
1326
+ var INDEX_VUE = `<template>
1327
+ <div class="mx-auto flex min-h-full max-w-xl flex-col justify-center gap-6 px-6 py-12">
1328
+ <div>
1329
+ <p class="text-mono text-muted-foreground">Integrations \xB7 node devkit</p>
1330
+ <h1 class="mt-1 text-2xl font-medium">Integration Studio \u2014 Preview</h1>
1331
+ <p class="mt-2 text-sm text-muted-foreground">
1332
+ Lokaler Host f\xFCr <code>@revenexx/studio-integrations</code> gegen die Mock-API
1333
+ deines Node-Pakets. Authentifizierung ist ein festes Dev-Token \u2014 nichts einzugeben.
1334
+ </p>
1335
+ </div>
1336
+
1337
+ <div class="rounded-lg border border-black/[0.06] bg-card p-5 text-sm shadow-sm">
1338
+ <p class="text-mono text-muted-foreground">Session</p>
1339
+ <dl class="mt-2 grid grid-cols-[7rem_1fr] gap-y-1">
1340
+ <dt class="text-muted-foreground">Mock API</dt>
1341
+ <dd class="truncate font-mono text-xs leading-5">{{ api }}</dd>
1342
+ <dt class="text-muted-foreground">Tenant</dt>
1343
+ <dd class="font-mono text-xs leading-5">{{ tenant }}</dd>
1344
+ </dl>
1345
+ </div>
1346
+
1347
+ <div class="rounded-lg border border-black/[0.06] bg-card p-5 shadow-sm">
1348
+ <p class="text-mono text-muted-foreground">Einstieg</p>
1349
+ <div class="mt-3 flex flex-col gap-4">
1350
+ <NuxtLink
1351
+ to="/nodes"
1352
+ class="inline-flex w-fit items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90"
1353
+ >
1354
+ Lokale Nodes \xF6ffnen \u2014 Preview + Validierung
1355
+ </NuxtLink>
1356
+ <div class="flex flex-wrap gap-x-4 gap-y-1.5">
1357
+ <NuxtLink
1358
+ v-for="link in quickLinks"
1359
+ :key="link.to"
1360
+ :to="link.to"
1361
+ class="text-sm text-primary hover:underline"
1362
+ >
1363
+ {{ link.label }}
1364
+ </NuxtLink>
1365
+ </div>
1366
+ </div>
1367
+ </div>
1368
+ </div>
1369
+ </template>
1370
+
1371
+ <script setup lang="ts">
1372
+ const rc = useRuntimeConfig().public
1373
+ const api = rc.integrationsApi
1374
+ const tenant = (rc.devTenant as string) || 'dev-tenant'
1375
+
1376
+ const quickLinks = [
1377
+ { to: '/integrations', label: 'Overview' },
1378
+ { to: '/integrations/credentials', label: 'Credentials' },
1379
+ { to: '/integrations/secrets', label: 'Secrets' },
1380
+ { to: '/nodes', label: 'Local nodes' },
1381
+ ]
1382
+ </script>
1383
+ `;
1384
+ var NODES_VUE = `<template>
1385
+ <div class="ndx-page">
1386
+ <div class="ndx-inner">
1387
+ <header class="ndx-head">
1388
+ <h1>Lokale Nodes</h1>
1389
+ <p>Mock-API: <code>{{ apiUrl }}</code></p>
1390
+ <p v-if="loadError" class="ndx-err">{{ loadError }}</p>
1391
+ </header>
1392
+
1393
+ <p v-if="loading">Lade Nodes\u2026</p>
1394
+ <p v-else-if="nodes.length === 0">Keine Nodes gefunden. Exportiert dein Paket <code>NODES</code>?</p>
1395
+
1396
+ <ul v-else class="ndx-grid">
1397
+ <li v-for="n in nodes" :key="n.slug + '@' + n.version" class="ndx-card" @click="openNode(n)">
1398
+ <div class="ndx-card-title">{{ label(n) }}</div>
1399
+ <div class="ndx-card-slug">{{ n.slug }} \xB7 v{{ n.version }}</div>
1400
+ <div class="ndx-badges">
1401
+ <span v-if="n.has_dynamic_options" class="ndx-badge">dynamic options</span>
1402
+ <span v-if="n.has_dynamic_schema" class="ndx-badge">dynamic schema</span>
1403
+ <span v-if="n.has_dynamic_outputs" class="ndx-badge">dynamic outputs</span>
1404
+ </div>
1405
+ </li>
1406
+ </ul>
1407
+ </div>
1408
+
1409
+ <!-- REUSE of the exact editor lightbox: studio <Dialog> owns the modal
1410
+ chrome, <IntegrationsNodeInspector> is the content \u2014 mirrors
1411
+ WorkflowEditor.vue's <Dialog><DialogContent><NodeInspector/> block. -->
1412
+ <Dialog :open="!!selection" @update:open="(v) => { if (!v) requestClose() }">
1413
+ <DialogContent :show-close-button="false" class="flex h-[min(680px,86vh)] w-[min(1100px,94vw)] max-w-none flex-col gap-0 overflow-hidden rounded-lg p-0 sm:max-w-none">
1414
+ <div v-if="result === 'ok'" class="ndx-strip ndx-strip-ok">\u2713 Payload g\xFCltig \u2014 alles gut.</div>
1415
+ <div v-else-if="result === 'err'" class="ndx-strip ndx-strip-err">\u2717 Payload ung\xFCltig \u2014 {{ errorCount }} Feld(er) pr\xFCfen (rot markiert).</div>
1416
+ <div v-else-if="formError" class="ndx-strip ndx-strip-err">{{ formError }}</div>
1417
+ <IntegrationsNodeInspector
1418
+ v-if="selection"
1419
+ :selection="selection"
1420
+ :secret-keys="secretKeys"
1421
+ :refused-fields="refused"
1422
+ @update="onSubmit"
1423
+ @close="requestClose" />
1424
+ </DialogContent>
1425
+ </Dialog>
1426
+ </div>
1427
+ </template>
1428
+
1429
+ <script setup lang="ts">
1430
+ import { computed, onMounted, ref } from 'vue'
1431
+ import { Dialog, DialogContent } from '@revenexx/studio'
1432
+
1433
+ interface ApiNode {
1434
+ name: string | Record<string, string>
1435
+ slug: string
1436
+ version: string
1437
+ manifest?: { name?: string | Record<string, string> }
1438
+ has_dynamic_options?: boolean
1439
+ has_dynamic_schema?: boolean
1440
+ has_dynamic_outputs?: boolean
1441
+ }
1442
+
1443
+ const apiUrl = useRuntimeConfig().public.integrationsApi
1444
+ const client = useIntegrationsApi()
1445
+ // load() fills the reactive catalog the inspector reads via findManifest();
1446
+ // resolveLocalized() turns a LocalizedString into the active-locale string.
1447
+ const { load, resolveLocalized } = useIntegrationsNodes()
1448
+
1449
+ const nodes = ref<ApiNode[]>([])
1450
+ const loading = ref(true)
1451
+ const loadError = ref<string | null>(null)
1452
+
1453
+ const selection = ref<any>(null)
1454
+ const secretKeys = ref<string[]>([])
1455
+ const refused = ref<Record<string, string>>({})
1456
+ const result = ref<string | null>(null)
1457
+ const formError = ref<string | null>(null)
1458
+ // Set synchronously in onSubmit so the inspector's own Save (it emits update THEN
1459
+ // close) does NOT close the dialog \u2014 we keep it open to show the verdict.
1460
+ const validating = ref(false)
1461
+
1462
+ const errorCount = computed(() => Object.keys(refused.value).length)
1463
+
1464
+ function label(n: ApiNode): string {
1465
+ return resolveLocalized(n.manifest?.name ?? n.name) || n.slug
1466
+ }
1467
+
1468
+ onMounted(async () => {
1469
+ await load()
1470
+ try {
1471
+ const res = await client.get<any>('/nodes')
1472
+ nodes.value = (Array.isArray(res) ? res : res?.data ?? []) as ApiNode[]
1473
+ } catch (e: any) {
1474
+ loadError.value = e?.message ?? 'Nodes konnten nicht geladen werden.'
1475
+ } finally {
1476
+ loading.value = false
1477
+ }
1478
+ try {
1479
+ const secrets = await client.get<any>('/secrets')
1480
+ const list = (Array.isArray(secrets) ? secrets : secrets?.data ?? []) as Array<{ key: string }>
1481
+ secretKeys.value = list.map(s => s.key).filter(Boolean)
1482
+ } catch {
1483
+ // secrets are optional for the preview
1484
+ }
1485
+ })
1486
+
1487
+ function openNode(n: ApiNode) {
1488
+ refused.value = {}
1489
+ result.value = null
1490
+ formError.value = null
1491
+ // Synthetic WorkflowNode selection (distinguished by nodeSlug); the inspector
1492
+ // resolves its manifest from the catalog load() populated above.
1493
+ selection.value = { id: 'preview', nodeSlug: n.slug, nodeVersion: n.version, name: label(n), config: {} }
1494
+ }
1495
+
1496
+ async function onSubmit(draft: any) {
1497
+ validating.value = true
1498
+ refused.value = {}
1499
+ result.value = null
1500
+ formError.value = null
1501
+ try {
1502
+ const slug = encodeURIComponent(draft.nodeSlug)
1503
+ const version = encodeURIComponent(draft.nodeVersion || 'latest')
1504
+ const res = await client.post<any>(
1505
+ '/nodes/' + slug + '/' + version + '/config:validate',
1506
+ { config: draft.config ?? {} },
1507
+ )
1508
+ if (res.valid) {
1509
+ result.value = 'ok'
1510
+ } else {
1511
+ refused.value = Object.fromEntries(
1512
+ Object.entries(res.errors ?? {}).map(([k, msgs]) => [k, (msgs as string[]).join(' ')]),
1513
+ )
1514
+ result.value = 'err'
1515
+ }
1516
+ } catch (e: any) {
1517
+ formError.value = e?.message ?? 'Validierung fehlgeschlagen.'
1518
+ } finally {
1519
+ validating.value = false
1520
+ }
1521
+ }
1522
+
1523
+ // The inspector emits close on both Save and Cancel; the studio Dialog emits it
1524
+ // on Esc / backdrop. Hold the close while a Save-validation is in flight so the
1525
+ // dialog stays open to show the result; otherwise close (discard).
1526
+ function requestClose() {
1527
+ if (validating.value) return
1528
+ selection.value = null
1529
+ refused.value = {}
1530
+ result.value = null
1531
+ formError.value = null
1532
+ }
1533
+ </script>
1534
+
1535
+ <style scoped>
1536
+ /* The app shell (app.vue) is h-svh + overflow-hidden, so this page must own its
1537
+ own vertical scroll \u2014 otherwise the node list is clipped and can't scroll. */
1538
+ .ndx-page { height: 100%; overflow-y: auto; }
1539
+ .ndx-inner { max-width: 60rem; margin: 0 auto; padding: 2rem; font-family: sans-serif; }
1540
+ .ndx-head h1 { font-size: 1.5rem; font-weight: 600; }
1541
+ .ndx-err { color: #b91c1c; }
1542
+ .ndx-grid { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }
1543
+ .ndx-card { border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }
1544
+ .ndx-card:hover { border-color: #6366f1; box-shadow: 0 1px 6px rgba(0,0,0,.08); }
1545
+ .ndx-card-title { font-weight: 600; }
1546
+ .ndx-card-slug { color: #6b7280; font-size: .85rem; margin-top: .25rem; }
1547
+ .ndx-badges { margin-top: .5rem; display: flex; flex-wrap: wrap; gap: .35rem; }
1548
+ .ndx-badge { font-size: .7rem; background: #eef2ff; color: #4338ca; border-radius: .25rem; padding: .1rem .4rem; }
1549
+
1550
+ /* Verdict strip shown at the top of the reused dialog content (does not close). */
1551
+ .ndx-strip { flex: 0 0 auto; padding: .5rem 1rem; font-size: .85rem; font-weight: 600; }
1552
+ .ndx-strip-ok { background: #dcfce7; color: #166534; }
1553
+ .ndx-strip-err { background: #fee2e2; color: #991b1b; }
1554
+ </style>
1555
+ `;
1556
+ var GITIGNORE = `node_modules/
1557
+ .nuxt/
1558
+ .output/
1559
+ .data/
1560
+ `;
1561
+ var CONSOLE_STUBS = `import { ref } from 'vue'
1562
+
1563
+ export function useConsoleTenants() {
1564
+ return { tenants: ref([]), onlyTenantSlug: ref(null), load: async () => {} }
1565
+ }
1566
+ export function useActiveMarket() {
1567
+ return {
1568
+ markets: ref([]),
1569
+ activeCode: ref(''),
1570
+ isGlobal: ref(true),
1571
+ GLOBAL_MARKET_CODE: '__global__',
1572
+ fetchMarkets: async () => {},
1573
+ }
1574
+ }
1575
+ export function useConsoleSftp() {
1576
+ return {
1577
+ accounts: ref([]),
1578
+ load: async () => {},
1579
+ revealPassword: async () => ({}),
1580
+ create: async () => ({}),
1581
+ refresh: async () => ({}),
1582
+ }
1583
+ }
1584
+ export function useMailAdmin() {
1585
+ return {
1586
+ listCredentials: async () => [],
1587
+ getCredential: async () => ({}),
1588
+ createCredential: async () => ({}),
1589
+ }
1590
+ }
1591
+ export function useConsoleApiKeys() {
1592
+ return { create: async () => ({ secret: '' }) }
1593
+ }
1594
+ `;
1595
+ var HIDE_WORKFLOWS_MW = `export default defineNuxtRouteMiddleware((to) => {
1596
+ if (to.path === '/integrations/workflows' || to.path.startsWith('/integrations/workflows/')) {
1597
+ return navigateTo('/integrations')
1598
+ }
1599
+ })
1600
+ `;
1601
+ function previewTemplates(options) {
1602
+ const env = `# Overrides the Nuxt runtimeConfig.public.* values.
1603
+ NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
1604
+ NUXT_PUBLIC_DEV_TOKEN=dev
1605
+ NUXT_PUBLIC_DEV_TENANT=dev-tenant
1606
+ `;
1607
+ return {
1608
+ "package.json": PACKAGE_JSON,
1609
+ "nuxt.config.ts": NUXT_CONFIG,
1610
+ "assets/css/main.css": MAIN_CSS,
1611
+ "app.vue": APP_VUE,
1612
+ "pages/index.vue": INDEX_VUE,
1613
+ "pages/nodes.vue": NODES_VUE,
1614
+ "composables/devkit-console-stubs.ts": CONSOLE_STUBS,
1615
+ "middleware/hide-workflows.global.ts": HIDE_WORKFLOWS_MW,
1616
+ ".env": env,
1617
+ ".gitignore": GITIGNORE
1618
+ };
1619
+ }
1620
+
1621
+ // src/preview/scaffold.ts
1622
+ function scaffoldPreview(options) {
1623
+ const log = options.log ?? (() => {
1624
+ });
1625
+ const files = previewTemplates({ integrationsApiUrl: options.integrationsApiUrl });
1626
+ const written = [];
1627
+ const skipped = [];
1628
+ for (const [relative, content] of Object.entries(files)) {
1629
+ const target = (0, import_node_path2.resolve)(options.dir, relative);
1630
+ if ((0, import_node_fs2.existsSync)(target) && !options.force) {
1631
+ skipped.push(relative);
1632
+ continue;
1633
+ }
1634
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(target), { recursive: true });
1635
+ (0, import_node_fs2.writeFileSync)(target, content, "utf-8");
1636
+ written.push(relative);
1637
+ }
1638
+ if (written.length > 0) {
1639
+ log(`Scaffolded preview host in ${options.dir} (${written.length} file(s)).`);
1640
+ }
1641
+ if (skipped.length > 0) {
1642
+ log(`Kept ${skipped.length} existing file(s) (use --force to overwrite).`);
1643
+ }
1644
+ return { dir: options.dir, written, skipped };
1645
+ }
1646
+ function previewDepsInstalled(dir) {
1647
+ return (0, import_node_fs2.existsSync)((0, import_node_path2.join)(dir, "node_modules"));
1648
+ }
1649
+ function previewExists(dir) {
1650
+ return (0, import_node_fs2.existsSync)((0, import_node_path2.join)(dir, "package.json")) && (0, import_node_fs2.existsSync)((0, import_node_path2.join)(dir, "nuxt.config.ts"));
1651
+ }
1652
+
1653
+ // src/cli.ts
1654
+ var import_meta = {};
1655
+ function parseArgs(argv) {
1656
+ const cwd = process.cwd();
1657
+ const opts = {
1658
+ entry: "",
1659
+ seedDir: (0, import_node_path3.resolve)(cwd, "dev/seeds"),
1660
+ stateFile: (0, import_node_path3.resolve)(cwd, ".revenexx-dev/state.json"),
1661
+ persist: true,
1662
+ port: Number.parseInt(process.env.PORT ?? "3555", 10),
1663
+ uiDir: null,
1664
+ serveUi: true,
1665
+ open: false,
1666
+ previewDir: (0, import_node_path3.resolve)(cwd, ".revenexx-dev/preview"),
1667
+ force: false
1668
+ };
1669
+ let command = null;
1670
+ for (let i = 0; i < argv.length; i++) {
1671
+ const arg = argv[i];
1672
+ switch (arg) {
1673
+ case "reset":
1674
+ command = "reset";
1675
+ break;
1676
+ case "init-preview":
1677
+ command = "init-preview";
1678
+ break;
1679
+ case "preview":
1680
+ command = "preview";
1681
+ break;
1682
+ case "--dir":
1683
+ opts.previewDir = (0, import_node_path3.resolve)(cwd, argv[++i] ?? "");
1684
+ break;
1685
+ case "--force":
1686
+ opts.force = true;
1687
+ break;
1688
+ case "--entry":
1689
+ opts.entry = (0, import_node_path3.resolve)(cwd, argv[++i] ?? "");
1690
+ break;
1691
+ case "--seed":
1692
+ opts.seedDir = (0, import_node_path3.resolve)(cwd, argv[++i] ?? "");
1693
+ break;
1694
+ case "--state":
1695
+ opts.stateFile = (0, import_node_path3.resolve)(cwd, argv[++i] ?? "");
1696
+ break;
1697
+ case "--no-persist":
1698
+ opts.persist = false;
1699
+ break;
1700
+ case "--port":
1701
+ opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
1702
+ break;
1703
+ case "--ui":
1704
+ opts.uiDir = (0, import_node_path3.resolve)(cwd, argv[++i] ?? "");
1705
+ break;
1706
+ case "--no-ui":
1707
+ opts.serveUi = false;
1708
+ break;
1709
+ case "--open":
1710
+ opts.open = true;
1711
+ break;
1712
+ case "--version":
1713
+ case "-v":
1714
+ command = "version";
1715
+ break;
1716
+ default:
1717
+ if (arg?.startsWith("-")) {
1718
+ console.error(`Unknown option: ${arg}`);
1719
+ process.exit(1);
1720
+ }
1721
+ }
1722
+ }
1723
+ if (!opts.entry) {
1724
+ const src = (0, import_node_path3.resolve)(cwd, "src/index.ts");
1725
+ opts.entry = (0, import_node_fs3.existsSync)(src) ? src : (0, import_node_path3.resolve)(cwd, "dist/index.js");
1726
+ }
1727
+ return { command, options: opts };
1728
+ }
1729
+ function loadSchemas() {
1730
+ const here = (0, import_node_url2.fileURLToPath)(new URL(".", import_meta.url));
1731
+ const schemasDir = (0, import_node_path3.resolve)(here, "..", "assets", "schemas");
1732
+ const schemas = {};
1733
+ if (!(0, import_node_fs3.existsSync)(schemasDir)) {
1734
+ return schemas;
1735
+ }
1736
+ for (const file of (0, import_node_fs3.readdirSync)(schemasDir)) {
1737
+ if ((0, import_node_path3.extname)(file) !== ".json") {
1738
+ continue;
1739
+ }
1740
+ const parsed = JSON.parse((0, import_node_fs3.readFileSync)((0, import_node_path3.join)(schemasDir, file), "utf-8"));
1741
+ const base = file.replace(/\.json$/, "");
1742
+ const dash = base.indexOf("-");
1743
+ if (dash > 0) {
1744
+ const domain = base.slice(0, dash);
1745
+ const version = base.slice(dash + 1);
1746
+ schemas[`${domain}/${version}`] = parsed;
1747
+ schemas[domain] = parsed;
1748
+ } else {
1749
+ schemas[base] = parsed;
1750
+ }
1751
+ }
1752
+ return schemas;
1753
+ }
1754
+ function resolveUiDir(explicit) {
1755
+ if (explicit) {
1756
+ return (0, import_node_fs3.existsSync)(explicit) ? explicit : null;
1757
+ }
1758
+ const candidates = ["@revenexx/studio-integrations"];
1759
+ const req = (0, import_node_module.createRequire)(import_meta.url);
1760
+ for (const pkg of candidates) {
1761
+ try {
1762
+ const entry = req.resolve(`${pkg}/package.json`);
1763
+ const dist = (0, import_node_path3.resolve)(entry, "..", "dist");
1764
+ if ((0, import_node_fs3.existsSync)((0, import_node_path3.join)(dist, "index.html"))) {
1765
+ return dist;
1766
+ }
1767
+ } catch {
1768
+ }
1769
+ }
1770
+ return null;
1771
+ }
1772
+ var MIME = {
1773
+ ".html": "text/html",
1774
+ ".js": "text/javascript",
1775
+ ".mjs": "text/javascript",
1776
+ ".css": "text/css",
1777
+ ".json": "application/json",
1778
+ ".svg": "image/svg+xml",
1779
+ ".png": "image/png",
1780
+ ".ico": "image/x-icon",
1781
+ ".woff2": "font/woff2"
1782
+ };
1783
+ function serveStatic(uiDir, req, res) {
1784
+ const url = new URL(req.url ?? "/", "http://localhost");
1785
+ const relative = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1786
+ let filePath = (0, import_node_path3.resolve)(uiDir, relative);
1787
+ if (!filePath.startsWith(uiDir) || !(0, import_node_fs3.existsSync)(filePath)) {
1788
+ filePath = (0, import_node_path3.join)(uiDir, "index.html");
1789
+ }
1790
+ if (!(0, import_node_fs3.existsSync)(filePath)) {
1791
+ res.writeHead(404).end("UI build not found");
1792
+ return;
1793
+ }
1794
+ res.writeHead(200, { "Content-Type": MIME[(0, import_node_path3.extname)(filePath)] ?? "application/octet-stream" });
1795
+ res.end((0, import_node_fs3.readFileSync)(filePath));
1796
+ }
1797
+ async function startMock(options) {
1798
+ let loaded = await loadPackageFromEntry(options.entry);
1799
+ console.log(`Loaded ${loaded.nodes.length} node(s), ${loaded.credentials.length} credential(s), ${loaded.templates.length} template(s) from ${options.entry}`);
1800
+ const store = new DevStore();
1801
+ applySeeds(store, await loadSeedsFromDir(options.seedDir));
1802
+ if (options.persist) {
1803
+ const state = loadState(options.stateFile);
1804
+ if (state) {
1805
+ store.mergeSnapshot(state);
1806
+ console.log(`Restored session from ${options.stateFile}`);
1807
+ }
1808
+ let timer;
1809
+ store.setOnMutation(() => {
1810
+ clearTimeout(timer);
1811
+ timer = setTimeout(() => saveState(options.stateFile, store.toSnapshot()), 150);
1812
+ });
1813
+ }
1814
+ const schemas = loadSchemas();
1815
+ const apiListener = createRequestListener({ getPackage: () => loaded, store, schemas });
1816
+ const uiDir = options.serveUi ? resolveUiDir(options.uiDir) : null;
1817
+ const server = (0, import_node_http2.createServer)((req, res) => {
1818
+ const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
1819
+ if (pathname.startsWith("/api/") || pathname === "/health") {
1820
+ apiListener(req, res);
1821
+ } else if (uiDir) {
1822
+ serveStatic(uiDir, req, res);
1823
+ } else {
1824
+ res.writeHead(404, { "Content-Type": "application/json" }).end(
1825
+ JSON.stringify({
1826
+ message: "API-only. Point your Nuxt host (studio-integrations) integrationsApi at this URL, or pass --ui <static-build-dir>. CORS is open."
1827
+ })
1828
+ );
1829
+ }
1830
+ });
1831
+ await new Promise((r) => server.listen(options.port, r));
1832
+ const stopWatch = watchAndReload(options.entry, async () => {
1833
+ try {
1834
+ loaded = await loadPackageFromEntry(options.entry);
1835
+ console.log(`\u21BB Reloaded package (${loaded.nodes.length} nodes, ${loaded.credentials.length} credentials).`);
1836
+ } catch (err) {
1837
+ console.error(`Reload failed: ${err.message}`);
1838
+ }
1839
+ });
1840
+ return {
1841
+ uiDir,
1842
+ dispose() {
1843
+ if (options.persist) {
1844
+ saveState(options.stateFile, store.toSnapshot());
1845
+ }
1846
+ stopWatch?.();
1847
+ server.close();
1848
+ }
1849
+ };
1850
+ }
1851
+ async function run(options) {
1852
+ const mock = await startMock(options);
1853
+ const urlBase = `http://localhost:${options.port}`;
1854
+ console.log(`
1855
+ Mock Integrations API ${urlBase}/api/v1`);
1856
+ console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only \u2014 set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);
1857
+ console.log("\n Watching for changes. Ctrl-C to stop.\n");
1858
+ if (options.open && mock.uiDir) {
1859
+ void openBrowser(urlBase);
1860
+ }
1861
+ const shutdown = () => {
1862
+ mock.dispose();
1863
+ process.exit(0);
1864
+ };
1865
+ process.on("SIGINT", shutdown);
1866
+ process.on("SIGTERM", shutdown);
1867
+ }
1868
+ function watchAndReload(entry, onChange) {
1869
+ const dir = (0, import_node_path3.resolve)(entry, "..");
1870
+ let timer;
1871
+ try {
1872
+ const watcher = (0, import_node_fs3.watch)(dir, { recursive: true }, (_event, file) => {
1873
+ if (file && /\.[cm]?tsx?$|\.js$/.test(file.toString())) {
1874
+ clearTimeout(timer);
1875
+ timer = setTimeout(onChange, 200);
1876
+ }
1877
+ });
1878
+ return () => watcher.close();
1879
+ } catch {
1880
+ console.warn("Hot-reload unavailable on this platform; restart to pick up changes.");
1881
+ return void 0;
1882
+ }
1883
+ }
1884
+ async function runNpmInstall(dir) {
1885
+ const { spawn } = await import("child_process");
1886
+ await new Promise((resolvePromise, reject) => {
1887
+ const child = spawn("npm", ["install"], { cwd: dir, stdio: "inherit" });
1888
+ child.on("exit", (code) => code === 0 ? resolvePromise() : reject(new Error(`npm install exited with code ${code}`)));
1889
+ child.on("error", reject);
1890
+ });
1891
+ }
1892
+ async function preview(options) {
1893
+ const dir = options.previewDir;
1894
+ const apiUrl = `http://localhost:${options.port}/api/v1`;
1895
+ if (!previewExists(dir) || options.force) {
1896
+ scaffoldPreview({ dir, integrationsApiUrl: apiUrl, force: options.force, log: (msg) => console.log(msg) });
1897
+ }
1898
+ if (!previewDepsInstalled(dir)) {
1899
+ console.log("Installing preview-host dependencies (first run \u2014 this pulls Nuxt + the studio packages and may take a while)\u2026");
1900
+ await runNpmInstall(dir);
1901
+ }
1902
+ const mock = await startMock({ ...options, serveUi: false });
1903
+ console.log(`
1904
+ Mock Integrations API ${apiUrl}`);
1905
+ console.log(" Preview UI http://localhost:3000/integrations (Nuxt starting\u2026)\n");
1906
+ const { spawn } = await import("child_process");
1907
+ const child = spawn("npm", ["run", "dev"], {
1908
+ cwd: dir,
1909
+ stdio: "inherit",
1910
+ env: {
1911
+ ...process.env,
1912
+ NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
1913
+ NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1914
+ NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant"
1915
+ }
1916
+ });
1917
+ const shutdown = () => {
1918
+ child.kill("SIGTERM");
1919
+ mock.dispose();
1920
+ process.exit(0);
1921
+ };
1922
+ process.on("SIGINT", shutdown);
1923
+ process.on("SIGTERM", shutdown);
1924
+ child.on("exit", (code) => {
1925
+ mock.dispose();
1926
+ process.exit(code ?? 0);
1927
+ });
1928
+ }
1929
+ async function openBrowser(url) {
1930
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
1931
+ const { spawn } = await import("child_process");
1932
+ spawn(cmd, [url], { stdio: "ignore", detached: true }).unref();
1933
+ }
1934
+ async function main() {
1935
+ const { command, options } = parseArgs(process.argv.slice(2));
1936
+ if (command === "version") {
1937
+ console.log(DEVKIT_VERSION);
1938
+ return;
1939
+ }
1940
+ if (command === "reset") {
1941
+ const { rmSync } = await import("fs");
1942
+ rmSync(options.stateFile, { force: true });
1943
+ console.log(`Removed ${options.stateFile}`);
1944
+ return;
1945
+ }
1946
+ if (command === "init-preview") {
1947
+ scaffoldPreview({
1948
+ dir: options.previewDir,
1949
+ integrationsApiUrl: `http://localhost:${options.port}/api/v1`,
1950
+ force: options.force,
1951
+ log: (msg) => console.log(msg)
1952
+ });
1953
+ console.log(`
1954
+ Next: \`integrations-devkit preview\` (installs deps + starts mock + Nuxt), or \`cd ${options.previewDir} && npm install && npm run dev\`.`);
1955
+ return;
1956
+ }
1957
+ if (command === "preview") {
1958
+ await preview(options);
1959
+ return;
1960
+ }
1961
+ await run(options);
1962
+ }
1963
+ main().catch((err) => {
1964
+ console.error(err);
1965
+ process.exit(1);
1966
+ });
1967
+ //# sourceMappingURL=cli.cjs.map