@revenexx/integrations-node-devkit 0.2.2 → 0.3.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 CHANGED
@@ -28,11 +28,11 @@ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${_
28
28
  var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
29
29
 
30
30
  // src/cli.ts
31
- var import_node_fs5 = require("fs");
31
+ var import_node_fs6 = require("fs");
32
32
  var import_node_http2 = require("http");
33
33
  var import_node_module = require("module");
34
- var import_node_path4 = require("path");
35
- var import_node_url2 = require("url");
34
+ var import_node_path5 = require("path");
35
+ var import_node_url3 = require("url");
36
36
 
37
37
  // src/env.ts
38
38
  var import_node_fs = require("fs");
@@ -91,7 +91,7 @@ function loadEnvFile(argv, options = {}) {
91
91
  }
92
92
 
93
93
  // src/index.ts
94
- var import_node_fs3 = require("fs");
94
+ var import_node_fs4 = require("fs");
95
95
 
96
96
  // src/errors.ts
97
97
  var DevApiError = class extends Error {
@@ -106,9 +106,31 @@ var DevApiError = class extends Error {
106
106
  };
107
107
 
108
108
  // src/loader.ts
109
+ var import_node_fs2 = require("fs");
110
+ var import_node_path2 = require("path");
109
111
  var import_node_url = require("url");
110
112
  var import_integrations_node_sdk = require("@revenexx/integrations-node-sdk");
111
- function resolveExports(mod) {
113
+ var UNKNOWN_PACKAGE = { name: "unknown", version: "0.0.0", label: "Local package" };
114
+ function readPackageInfo(entryPath) {
115
+ let dir = (0, import_node_path2.dirname)(entryPath);
116
+ for (let up = 0; up < 6; up += 1) {
117
+ const candidate = (0, import_node_path2.join)(dir, "package.json");
118
+ if ((0, import_node_fs2.existsSync)(candidate)) {
119
+ try {
120
+ const pkg = JSON.parse((0, import_node_fs2.readFileSync)(candidate, "utf-8"));
121
+ if (pkg.name) {
122
+ return { name: pkg.name, version: pkg.version ?? "0.0.0", label: pkg.name.split("/").pop() ?? pkg.name };
123
+ }
124
+ } catch {
125
+ }
126
+ }
127
+ const parent = (0, import_node_path2.dirname)(dir);
128
+ if (parent === dir) break;
129
+ dir = parent;
130
+ }
131
+ return UNKNOWN_PACKAGE;
132
+ }
133
+ function resolveExports(mod, packageInfo = UNKNOWN_PACKAGE) {
112
134
  if (!Array.isArray(mod.NODES)) {
113
135
  throw new Error("Package entry does not export a `NODES` array. Export `NODES: INode[]`.");
114
136
  }
@@ -125,7 +147,9 @@ function resolveExports(mod) {
125
147
  nodes,
126
148
  credentials,
127
149
  templates,
128
- manifest: (0, import_integrations_node_sdk.buildManifest)(nodes, credentials, templates)
150
+ manifest: (0, import_integrations_node_sdk.buildManifest)(nodes, credentials, templates),
151
+ packageInfo,
152
+ loadedAt: (/* @__PURE__ */ new Date()).toISOString()
129
153
  };
130
154
  }
131
155
  var tsxRegistered = false;
@@ -137,6 +161,10 @@ async function ensureTsxRegistered() {
137
161
  register();
138
162
  tsxRegistered = true;
139
163
  }
164
+ var RELOADABLE_SOURCE = /\.(?:[cm]?[jt]sx?|json)$/;
165
+ function isReloadableSource(file) {
166
+ return RELOADABLE_SOURCE.test(file);
167
+ }
140
168
  async function importFresh(entryPath) {
141
169
  if (/\.[cm]?tsx?$/.test(entryPath)) {
142
170
  await ensureTsxRegistered();
@@ -145,17 +173,19 @@ async function importFresh(entryPath) {
145
173
  return await import(href);
146
174
  }
147
175
  async function loadPackageFromEntry(entryPath) {
148
- return resolveExports(await importFresh(entryPath));
176
+ return resolveExports(await importFresh(entryPath), readPackageInfo(entryPath));
149
177
  }
150
178
 
151
179
  // src/persistence.ts
152
- var import_node_fs2 = require("fs");
153
- var import_node_path2 = require("path");
180
+ var import_node_fs3 = require("fs");
181
+ var import_node_path3 = require("path");
154
182
 
155
183
  // src/store.ts
156
184
  var import_node_crypto = require("crypto");
157
185
  var DEV_TENANT_ID = "dev-tenant";
158
- var STORE_SCHEMA_VERSION = 1;
186
+ var BLOB_DEFINITION_VERSION = "v0-draft";
187
+ var EXECUTION_MODES = ["async_only", "sync_only", "caller_decides"];
188
+ var STORE_SCHEMA_VERSION = 2;
159
189
  function now() {
160
190
  return (/* @__PURE__ */ new Date()).toISOString();
161
191
  }
@@ -198,6 +228,9 @@ var DevStore = class {
198
228
  status: input.status ?? "active",
199
229
  config: input.config,
200
230
  durableCreds: input.durableCreds ?? null,
231
+ lastTestAt: null,
232
+ lastTestOk: null,
233
+ lastTestMessage: null,
201
234
  createdAt: ts,
202
235
  updatedAt: ts
203
236
  };
@@ -226,6 +259,21 @@ var DevStore = class {
226
259
  this.touch();
227
260
  return record;
228
261
  }
262
+ /**
263
+ * Records the outcome of a credential test. The service persists this on the
264
+ * record and reports it back from `POST /credentials/{id}/test`.
265
+ */
266
+ recordCredentialTest(id, result) {
267
+ const record = this.credentials.get(id);
268
+ if (!record) {
269
+ return void 0;
270
+ }
271
+ record.lastTestAt = now();
272
+ record.lastTestOk = result.ok;
273
+ record.lastTestMessage = result.message ?? null;
274
+ this.touch();
275
+ return record;
276
+ }
229
277
  deleteCredential(id) {
230
278
  const deleted = this.credentials.delete(id);
231
279
  if (deleted) {
@@ -272,7 +320,12 @@ var DevStore = class {
272
320
  const record = {
273
321
  id: this.nextWorkflowId++,
274
322
  name: input.name,
275
- definition: input.definition,
323
+ description: input.description ?? null,
324
+ blob: input.blob,
325
+ blobDefinitionVersion: input.blobDefinitionVersion ?? BLOB_DEFINITION_VERSION,
326
+ active: input.active ?? true,
327
+ executionMode: input.executionMode ?? EXECUTION_MODES[0],
328
+ revision: 1,
276
329
  buildStatus: "ready",
277
330
  createdAt: ts,
278
331
  updatedAt: ts
@@ -286,7 +339,8 @@ var DevStore = class {
286
339
  if (!record) {
287
340
  return void 0;
288
341
  }
289
- Object.assign(record, patch, { updatedAt: now() });
342
+ const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== void 0));
343
+ Object.assign(record, defined, { revision: record.revision + 1, updatedAt: now() });
290
344
  this.touch();
291
345
  return record;
292
346
  }
@@ -427,16 +481,23 @@ function applySeeds(store, seeds, env = process.env) {
427
481
  });
428
482
  }
429
483
  for (const workflow of seeds.workflows ?? []) {
430
- store.createWorkflow(interpolateEnv(workflow, env));
484
+ const resolved = interpolateEnv(workflow, env);
485
+ store.createWorkflow({
486
+ name: resolved.name,
487
+ blob: resolved.blob ?? resolved.definition ?? {},
488
+ description: resolved.description,
489
+ active: resolved.active,
490
+ executionMode: resolved.executionMode
491
+ });
431
492
  }
432
493
  }
433
494
  function loadState(file, log = console.warn) {
434
- if (!(0, import_node_fs2.existsSync)(file)) {
495
+ if (!(0, import_node_fs3.existsSync)(file)) {
435
496
  return null;
436
497
  }
437
498
  let parsed;
438
499
  try {
439
- parsed = JSON.parse((0, import_node_fs2.readFileSync)(file, "utf-8"));
500
+ parsed = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf-8"));
440
501
  } catch {
441
502
  log(`Ignoring ${file}: not valid JSON.`);
442
503
  return null;
@@ -448,14 +509,14 @@ function loadState(file, log = console.warn) {
448
509
  return parsed;
449
510
  }
450
511
  function saveState(file, snapshot) {
451
- (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(file), { recursive: true });
452
- (0, import_node_fs2.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
512
+ (0, import_node_fs3.mkdirSync)((0, import_node_path3.dirname)(file), { recursive: true });
513
+ (0, import_node_fs3.writeFileSync)(file, JSON.stringify(snapshot, null, 2), "utf-8");
453
514
  }
454
515
  var SEED_ENTRY_CANDIDATES = ["index.ts", "index.mjs", "index.js", "seeds.ts", "seeds.js"];
455
516
  async function loadSeedsFromDir(dir) {
456
517
  for (const candidate of SEED_ENTRY_CANDIDATES) {
457
- const path = (0, import_node_path2.resolve)(dir, candidate);
458
- if ((0, import_node_fs2.existsSync)(path)) {
518
+ const path = (0, import_node_path3.resolve)(dir, candidate);
519
+ if ((0, import_node_fs3.existsSync)(path)) {
459
520
  const mod = await importFresh(path);
460
521
  return mod.default ?? mod.seeds ?? {};
461
522
  }
@@ -721,6 +782,56 @@ async function validateNodeConfig(loaded, store, input) {
721
782
  }
722
783
  return { valid: Object.keys(errors).length === 0, errors };
723
784
  }
785
+ var MIN_TIMEOUT_MS = 1e3;
786
+ var DEFAULT_TIMEOUT_MS = 3e4;
787
+ var ExecuteTimeout = class extends Error {
788
+ };
789
+ async function executeNodeTest(loaded, store, input) {
790
+ const node = findNode(loaded, input.slug, input.version);
791
+ const logs = [];
792
+ const record = (level) => (message, meta) => {
793
+ logs.push(meta === void 0 ? { level, message } : { level, message, meta });
794
+ };
795
+ const timeoutMs = Math.max(MIN_TIMEOUT_MS, input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
796
+ const controller = new AbortController();
797
+ let timer;
798
+ const expired = new Promise((_resolve, reject) => {
799
+ timer = setTimeout(() => {
800
+ controller.abort();
801
+ reject(new ExecuteTimeout());
802
+ }, timeoutMs);
803
+ });
804
+ const ctx = {
805
+ signal: controller.signal,
806
+ logger: { info: record("info"), warn: record("warn"), error: record("error") },
807
+ secrets: {
808
+ async get(key) {
809
+ const secret = store.getSecret(key);
810
+ if (!secret) {
811
+ throw new DevApiError(404, `Secret '${key}' not found.`);
812
+ }
813
+ return secret.value;
814
+ }
815
+ },
816
+ credentials: {
817
+ async get(id) {
818
+ return (await resolveCredentialInstance(loaded, store, id)).credentials;
819
+ }
820
+ }
821
+ };
822
+ try {
823
+ const result = await Promise.race([node.execute(ctx, { ...input.config, ...input.inputs }), expired]);
824
+ return { outputs: result.outputs ?? {}, branch: result.branch ?? null, logs };
825
+ } catch (err) {
826
+ if (err instanceof DevApiError) {
827
+ throw err;
828
+ }
829
+ const reason = err instanceof ExecuteTimeout || controller.signal.aborted ? `timed out after ${timeoutMs} ms` : err.message;
830
+ throw new DevApiError(502, `Node execution failed: ${reason}`, { logs: logs.map((l) => `${l.level}: ${l.message}`) });
831
+ } finally {
832
+ clearTimeout(timer);
833
+ }
834
+ }
724
835
  async function testCredentialConfig(loaded, store, typeSlug, config) {
725
836
  const cred = findCredential(loaded, typeSlug);
726
837
  return cred.test(credentialContext(store), config);
@@ -762,16 +873,22 @@ async function exchangeOAuthCode(loaded, store, credentialId, params) {
762
873
  var import_node_http = __toESM(require("http"), 1);
763
874
 
764
875
  // src/http.ts
876
+ var API_VERSION = "1.0.0";
877
+ var BASE_HEADERS = {
878
+ "X-Api-Version": API_VERSION,
879
+ "Access-Control-Allow-Origin": "*",
880
+ "Access-Control-Allow-Headers": "*",
881
+ "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
882
+ };
765
883
  function sendJson(res, status, body) {
766
884
  const payload = JSON.stringify(body);
767
- res.writeHead(status, {
768
- "Content-Type": "application/json",
769
- "Access-Control-Allow-Origin": "*",
770
- "Access-Control-Allow-Headers": "*",
771
- "Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS"
772
- });
885
+ res.writeHead(status, { "Content-Type": "application/json", ...BASE_HEADERS });
773
886
  res.end(payload);
774
887
  }
888
+ function sendNoContent(res) {
889
+ res.writeHead(204, BASE_HEADERS);
890
+ res.end();
891
+ }
775
892
  function sendError(res, err) {
776
893
  if (err instanceof DevApiError) {
777
894
  sendJson(res, err.status, err.errors ? { message: err.message, errors: err.errors } : { message: err.message });
@@ -809,20 +926,24 @@ function hasDynamicSchema(desc) {
809
926
  function hasDynamicOutputs(desc) {
810
927
  return (desc.outputs ?? []).some((o) => o.resolveOutputs === true);
811
928
  }
812
- function nodeToApi(desc) {
929
+ function nodeToApi(desc, ctx) {
813
930
  const [namespace] = desc.slug.split(":");
814
931
  return {
815
932
  name: desc.name,
816
933
  namespace: namespace ?? null,
817
934
  slug: desc.slug,
818
935
  version: desc.version,
936
+ // The contract declares `package` and both timestamps as present. Nodes here
937
+ // come from the developer's working tree, so the package identity is read from
938
+ // their package.json and the timestamps are when the mock loaded the entry.
939
+ package: ctx?.packageInfo ?? null,
819
940
  manifest_version: import_integrations_node_sdk3.MANIFEST_VERSION,
820
941
  manifest: desc,
821
942
  has_dynamic_options: hasDynamicOptions(desc),
822
943
  has_dynamic_schema: hasDynamicSchema(desc),
823
944
  has_dynamic_outputs: hasDynamicOutputs(desc),
824
- created_at: null,
825
- updated_at: null
945
+ created_at: ctx?.loadedAt ?? null,
946
+ updated_at: ctx?.loadedAt ?? null
826
947
  };
827
948
  }
828
949
  function credentialTypeToApi(desc) {
@@ -832,6 +953,7 @@ function credentialTypeToApi(desc) {
832
953
  name: desc.name,
833
954
  description: desc.description ?? null,
834
955
  icon: desc.icon ?? null,
956
+ images: desc.images ?? [],
835
957
  auth_kind: desc.authKind,
836
958
  fields: desc.fields
837
959
  };
@@ -867,7 +989,16 @@ function workflowToApi(record) {
867
989
  return {
868
990
  id: record.id,
869
991
  name: record.name,
870
- definition: record.definition,
992
+ description: record.description,
993
+ blob_definition_version: record.blobDefinitionVersion,
994
+ blob: record.blob,
995
+ active: record.active,
996
+ execution_mode: record.executionMode,
997
+ revision: record.revision,
998
+ // The service reports blob-validation warnings here. The mock's validation is
999
+ // schema-light (see the fidelity caveats), so it never has any — but the field
1000
+ // is part of the contract and clients may read it.
1001
+ warnings: [],
871
1002
  build_status: record.buildStatus,
872
1003
  created_at: record.createdAt,
873
1004
  updated_at: record.updatedAt
@@ -896,6 +1027,7 @@ function templateSummaryToApi(t) {
896
1027
  shortDescription: t.shortDescription ?? null,
897
1028
  description: t.description ?? null,
898
1029
  icon: t.icon ?? null,
1030
+ images: t.images ?? [],
899
1031
  industries: t.industries ?? [],
900
1032
  vendors: t.vendors ?? [],
901
1033
  triggerTypes: (t.triggers ?? []).map((tr) => tr.type)
@@ -904,9 +1036,13 @@ function templateSummaryToApi(t) {
904
1036
  function templateFullToApi(t) {
905
1037
  return {
906
1038
  ...templateSummaryToApi(t),
907
- blobVersion: t.blobVersion,
1039
+ // snake_case per the contract, even though the surrounding template fields are
1040
+ // camelCase and the SDK's own field is `blobVersion`.
1041
+ blob_version: t.blobVersion,
908
1042
  definition: t.definition,
909
- triggers: t.triggers ?? []
1043
+ // `config` is optional in the SDK (a manual trigger has none) but declared in
1044
+ // the contract, so normalise it to an object rather than omitting it.
1045
+ triggers: (t.triggers ?? []).map((tr) => ({ ...tr, config: tr.config ?? {} }))
910
1046
  };
911
1047
  }
912
1048
 
@@ -934,13 +1070,15 @@ async function handle(req, res, deps) {
934
1070
  switch (seg[0]) {
935
1071
  case void 0:
936
1072
  case "health":
1073
+ // The service's health route is `/up` (Laravel's default); `/health` is kept
1074
+ // because the devkit has always answered there.
1075
+ case "up":
937
1076
  return void sendJson(res, 200, { status: "ok" });
938
1077
  case "me":
939
1078
  return void sendJson(res, 200, {
940
- id: "dev-user",
941
- name: "Dev User",
942
- email: "dev@revenexx.test",
943
- tenant_id: DEV_TENANT_ID
1079
+ user: { id: 1, zitadel_id: "dev-user", email: "dev@revenexx.test", name: "Dev User" },
1080
+ context: { tenant_id: DEV_TENANT_ID, active_plane: "public", roles: ["admin", "user"] },
1081
+ claims: { iss: "https://id.revenexx.test", sub: "dev-user", aud: ["devkit"] }
944
1082
  });
945
1083
  case "schemas":
946
1084
  return handleSchemas(res, deps, seg);
@@ -967,15 +1105,22 @@ function handleSchemas(res, deps, seg) {
967
1105
  throw new DevApiError(404, "Schema domain required.");
968
1106
  }
969
1107
  const schemas = deps.schemas ?? {};
970
- const schema = version && schemas[`${domain}/${version}`] || schemas[domain];
1108
+ if (!version) {
1109
+ const versions = Object.keys(schemas).filter((key) => key.startsWith(`${domain}/`)).map((key) => key.slice(domain.length + 1)).sort();
1110
+ if (versions.length === 0 && !schemas[domain]) {
1111
+ throw new DevApiError(404, `Unknown schema domain '${domain}'. Vendor it into assets/schemas.`);
1112
+ }
1113
+ return void sendJson(res, 200, { domain, versions });
1114
+ }
1115
+ const schema = schemas[`${domain}/${version}`];
971
1116
  if (!schema) {
972
- throw new DevApiError(404, `No schema for '${domain}${version ? `/${version}` : ""}'. Vendor it into assets/schemas.`);
1117
+ throw new DevApiError(404, `Unknown schema version '${domain}/${version}'. Vendor it into assets/schemas.`);
973
1118
  }
974
- sendJson(res, 200, schema);
1119
+ sendJson(res, 200, { domain, version, schema });
975
1120
  }
976
1121
  async function handleNodes(req, res, method, loaded, store, seg) {
977
1122
  if (seg.length === 1 && method === "GET") {
978
- return void sendJson(res, 200, { data: loaded.manifest.nodes.map(nodeToApi) });
1123
+ return void sendJson(res, 200, { data: loaded.manifest.nodes.map((n) => nodeToApi(n, nodeApiContext(loaded))) });
979
1124
  }
980
1125
  const slug = seg[1];
981
1126
  if (!slug) {
@@ -1016,15 +1161,36 @@ async function handleNodes(req, res, method, loaded, store, seg) {
1016
1161
  });
1017
1162
  return void sendJson(res, 200, result);
1018
1163
  }
1164
+ if (seg[3] === "execute:test" && method === "POST") {
1165
+ const body = await readJson(req);
1166
+ const result = await executeNodeTest(loaded, store, {
1167
+ slug,
1168
+ version,
1169
+ config: body.config ?? {},
1170
+ inputs: body.inputs ?? {},
1171
+ timeoutMs: body.timeout_ms
1172
+ });
1173
+ return void sendJson(res, 200, result);
1174
+ }
1019
1175
  if (seg.length === 3 && method === "GET") {
1020
- const node = loaded.manifest.nodes.find((n) => n.slug === slug && (version === "latest" || n.version === version));
1021
- if (!node) {
1022
- throw new DevApiError(404, `Node '${slug}@${version}' not found.`);
1023
- }
1024
- return void sendJson(res, 200, nodeToApi(node));
1176
+ return void sendJson(res, 200, nodeToApi(findManifestNode(loaded, slug, version), nodeApiContext(loaded)));
1177
+ }
1178
+ if (seg.length === 3 && method === "DELETE") {
1179
+ findManifestNode(loaded, slug, version);
1180
+ return void sendNoContent(res);
1025
1181
  }
1026
1182
  throw new DevApiError(404, `No route for nodes/${seg.slice(1).join("/")}`);
1027
1183
  }
1184
+ function nodeApiContext(loaded) {
1185
+ return { packageInfo: loaded.packageInfo, loadedAt: loaded.loadedAt };
1186
+ }
1187
+ function findManifestNode(loaded, slug, version) {
1188
+ const node = loaded.manifest.nodes.find((n) => n.slug === slug && (version === "latest" || n.version === version));
1189
+ if (!node) {
1190
+ throw new DevApiError(404, `Node '${slug}@${version}' not found.`);
1191
+ }
1192
+ return node;
1193
+ }
1028
1194
  function handleCredentialTypes(res, loaded, seg) {
1029
1195
  if (seg.length === 1) {
1030
1196
  return void sendJson(res, 200, {
@@ -1088,7 +1254,13 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1088
1254
  }
1089
1255
  if (seg[2] === "test" && method === "POST") {
1090
1256
  const result = await testCredentialInstance(loaded, store, id);
1091
- return void sendJson(res, 200, result);
1257
+ const record = store.recordCredentialTest(id, { ok: result.ok, message: result.message ?? null });
1258
+ return void sendJson(res, 200, {
1259
+ ok: result.ok,
1260
+ message: result.message ?? null,
1261
+ last_test_at: record?.lastTestAt ?? null,
1262
+ last_test_ok: record?.lastTestOk ?? result.ok
1263
+ });
1092
1264
  }
1093
1265
  if (seg[2] === "oauth" && seg[3] === "authorize-url" && method === "POST") {
1094
1266
  const redirectUri = "http://localhost/api/v1/credentials/oauth/callback";
@@ -1113,7 +1285,7 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1113
1285
  }
1114
1286
  if (method === "DELETE") {
1115
1287
  store.deleteCredential(id);
1116
- return void sendJson(res, 200, { deleted: true });
1288
+ return void sendNoContent(res);
1117
1289
  }
1118
1290
  }
1119
1291
  throw new DevApiError(404, `No route for credentials/${seg.slice(1).join("/")}`);
@@ -1121,7 +1293,7 @@ async function handleCredentials(req, res, method, loaded, store, seg, url) {
1121
1293
  async function handleSecrets(req, res, method, store, seg) {
1122
1294
  if (seg.length === 1) {
1123
1295
  if (method === "GET") {
1124
- return void sendJson(res, 200, { data: store.listSecrets().map(secretToApi) });
1296
+ return void sendJson(res, 200, { keys: store.listSecrets().map((s) => s.key) });
1125
1297
  }
1126
1298
  if (method === "POST") {
1127
1299
  const body = await readJson(req);
@@ -1143,7 +1315,7 @@ async function handleSecrets(req, res, method, store, seg) {
1143
1315
  }
1144
1316
  if (method === "DELETE") {
1145
1317
  store.deleteSecret(key);
1146
- return void sendJson(res, 200, { deleted: true });
1318
+ return void sendNoContent(res);
1147
1319
  }
1148
1320
  }
1149
1321
  throw new DevApiError(404, `No route for secrets/${seg.slice(1).join("/")}`);
@@ -1159,16 +1331,17 @@ async function handleTemplates(req, res, method, loaded, store, seg) {
1159
1331
  throw new DevApiError(404, `Template '${slug}' not found.`);
1160
1332
  }
1161
1333
  if (seg.length === 2 && method === "GET") {
1162
- return void sendJson(res, 200, templateFullToApi(template));
1334
+ return void sendJson(res, 200, { data: templateFullToApi(template) });
1163
1335
  }
1164
1336
  if (seg[2] === "requirements" && method === "GET") {
1165
- return void sendJson(res, 200, { data: { credentials: [], secrets: [] } });
1337
+ return void sendJson(res, 200, { data: { credentialTypes: [], secrets: [] } });
1166
1338
  }
1167
1339
  if (seg[2] === "instantiate" && method === "POST") {
1168
1340
  const body = await readJson(req);
1169
1341
  const workflow = store.createWorkflow({
1170
1342
  name: body.name ?? String(template.name),
1171
- definition: template.definition
1343
+ blob: template.definition,
1344
+ blobDefinitionVersion: template.blobVersion
1172
1345
  });
1173
1346
  for (const trigger of template.triggers ?? []) {
1174
1347
  store.createTrigger({
@@ -1193,7 +1366,11 @@ async function handleWorkflows(req, res, method, store, seg) {
1193
1366
  const body = await readJson(req);
1194
1367
  const workflow = store.createWorkflow({
1195
1368
  name: body.name ?? "Untitled workflow",
1196
- definition: body.definition ?? {}
1369
+ blob: body.blob ?? {},
1370
+ blobDefinitionVersion: body.blob_definition_version,
1371
+ description: body.description,
1372
+ active: body.active,
1373
+ executionMode: body.execution_mode
1197
1374
  });
1198
1375
  return void sendJson(res, 201, workflowToApi(workflow));
1199
1376
  }
@@ -1234,7 +1411,7 @@ async function handleWorkflows(req, res, method, store, seg) {
1234
1411
  }
1235
1412
  if (triggerId && method === "DELETE") {
1236
1413
  store.deleteTrigger(triggerId);
1237
- return void sendJson(res, 200, { deleted: true });
1414
+ return void sendNoContent(res);
1238
1415
  }
1239
1416
  }
1240
1417
  if (seg.length === 2) {
@@ -1247,7 +1424,14 @@ async function handleWorkflows(req, res, method, store, seg) {
1247
1424
  }
1248
1425
  if (method === "PUT") {
1249
1426
  const body = await readJson(req);
1250
- const updated = store.updateWorkflow(id, { name: body.name, definition: body.definition });
1427
+ const updated = store.updateWorkflow(id, {
1428
+ name: body.name,
1429
+ blob: body.blob,
1430
+ blobDefinitionVersion: body.blob_definition_version,
1431
+ description: body.description,
1432
+ active: body.active,
1433
+ executionMode: body.execution_mode
1434
+ });
1251
1435
  if (!updated) {
1252
1436
  throw new DevApiError(404, `Workflow '${id}' not found.`);
1253
1437
  }
@@ -1255,7 +1439,7 @@ async function handleWorkflows(req, res, method, store, seg) {
1255
1439
  }
1256
1440
  if (method === "DELETE") {
1257
1441
  store.deleteWorkflow(id);
1258
- return void sendJson(res, 200, { deleted: true });
1442
+ return void sendNoContent(res);
1259
1443
  }
1260
1444
  }
1261
1445
  if ((seg[2] === "credentials" || seg[2] === "credential-types") && method === "GET") {
@@ -1266,452 +1450,109 @@ async function handleWorkflows(req, res, method, store, seg) {
1266
1450
 
1267
1451
  // src/index.ts
1268
1452
  var manifestUrl = new URL("../package.json", importMetaUrl);
1269
- var DEVKIT_VERSION = JSON.parse((0, import_node_fs3.readFileSync)(manifestUrl, "utf8")).version;
1270
-
1271
- // src/preview/scaffold.ts
1272
- var import_node_fs4 = require("fs");
1273
- var import_node_path3 = require("path");
1274
-
1275
- // src/preview/templates.ts
1276
- var VERSIONS = {
1277
- nuxt: "^4.0.0",
1278
- vue: "^3.5.0",
1279
- studio: "^0.1.3",
1280
- studioShared: "^0.2.0",
1281
- studioIntegrations: "^0.5.1",
1282
- vueFlowCore: "^1.48.2",
1283
- vueFlowBackground: "^1.3.2",
1284
- vueFlowControls: "^1.1.3",
1285
- vueFlowMinimap: "^1.5.4",
1286
- vueFlowNodeToolbar: "^1.1.1",
1287
- dagre: "^3.0.0",
1288
- lucide: "^1.0.0",
1289
- solarIcons: "^1.2.1",
1290
- // studio-integrations 0.5.x embeds a TipTap rich-text editor and vue-sonner toasts.
1291
- tiptap: "^3.28.0",
1292
- vueSonner: "^2.0.0",
1293
- tailwindVite: "^4.0.0",
1294
- tailwind: "^4.0.0"
1295
- };
1296
- var PACKAGE_JSON = `{
1297
- "name": "integrations-preview-host",
1298
- "private": true,
1299
- "type": "module",
1300
- "scripts": {
1301
- "dev": "nuxt dev",
1302
- "build": "nuxt build"
1303
- },
1304
- "dependencies": {
1305
- "@revenexx/studio": "${VERSIONS.studio}",
1306
- "@revenexx/studio-integrations": "${VERSIONS.studioIntegrations}",
1307
- "@revenexx/studio-shared": "${VERSIONS.studioShared}",
1308
- "@solar-icons/nuxt": "${VERSIONS.solarIcons}",
1309
- "@dagrejs/dagre": "${VERSIONS.dagre}",
1310
- "@tiptap/core": "${VERSIONS.tiptap}",
1311
- "@tiptap/extension-document": "${VERSIONS.tiptap}",
1312
- "@tiptap/extension-history": "${VERSIONS.tiptap}",
1313
- "@tiptap/extension-paragraph": "${VERSIONS.tiptap}",
1314
- "@tiptap/extension-text": "${VERSIONS.tiptap}",
1315
- "@tiptap/pm": "${VERSIONS.tiptap}",
1316
- "@tiptap/vue-3": "${VERSIONS.tiptap}",
1317
- "@vue-flow/background": "${VERSIONS.vueFlowBackground}",
1318
- "@vue-flow/controls": "${VERSIONS.vueFlowControls}",
1319
- "@vue-flow/core": "${VERSIONS.vueFlowCore}",
1320
- "@vue-flow/minimap": "${VERSIONS.vueFlowMinimap}",
1321
- "@vue-flow/node-toolbar": "${VERSIONS.vueFlowNodeToolbar}",
1322
- "lucide-vue-next": "${VERSIONS.lucide}",
1323
- "nuxt": "${VERSIONS.nuxt}",
1324
- "vue": "${VERSIONS.vue}",
1325
- "vue-sonner": "${VERSIONS.vueSonner}"
1326
- },
1327
- "devDependencies": {
1328
- "@tailwindcss/vite": "${VERSIONS.tailwindVite}",
1329
- "tailwindcss": "${VERSIONS.tailwind}"
1330
- }
1331
- }
1332
- `;
1333
- var NUXT_CONFIG = `import tailwindcss from '@tailwindcss/vite';
1334
-
1335
- // Minimal preview host for local integration-node development.
1336
- // Generated by \`integrations-devkit init-preview\` \u2014 safe to edit or delete
1337
- // (it lives under the gitignored .revenexx-dev/).
1338
- export default defineNuxtConfig({
1339
- compatibilityDate: '2025-01-01',
1340
- // SPA: no SSR, so the studio's browser-only composables (localStorage etc.)
1341
- // behave exactly as in the real cockpit, and boot is fast.
1342
- ssr: false,
1343
- // studio-shared 0.2.x ships as a Nuxt MODULE (not a layer) \u2014 it must be
1344
- // registered in 'modules', before studio-integrations which builds on it.
1345
- // @solar-icons/nuxt provides the #solar-icons alias the studio components import.
1346
- modules: ['@revenexx/studio-shared', '@solar-icons/nuxt', '@revenexx/studio-integrations'],
1347
- css: ['~/assets/css/main.css'],
1348
- vite: { plugins: [tailwindcss()] },
1349
- runtimeConfig: {
1350
- public: {
1351
- // Overridden at runtime by NUXT_PUBLIC_* env (see .env / the preview command).
1352
- integrationsApi: '',
1353
- devToken: '',
1354
- devTenant: '',
1355
- },
1356
- },
1357
- });
1358
- `;
1359
- var MAIN_CSS = `@import "tailwindcss";
1360
- @import "@revenexx/studio/tokens";
1361
- @import "@revenexx/studio/fonts";
1362
-
1363
- @source "../../node_modules/@revenexx/studio/dist";
1364
- @source "../../node_modules/@revenexx/studio-shared/components";
1365
- @source "../../node_modules/@revenexx/studio-integrations/dist/runtime";
1366
-
1367
- /* Phase 1: workflow EXECUTION is not wired up in the devkit preview yet, so the
1368
- Workflows surface is hidden until phase 2. This hides the sidebar nav entry
1369
- and any deep links to the workflow editor; the routes are also redirected by
1370
- middleware/hide-workflows.global.ts. */
1371
- a[href^="/integrations/workflows"] { display: none !important; }
1372
- li:has(> a[href^="/integrations/workflows"]) { display: none !important; }
1373
- `;
1374
- var APP_VUE = `<script setup lang="ts">
1375
- import { Toaster } from '@revenexx/studio'
1376
-
1377
- useHead({ title: 'Integration Studio \u2014 devkit preview' })
1378
- </script>
1379
-
1380
- <template>
1381
- <div class="flex h-svh flex-col overflow-hidden bg-[#f3f1fa] text-foreground">
1382
- <NuxtLoadingIndicator color="var(--color-primary, #620DFF)" :height="3" />
1383
- <div class="min-h-0 flex-1 pt-3">
1384
- <NuxtPage />
1385
- </div>
1386
- <Toaster rich-colors position="bottom-right" :duration="3500" close-button />
1387
- </div>
1388
- </template>
1389
- `;
1390
- var INDEX_VUE = `<template>
1391
- <div class="mx-auto flex min-h-full max-w-xl flex-col justify-center gap-6 px-6 py-12">
1392
- <div>
1393
- <p class="text-mono text-muted-foreground">Integrations \xB7 node devkit</p>
1394
- <h1 class="mt-1 text-2xl font-medium">Integration Studio \u2014 Preview</h1>
1395
- <p class="mt-2 text-sm text-muted-foreground">
1396
- Lokaler Host f\xFCr <code>@revenexx/studio-integrations</code> gegen die Mock-API
1397
- deines Node-Pakets. Authentifizierung ist ein festes Dev-Token \u2014 nichts einzugeben.
1398
- </p>
1399
- </div>
1400
-
1401
- <div class="rounded-lg border border-black/[0.06] bg-card p-5 text-sm shadow-sm">
1402
- <p class="text-mono text-muted-foreground">Session</p>
1403
- <dl class="mt-2 grid grid-cols-[7rem_1fr] gap-y-1">
1404
- <dt class="text-muted-foreground">Mock API</dt>
1405
- <dd class="truncate font-mono text-xs leading-5">{{ api }}</dd>
1406
- <dt class="text-muted-foreground">Tenant</dt>
1407
- <dd class="font-mono text-xs leading-5">{{ tenant }}</dd>
1408
- </dl>
1409
- </div>
1410
-
1411
- <div class="rounded-lg border border-black/[0.06] bg-card p-5 shadow-sm">
1412
- <p class="text-mono text-muted-foreground">Einstieg</p>
1413
- <div class="mt-3 flex flex-col gap-4">
1414
- <NuxtLink
1415
- to="/nodes"
1416
- 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"
1417
- >
1418
- Lokale Nodes \xF6ffnen \u2014 Preview + Validierung
1419
- </NuxtLink>
1420
- <div class="flex flex-wrap gap-x-4 gap-y-1.5">
1421
- <NuxtLink
1422
- v-for="link in quickLinks"
1423
- :key="link.to"
1424
- :to="link.to"
1425
- class="text-sm text-primary hover:underline"
1426
- >
1427
- {{ link.label }}
1428
- </NuxtLink>
1429
- </div>
1430
- </div>
1431
- </div>
1432
- </div>
1433
- </template>
1434
-
1435
- <script setup lang="ts">
1436
- const rc = useRuntimeConfig().public
1437
- const api = rc.integrationsApi
1438
- const tenant = (rc.devTenant as string) || 'dev-tenant'
1439
-
1440
- const quickLinks = [
1441
- { to: '/integrations', label: 'Overview' },
1442
- { to: '/integrations/credentials', label: 'Credentials' },
1443
- { to: '/integrations/secrets', label: 'Secrets' },
1444
- { to: '/nodes', label: 'Local nodes' },
1445
- ]
1446
- </script>
1447
- `;
1448
- var NODES_VUE = `<template>
1449
- <div class="ndx-page">
1450
- <div class="ndx-inner">
1451
- <header class="ndx-head">
1452
- <h1>Lokale Nodes</h1>
1453
- <p>Mock-API: <code>{{ apiUrl }}</code></p>
1454
- <p v-if="loadError" class="ndx-err">{{ loadError }}</p>
1455
- </header>
1456
-
1457
- <p v-if="loading">Lade Nodes\u2026</p>
1458
- <p v-else-if="nodes.length === 0">Keine Nodes gefunden. Exportiert dein Paket <code>NODES</code>?</p>
1459
-
1460
- <ul v-else class="ndx-grid">
1461
- <li v-for="n in nodes" :key="n.slug + '@' + n.version" class="ndx-card" @click="openNode(n)">
1462
- <div class="ndx-card-title">{{ label(n) }}</div>
1463
- <div class="ndx-card-slug">{{ n.slug }} \xB7 v{{ n.version }}</div>
1464
- <div class="ndx-badges">
1465
- <span v-if="n.has_dynamic_options" class="ndx-badge">dynamic options</span>
1466
- <span v-if="n.has_dynamic_schema" class="ndx-badge">dynamic schema</span>
1467
- <span v-if="n.has_dynamic_outputs" class="ndx-badge">dynamic outputs</span>
1468
- </div>
1469
- </li>
1470
- </ul>
1471
- </div>
1472
-
1473
- <!-- REUSE of the exact editor lightbox: studio <Dialog> owns the modal
1474
- chrome, <IntegrationsNodeInspector> is the content \u2014 mirrors
1475
- WorkflowEditor.vue's <Dialog><DialogContent><NodeInspector/> block. -->
1476
- <Dialog :open="!!selection" @update:open="(v) => { if (!v) requestClose() }">
1477
- <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">
1478
- <div v-if="result === 'ok'" class="ndx-strip ndx-strip-ok">\u2713 Payload g\xFCltig \u2014 alles gut.</div>
1479
- <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>
1480
- <div v-else-if="formError" class="ndx-strip ndx-strip-err">{{ formError }}</div>
1481
- <IntegrationsNodeInspector
1482
- v-if="selection"
1483
- :selection="selection"
1484
- :secret-keys="secretKeys"
1485
- :refused-fields="refused"
1486
- @update="onSubmit"
1487
- @close="requestClose" />
1488
- </DialogContent>
1489
- </Dialog>
1490
- </div>
1491
- </template>
1492
-
1493
- <script setup lang="ts">
1494
- import { computed, onMounted, ref } from 'vue'
1495
- import { Dialog, DialogContent } from '@revenexx/studio'
1496
-
1497
- interface ApiNode {
1498
- name: string | Record<string, string>
1499
- slug: string
1500
- version: string
1501
- manifest?: { name?: string | Record<string, string> }
1502
- has_dynamic_options?: boolean
1503
- has_dynamic_schema?: boolean
1504
- has_dynamic_outputs?: boolean
1505
- }
1506
-
1507
- const apiUrl = useRuntimeConfig().public.integrationsApi
1508
- const client = useIntegrationsApi()
1509
- // load() fills the reactive catalog the inspector reads via findManifest();
1510
- // resolveLocalized() turns a LocalizedString into the active-locale string.
1511
- const { load, resolveLocalized } = useIntegrationsNodes()
1512
-
1513
- const nodes = ref<ApiNode[]>([])
1514
- const loading = ref(true)
1515
- const loadError = ref<string | null>(null)
1516
-
1517
- const selection = ref<any>(null)
1518
- const secretKeys = ref<string[]>([])
1519
- const refused = ref<Record<string, string>>({})
1520
- const result = ref<string | null>(null)
1521
- const formError = ref<string | null>(null)
1522
- // Set synchronously in onSubmit so the inspector's own Save (it emits update THEN
1523
- // close) does NOT close the dialog \u2014 we keep it open to show the verdict.
1524
- const validating = ref(false)
1525
-
1526
- const errorCount = computed(() => Object.keys(refused.value).length)
1527
-
1528
- function label(n: ApiNode): string {
1529
- return resolveLocalized(n.manifest?.name ?? n.name) || n.slug
1530
- }
1531
-
1532
- onMounted(async () => {
1533
- await load()
1534
- try {
1535
- const res = await client.get<any>('/nodes')
1536
- nodes.value = (Array.isArray(res) ? res : res?.data ?? []) as ApiNode[]
1537
- } catch (e: any) {
1538
- loadError.value = e?.message ?? 'Nodes konnten nicht geladen werden.'
1539
- } finally {
1540
- loading.value = false
1541
- }
1542
- try {
1543
- const secrets = await client.get<any>('/secrets')
1544
- const list = (Array.isArray(secrets) ? secrets : secrets?.data ?? []) as Array<{ key: string }>
1545
- secretKeys.value = list.map(s => s.key).filter(Boolean)
1546
- } catch {
1547
- // secrets are optional for the preview
1548
- }
1549
- })
1550
-
1551
- function openNode(n: ApiNode) {
1552
- refused.value = {}
1553
- result.value = null
1554
- formError.value = null
1555
- // Synthetic WorkflowNode selection (distinguished by nodeSlug); the inspector
1556
- // resolves its manifest from the catalog load() populated above.
1557
- selection.value = { id: 'preview', nodeSlug: n.slug, nodeVersion: n.version, name: label(n), config: {} }
1558
- }
1559
-
1560
- async function onSubmit(draft: any) {
1561
- validating.value = true
1562
- refused.value = {}
1563
- result.value = null
1564
- formError.value = null
1565
- try {
1566
- const slug = encodeURIComponent(draft.nodeSlug)
1567
- const version = encodeURIComponent(draft.nodeVersion || 'latest')
1568
- const res = await client.post<any>(
1569
- '/nodes/' + slug + '/' + version + '/config:validate',
1570
- { config: draft.config ?? {} },
1571
- )
1572
- if (res.valid) {
1573
- result.value = 'ok'
1574
- } else {
1575
- refused.value = Object.fromEntries(
1576
- Object.entries(res.errors ?? {}).map(([k, msgs]) => [k, (msgs as string[]).join(' ')]),
1577
- )
1578
- result.value = 'err'
1579
- }
1580
- } catch (e: any) {
1581
- formError.value = e?.message ?? 'Validierung fehlgeschlagen.'
1582
- } finally {
1583
- validating.value = false
1584
- }
1585
- }
1453
+ var DEVKIT_VERSION = JSON.parse((0, import_node_fs4.readFileSync)(manifestUrl, "utf8")).version;
1586
1454
 
1587
- // The inspector emits close on both Save and Cancel; the studio Dialog emits it
1588
- // on Esc / backdrop. Hold the close while a Save-validation is in flight so the
1589
- // dialog stays open to show the result; otherwise close (discard).
1590
- function requestClose() {
1591
- if (validating.value) return
1592
- selection.value = null
1593
- refused.value = {}
1594
- result.value = null
1595
- formError.value = null
1596
- }
1597
- </script>
1598
-
1599
- <style scoped>
1600
- /* The app shell (app.vue) is h-svh + overflow-hidden, so this page must own its
1601
- own vertical scroll \u2014 otherwise the node list is clipped and can't scroll. */
1602
- .ndx-page { height: 100%; overflow-y: auto; }
1603
- .ndx-inner { max-width: 60rem; margin: 0 auto; padding: 2rem; font-family: sans-serif; }
1604
- .ndx-head h1 { font-size: 1.5rem; font-weight: 600; }
1605
- .ndx-err { color: #b91c1c; }
1606
- .ndx-grid { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }
1607
- .ndx-card { border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }
1608
- .ndx-card:hover { border-color: #6366f1; box-shadow: 0 1px 6px rgba(0,0,0,.08); }
1609
- .ndx-card-title { font-weight: 600; }
1610
- .ndx-card-slug { color: #6b7280; font-size: .85rem; margin-top: .25rem; }
1611
- .ndx-badges { margin-top: .5rem; display: flex; flex-wrap: wrap; gap: .35rem; }
1612
- .ndx-badge { font-size: .7rem; background: #eef2ff; color: #4338ca; border-radius: .25rem; padding: .1rem .4rem; }
1613
-
1614
- /* Verdict strip shown at the top of the reused dialog content (does not close). */
1615
- .ndx-strip { flex: 0 0 auto; padding: .5rem 1rem; font-size: .85rem; font-weight: 600; }
1616
- .ndx-strip-ok { background: #dcfce7; color: #166534; }
1617
- .ndx-strip-err { background: #fee2e2; color: #991b1b; }
1618
- </style>
1619
- `;
1620
- var GITIGNORE = `node_modules/
1455
+ // src/preview/host.ts
1456
+ var import_node_crypto2 = require("crypto");
1457
+ var import_node_fs5 = require("fs");
1458
+ var import_node_os = require("os");
1459
+ var import_node_path4 = require("path");
1460
+ var import_node_url2 = require("url");
1461
+ var INSTALL_MARKER = ".devkit-install-complete";
1462
+ var COPY_MARKER = ".devkit-copy-complete";
1463
+ var HOST_GITIGNORE = `node_modules/
1621
1464
  .nuxt/
1465
+ .nuxt-*/
1622
1466
  .output/
1623
1467
  .data/
1468
+ .env
1469
+ ${COPY_MARKER}
1470
+ ${INSTALL_MARKER}
1624
1471
  `;
1625
- var CONSOLE_STUBS = `import { ref } from 'vue'
1626
-
1627
- export function useConsoleTenants() {
1628
- return { tenants: ref([]), onlyTenantSlug: ref(null), load: async () => {} }
1472
+ function resolveHostDir(options) {
1473
+ const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? (0, import_node_path4.join)((0, import_node_os.homedir)(), ".cache");
1474
+ return (0, import_node_path4.join)(root, "revenexx", "devkit-preview", options.version);
1629
1475
  }
1630
- export function useActiveMarket() {
1631
- return {
1632
- markets: ref([]),
1633
- activeCode: ref(''),
1634
- isGlobal: ref(true),
1635
- GLOBAL_MARKET_CODE: '__global__',
1636
- fetchMarkets: async () => {},
1476
+ function shippedHostDir() {
1477
+ let dir = (0, import_node_path4.dirname)((0, import_node_url2.fileURLToPath)(importMetaUrl));
1478
+ for (let up = 0; up < 5; up += 1) {
1479
+ const candidate = (0, import_node_path4.join)(dir, "preview-host");
1480
+ if ((0, import_node_fs5.existsSync)((0, import_node_path4.join)(candidate, "nuxt.config.ts"))) {
1481
+ return candidate;
1482
+ }
1483
+ const parent = (0, import_node_path4.dirname)(dir);
1484
+ if (parent === dir) break;
1485
+ dir = parent;
1637
1486
  }
1487
+ throw new Error("Preview host not found: no preview-host/nuxt.config.ts above this module. Reinstall @revenexx/integrations-node-devkit.");
1638
1488
  }
1639
- export function useConsoleSftp() {
1640
- return {
1641
- accounts: ref([]),
1642
- load: async () => {},
1643
- revealPassword: async () => ({}),
1644
- create: async () => ({}),
1645
- refresh: async () => ({}),
1646
- }
1489
+ function materializeHost(options) {
1490
+ const log = options.log ?? (() => {
1491
+ });
1492
+ const source = options.sourceDir ?? shippedHostDir();
1493
+ const dir = (0, import_node_path4.resolve)(options.targetDir);
1494
+ const managed = options.managed ?? false;
1495
+ const intact = managed ? hostIsComplete(dir) : hostExists(dir);
1496
+ const alreadyIntact = intact && !options.force;
1497
+ if (!alreadyIntact) {
1498
+ (0, import_node_fs5.mkdirSync)(dir, { recursive: true });
1499
+ (0, import_node_fs5.rmSync)((0, import_node_path4.join)(dir, COPY_MARKER), { force: true });
1500
+ (0, import_node_fs5.cpSync)(source, dir, { recursive: true, filter: (src) => !isInsideNodeModules(source, src) });
1501
+ (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, COPY_MARKER), `${(/* @__PURE__ */ new Date()).toISOString()}
1502
+ `, "utf-8");
1503
+ (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, ".gitignore"), HOST_GITIGNORE, "utf-8");
1504
+ log(`Preview host ready in ${dir}`);
1505
+ }
1506
+ const envPath = (0, import_node_path4.join)(dir, ".env");
1507
+ if (managed || !(0, import_node_fs5.existsSync)(envPath)) {
1508
+ (0, import_node_fs5.writeFileSync)(envPath, envFile(options), "utf-8");
1509
+ }
1510
+ return { dir, copied: !alreadyIntact };
1511
+ }
1512
+ function isInsideNodeModules(source, src) {
1513
+ const rel = (0, import_node_path4.relative)(source, src);
1514
+ return rel !== "" && rel.split(import_node_path4.sep).includes("node_modules");
1515
+ }
1516
+ function envFile(options) {
1517
+ return `# Generated by integrations-devkit \u2014 overrides the Nuxt runtimeConfig.public.* values.
1518
+ # The \`preview\` command also passes these to the Nuxt child process; this file is
1519
+ # what makes a manual \`npm run dev\` in this directory work.
1520
+ NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
1521
+ NUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? "dev"}
1522
+ NUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? "dev-tenant"}
1523
+ `;
1647
1524
  }
1648
- export function useMailAdmin() {
1649
- return {
1650
- listCredentials: async () => [],
1651
- getCredential: async () => ({}),
1652
- createCredential: async () => ({}),
1653
- }
1525
+ function hostBuildDir(hostDir, consumerDir) {
1526
+ const key = (0, import_node_crypto2.createHash)("sha256").update(consumerDir).digest("hex").slice(0, 12);
1527
+ return (0, import_node_path4.join)(hostDir, `.nuxt-${key}`);
1654
1528
  }
1655
- export function useConsoleApiKeys() {
1656
- return { create: async () => ({ secret: '' }) }
1529
+ function hostExists(dir) {
1530
+ return (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "package.json")) && (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "nuxt.config.ts"));
1657
1531
  }
1658
- `;
1659
- var HIDE_WORKFLOWS_MW = `export default defineNuxtRouteMiddleware((to) => {
1660
- if (to.path === '/integrations/workflows' || to.path.startsWith('/integrations/workflows/')) {
1661
- return navigateTo('/integrations')
1662
- }
1663
- })
1664
- `;
1665
- function previewTemplates(options) {
1666
- const env = `# Overrides the Nuxt runtimeConfig.public.* values.
1667
- NUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}
1668
- NUXT_PUBLIC_DEV_TOKEN=dev
1669
- NUXT_PUBLIC_DEV_TENANT=dev-tenant
1670
- `;
1671
- return {
1672
- "package.json": PACKAGE_JSON,
1673
- "nuxt.config.ts": NUXT_CONFIG,
1674
- "assets/css/main.css": MAIN_CSS,
1675
- "app.vue": APP_VUE,
1676
- "pages/index.vue": INDEX_VUE,
1677
- "pages/nodes.vue": NODES_VUE,
1678
- "composables/devkit-console-stubs.ts": CONSOLE_STUBS,
1679
- "middleware/hide-workflows.global.ts": HIDE_WORKFLOWS_MW,
1680
- ".env": env,
1681
- ".gitignore": GITIGNORE
1682
- };
1532
+ function hostIsComplete(dir) {
1533
+ return hostExists(dir) && (0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, COPY_MARKER));
1683
1534
  }
1684
-
1685
- // src/preview/scaffold.ts
1686
- function scaffoldPreview(options) {
1687
- const log = options.log ?? (() => {
1688
- });
1689
- const files = previewTemplates({ integrationsApiUrl: options.integrationsApiUrl });
1690
- const written = [];
1691
- const skipped = [];
1692
- for (const [relative, content] of Object.entries(files)) {
1693
- const target = (0, import_node_path3.resolve)(options.dir, relative);
1694
- if ((0, import_node_fs4.existsSync)(target) && !options.force) {
1695
- skipped.push(relative);
1696
- continue;
1697
- }
1698
- (0, import_node_fs4.mkdirSync)((0, import_node_path3.dirname)(target), { recursive: true });
1699
- (0, import_node_fs4.writeFileSync)(target, content, "utf-8");
1700
- written.push(relative);
1701
- }
1702
- if (written.length > 0) {
1703
- log(`Scaffolded preview host in ${options.dir} (${written.length} file(s)).`);
1535
+ function hostNeedsInstall(dir) {
1536
+ const marker = (0, import_node_path4.join)(dir, INSTALL_MARKER);
1537
+ if (!(0, import_node_fs5.existsSync)((0, import_node_path4.join)(dir, "node_modules")) || !(0, import_node_fs5.existsSync)(marker)) {
1538
+ return true;
1704
1539
  }
1705
- if (skipped.length > 0) {
1706
- log(`Kept ${skipped.length} existing file(s) (use --force to overwrite).`);
1540
+ try {
1541
+ return (0, import_node_fs5.readFileSync)(marker, "utf-8").trim() !== manifestFingerprint(dir);
1542
+ } catch {
1543
+ return true;
1707
1544
  }
1708
- return { dir: options.dir, written, skipped };
1709
1545
  }
1710
- function previewDepsInstalled(dir) {
1711
- return (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "node_modules"));
1546
+ function markHostInstalled(dir) {
1547
+ (0, import_node_fs5.writeFileSync)((0, import_node_path4.join)(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}
1548
+ `, "utf-8");
1712
1549
  }
1713
- function previewExists(dir) {
1714
- return (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "package.json")) && (0, import_node_fs4.existsSync)((0, import_node_path3.join)(dir, "nuxt.config.ts"));
1550
+ function clearHostInstallMarker(dir) {
1551
+ (0, import_node_fs5.rmSync)((0, import_node_path4.join)(dir, INSTALL_MARKER), { force: true });
1552
+ }
1553
+ function manifestFingerprint(dir) {
1554
+ const pkg = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path4.join)(dir, "package.json"), "utf-8"));
1555
+ return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });
1715
1556
  }
1716
1557
 
1717
1558
  // src/cli.ts
@@ -1719,14 +1560,14 @@ function parseArgs(argv) {
1719
1560
  const cwd = process.cwd();
1720
1561
  const opts = {
1721
1562
  entry: "",
1722
- seedDir: (0, import_node_path4.resolve)(cwd, "dev/seeds"),
1723
- stateFile: (0, import_node_path4.resolve)(cwd, ".revenexx-dev/state.json"),
1563
+ seedDir: (0, import_node_path5.resolve)(cwd, "dev/seeds"),
1564
+ stateFile: (0, import_node_path5.resolve)(cwd, ".revenexx-dev/state.json"),
1724
1565
  persist: true,
1725
1566
  port: Number.parseInt(process.env.PORT ?? "3555", 10),
1726
1567
  uiDir: null,
1727
1568
  serveUi: true,
1728
1569
  open: false,
1729
- previewDir: (0, import_node_path4.resolve)(cwd, ".revenexx-dev/preview"),
1570
+ previewDir: null,
1730
1571
  force: false
1731
1572
  };
1732
1573
  let command = null;
@@ -1743,19 +1584,19 @@ function parseArgs(argv) {
1743
1584
  command = "preview";
1744
1585
  break;
1745
1586
  case "--dir":
1746
- opts.previewDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1587
+ opts.previewDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1747
1588
  break;
1748
1589
  case "--force":
1749
1590
  opts.force = true;
1750
1591
  break;
1751
1592
  case "--entry":
1752
- opts.entry = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1593
+ opts.entry = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1753
1594
  break;
1754
1595
  case "--seed":
1755
- opts.seedDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1596
+ opts.seedDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1756
1597
  break;
1757
1598
  case "--state":
1758
- opts.stateFile = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1599
+ opts.stateFile = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1759
1600
  break;
1760
1601
  case "--no-persist":
1761
1602
  opts.persist = false;
@@ -1764,7 +1605,7 @@ function parseArgs(argv) {
1764
1605
  opts.port = Number.parseInt(argv[++i] ?? "3555", 10);
1765
1606
  break;
1766
1607
  case "--ui":
1767
- opts.uiDir = (0, import_node_path4.resolve)(cwd, argv[++i] ?? "");
1608
+ opts.uiDir = (0, import_node_path5.resolve)(cwd, argv[++i] ?? "");
1768
1609
  break;
1769
1610
  case "--no-ui":
1770
1611
  opts.serveUi = false;
@@ -1798,23 +1639,23 @@ function parseArgs(argv) {
1798
1639
  }
1799
1640
  }
1800
1641
  if (!opts.entry) {
1801
- const src = (0, import_node_path4.resolve)(cwd, "src/index.ts");
1802
- opts.entry = (0, import_node_fs5.existsSync)(src) ? src : (0, import_node_path4.resolve)(cwd, "dist/index.js");
1642
+ const src = (0, import_node_path5.resolve)(cwd, "src/index.ts");
1643
+ opts.entry = (0, import_node_fs6.existsSync)(src) ? src : (0, import_node_path5.resolve)(cwd, "dist/index.js");
1803
1644
  }
1804
1645
  return { command, options: opts };
1805
1646
  }
1806
1647
  function loadSchemas() {
1807
- const here = (0, import_node_url2.fileURLToPath)(new URL(".", importMetaUrl));
1808
- const schemasDir = (0, import_node_path4.resolve)(here, "..", "assets", "schemas");
1648
+ const here = (0, import_node_url3.fileURLToPath)(new URL(".", importMetaUrl));
1649
+ const schemasDir = (0, import_node_path5.resolve)(here, "..", "assets", "schemas");
1809
1650
  const schemas = {};
1810
- if (!(0, import_node_fs5.existsSync)(schemasDir)) {
1651
+ if (!(0, import_node_fs6.existsSync)(schemasDir)) {
1811
1652
  return schemas;
1812
1653
  }
1813
- for (const file of (0, import_node_fs5.readdirSync)(schemasDir)) {
1814
- if ((0, import_node_path4.extname)(file) !== ".json") {
1654
+ for (const file of (0, import_node_fs6.readdirSync)(schemasDir)) {
1655
+ if ((0, import_node_path5.extname)(file) !== ".json") {
1815
1656
  continue;
1816
1657
  }
1817
- const parsed = JSON.parse((0, import_node_fs5.readFileSync)((0, import_node_path4.join)(schemasDir, file), "utf-8"));
1658
+ const parsed = JSON.parse((0, import_node_fs6.readFileSync)((0, import_node_path5.join)(schemasDir, file), "utf-8"));
1818
1659
  const base = file.replace(/\.json$/, "");
1819
1660
  const dash = base.indexOf("-");
1820
1661
  if (dash > 0) {
@@ -1830,15 +1671,15 @@ function loadSchemas() {
1830
1671
  }
1831
1672
  function resolveUiDir(explicit) {
1832
1673
  if (explicit) {
1833
- return (0, import_node_fs5.existsSync)(explicit) ? explicit : null;
1674
+ return (0, import_node_fs6.existsSync)(explicit) ? explicit : null;
1834
1675
  }
1835
1676
  const candidates = ["@revenexx/studio-integrations"];
1836
1677
  const req = (0, import_node_module.createRequire)(importMetaUrl);
1837
1678
  for (const pkg of candidates) {
1838
1679
  try {
1839
1680
  const entry = req.resolve(`${pkg}/package.json`);
1840
- const dist = (0, import_node_path4.resolve)(entry, "..", "dist");
1841
- if ((0, import_node_fs5.existsSync)((0, import_node_path4.join)(dist, "index.html"))) {
1681
+ const dist = (0, import_node_path5.resolve)(entry, "..", "dist");
1682
+ if ((0, import_node_fs6.existsSync)((0, import_node_path5.join)(dist, "index.html"))) {
1842
1683
  return dist;
1843
1684
  }
1844
1685
  } catch {
@@ -1859,17 +1700,17 @@ var MIME = {
1859
1700
  };
1860
1701
  function serveStatic(uiDir, req, res) {
1861
1702
  const url = new URL(req.url ?? "/", "http://localhost");
1862
- const relative = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1863
- let filePath = (0, import_node_path4.resolve)(uiDir, relative);
1864
- if (!filePath.startsWith(uiDir) || !(0, import_node_fs5.existsSync)(filePath)) {
1865
- filePath = (0, import_node_path4.join)(uiDir, "index.html");
1703
+ const relative2 = url.pathname === "/" ? "index.html" : url.pathname.replace(/^\/+/, "");
1704
+ let filePath = (0, import_node_path5.resolve)(uiDir, relative2);
1705
+ if (!filePath.startsWith(uiDir) || !(0, import_node_fs6.existsSync)(filePath)) {
1706
+ filePath = (0, import_node_path5.join)(uiDir, "index.html");
1866
1707
  }
1867
- if (!(0, import_node_fs5.existsSync)(filePath)) {
1708
+ if (!(0, import_node_fs6.existsSync)(filePath)) {
1868
1709
  res.writeHead(404).end("UI build not found");
1869
1710
  return;
1870
1711
  }
1871
- res.writeHead(200, { "Content-Type": MIME[(0, import_node_path4.extname)(filePath)] ?? "application/octet-stream" });
1872
- res.end((0, import_node_fs5.readFileSync)(filePath));
1712
+ res.writeHead(200, { "Content-Type": MIME[(0, import_node_path5.extname)(filePath)] ?? "application/octet-stream" });
1713
+ res.end((0, import_node_fs6.readFileSync)(filePath));
1873
1714
  }
1874
1715
  async function startMock(options) {
1875
1716
  let loaded = await loadPackageFromEntry(options.entry);
@@ -1943,11 +1784,11 @@ async function run(options) {
1943
1784
  process.on("SIGTERM", shutdown);
1944
1785
  }
1945
1786
  function watchAndReload(entry, onChange) {
1946
- const dir = (0, import_node_path4.resolve)(entry, "..");
1787
+ const dir = (0, import_node_path5.resolve)(entry, "..");
1947
1788
  let timer;
1948
1789
  try {
1949
- const watcher = (0, import_node_fs5.watch)(dir, { recursive: true }, (_event, file) => {
1950
- if (file && /\.[cm]?tsx?$|\.js$/.test(file.toString())) {
1790
+ const watcher = (0, import_node_fs6.watch)(dir, { recursive: true }, (_event, file) => {
1791
+ if (file && isReloadableSource(file.toString())) {
1951
1792
  clearTimeout(timer);
1952
1793
  timer = setTimeout(onChange, 200);
1953
1794
  }
@@ -1966,15 +1807,34 @@ async function runNpmInstall(dir) {
1966
1807
  child.on("error", reject);
1967
1808
  });
1968
1809
  }
1810
+ function noteLegacyPreviewDir() {
1811
+ const legacy = (0, import_node_path5.resolve)(process.cwd(), ".revenexx-dev/preview");
1812
+ if ((0, import_node_fs6.existsSync)(legacy)) {
1813
+ console.log(`Note: ${legacy} is no longer used \u2014 the preview host now lives in a shared cache. You can delete it to reclaim the space.`);
1814
+ }
1815
+ }
1969
1816
  async function preview(options) {
1970
- const dir = options.previewDir;
1971
1817
  const apiUrl = `http://localhost:${options.port}/api/v1`;
1972
- if (!previewExists(dir) || options.force) {
1973
- scaffoldPreview({ dir, integrationsApiUrl: apiUrl, force: options.force, log: (msg) => console.log(msg) });
1818
+ const managed = options.previewDir === null;
1819
+ const targetDir = options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION });
1820
+ noteLegacyPreviewDir();
1821
+ const { dir } = materializeHost({
1822
+ targetDir,
1823
+ integrationsApiUrl: apiUrl,
1824
+ force: options.force,
1825
+ managed,
1826
+ log: (msg) => console.log(msg)
1827
+ });
1828
+ if (managed) {
1829
+ console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);
1830
+ }
1831
+ if (options.force) {
1832
+ clearHostInstallMarker(dir);
1974
1833
  }
1975
- if (!previewDepsInstalled(dir)) {
1976
- console.log("Installing preview-host dependencies (first run \u2014 this pulls Nuxt + the studio packages and may take a while)\u2026");
1834
+ if (hostNeedsInstall(dir)) {
1835
+ console.log("Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)\u2026");
1977
1836
  await runNpmInstall(dir);
1837
+ markHostInstalled(dir);
1978
1838
  }
1979
1839
  const mock = await startMock({ ...options, serveUi: false });
1980
1840
  console.log(`
@@ -1988,7 +1848,10 @@ async function preview(options) {
1988
1848
  ...process.env,
1989
1849
  NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,
1990
1850
  NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? "dev",
1991
- NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant"
1851
+ NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? "dev-tenant",
1852
+ // Keep the shared host's dependency install shared but its BUILD per repo,
1853
+ // so two node packages previewing at once do not compile over each other.
1854
+ DEVKIT_NUXT_BUILD_DIR: hostBuildDir(dir, process.cwd())
1992
1855
  }
1993
1856
  });
1994
1857
  const shutdown = () => {
@@ -2010,30 +1873,37 @@ async function openBrowser(url) {
2010
1873
  }
2011
1874
  async function main() {
2012
1875
  const argv = process.argv.slice(2);
2013
- const envFile = loadEnvFile(argv);
1876
+ const envFile2 = loadEnvFile(argv);
2014
1877
  const { command, options } = parseArgs(argv);
2015
1878
  if (command === "version") {
2016
1879
  console.log(DEVKIT_VERSION);
2017
1880
  return;
2018
1881
  }
2019
- if (envFile) {
2020
- console.log(`Loaded env from ${envFile}`);
1882
+ if (envFile2) {
1883
+ console.log(`Loaded env from ${envFile2}`);
2021
1884
  }
2022
1885
  if (command === "reset") {
2023
- const { rmSync } = await import("fs");
2024
- rmSync(options.stateFile, { force: true });
1886
+ const { rmSync: rmSync2 } = await import("fs");
1887
+ rmSync2(options.stateFile, { force: true });
2025
1888
  console.log(`Removed ${options.stateFile}`);
2026
1889
  return;
2027
1890
  }
2028
1891
  if (command === "init-preview") {
2029
- scaffoldPreview({
2030
- dir: options.previewDir,
1892
+ if (options.previewDir === null) {
1893
+ console.error("init-preview needs an explicit target: `integrations-devkit init-preview --dir ./my-preview`.");
1894
+ console.error("It exists to give you an UNMANAGED copy of the preview host to modify. For the normal preview, just run `integrations-devkit preview` \u2014");
1895
+ console.error("that materializes the host into a shared cache and keeps it in step with the devkit version.");
1896
+ process.exit(1);
1897
+ }
1898
+ const { dir } = materializeHost({
1899
+ targetDir: options.previewDir,
2031
1900
  integrationsApiUrl: `http://localhost:${options.port}/api/v1`,
2032
1901
  force: options.force,
2033
1902
  log: (msg) => console.log(msg)
2034
1903
  });
2035
- console.log(`
2036
- Next: \`integrations-devkit preview\` (installs deps + starts mock + Nuxt), or \`cd ${options.previewDir} && npm install && npm run dev\`.`);
1904
+ console.log("\nThis copy is yours and will NOT be updated by devkit upgrades.");
1905
+ console.log(`Run it with: \`cd ${dir} && npm install && npm run dev\` (plus \`integrations-devkit --no-ui\` for the mock),`);
1906
+ console.log(`or \`integrations-devkit preview --dir ${dir}\` to have both started for you.`);
2037
1907
  return;
2038
1908
  }
2039
1909
  if (command === "preview") {