@powerhousedao/reactor-workflow 6.2.3-dev.29 → 6.2.3-dev.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- import { A as REACTOR_FIND, D as OUTPUT_UPDATE, E as LOG_WRITE, F as STORE_GET, I as STORE_PUT, M as REACTOR_MODEL, N as REACTOR_MODELS, O as REACTOR_CREATE, P as STORE_DELETE, T as jsonSafe, a as redactMessage, c as DEFAULT_EGRESS_POLICY, g as rewriteFileRefs, i as redactError, j as REACTOR_GET, k as REACTOR_EXECUTE, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor, t as collectSecretValues, y as configuredMaxFileBytes } from "./redact-DM3JhxdF.js";
2
- import { AppConnectionType } from "@powerhousedao/pieces-framework";
1
+ import { A as REACTOR_CREATE, D as jsonSafe, F as REACTOR_MODELS, I as STORE_DELETE, J as getActions, L as STORE_GET, M as REACTOR_FIND, N as REACTOR_GET, O as LOG_WRITE, P as REACTOR_MODEL, R as STORE_PUT, a as redactMessage, c as DEFAULT_EGRESS_POLICY, i as redactError, j as REACTOR_EXECUTE, k as OUTPUT_UPDATE, n as containsRedactedMarker, o as rememberSecrets, r as redact, s as secretsFor, t as collectSecretValues, v as rewriteFileRefs, x as configuredMaxFileBytes, z as buildDescriptor } from "./redact-LRWHJGW9.js";
2
+ import { AppConnectionType, PieceCategory, Property, TriggerStrategy, createAction, createPiece, createTrigger } from "@powerhousedao/pieces-framework";
3
3
  import { execFile, fork } from "node:child_process";
4
4
  import { existsSync } from "node:fs";
5
5
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
@@ -8,7 +8,9 @@ import { promisify } from "node:util";
8
8
  import { gunzip } from "node:zlib";
9
9
  import { childLogger } from "document-model";
10
10
  import { fileURLToPath } from "node:url";
11
- import { randomUUID } from "node:crypto";
11
+ import { BRANCH_PORTS, CORE_PIECE_NAME, NEXT_PORT, PIECE_ACTION_PORTS, SCHEDULE_MODES, SCHEDULE_UNIT_MS, TRIGGER_PORTS, undeclaredPortEdges } from "@powerhousedao/pieces-framework/workflow";
12
+ import { createHash, randomUUID } from "node:crypto";
13
+ import { blockKey, isExactVersion } from "@powerhousedao/pieces-framework/block-type";
12
14
  //#region src/pieces/activepieces/registry-source.ts
13
15
  const logger$2 = childLogger(["workflow", "piece-registry"]);
14
16
  function source(baseUrl) {
@@ -36,14 +38,19 @@ function pieceRegistrySource() {
36
38
  //#endregion
37
39
  //#region src/pieces/activepieces/fetch.ts
38
40
  const gunzip$1 = promisify(gunzip);
39
- const CDN_PIECES_URL = "https://cdn.activepieces.com/pieces/bundled/";
40
- const NPM_REGISTRY_URL = "https://registry.npmjs.org";
41
+ const DEFAULT_CDN_PIECES_URL = "https://cdn.activepieces.com/pieces/bundled";
42
+ const DEFAULT_NPM_REGISTRY_URL = "https://registry.npmjs.org";
43
+ let cdnPiecesUrl = DEFAULT_CDN_PIECES_URL;
44
+ let npmRegistryUrl = DEFAULT_NPM_REGISTRY_URL;
45
+ function npmRegistryBaseUrl() {
46
+ return npmRegistryUrl;
47
+ }
41
48
  function cdnTarballUrl(name, version) {
42
- return `${CDN_PIECES_URL}${name.replace("/", "-")}-${version}.tgz`;
49
+ return `${cdnPiecesUrl}/${name.replace("/", "-")}-${version}.tgz`;
43
50
  }
44
51
  function npmTarballUrl(name, version) {
45
52
  const unscoped = name.startsWith("@") ? name.split("/")[1] : name;
46
- return `${NPM_REGISTRY_URL}/${name}/-/${unscoped}-${version}.tgz`;
53
+ return `${npmRegistryUrl}/${name}/-/${unscoped}-${version}.tgz`;
47
54
  }
48
55
  const NPM_NAME_RE = /^(@[a-z0-9][a-z0-9-_.]*\/)?[a-z0-9][a-z0-9-_.]*$/;
49
56
  const NPM_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9.+-]*$/;
@@ -106,7 +113,11 @@ async function readBoundedBody(response, url) {
106
113
  }
107
114
  return Buffer.concat(chunks);
108
115
  }
109
- function tarballSources(name, version) {
116
+ function tarballSources(name, version, only) {
117
+ const all = allTarballSources(name, version);
118
+ return only ? all.filter(({ source }) => only.includes(source)) : all;
119
+ }
120
+ function allTarballSources(name, version) {
110
121
  const registry = pieceRegistrySource();
111
122
  return [
112
123
  ...registry ? [{
@@ -123,8 +134,8 @@ function tarballSources(name, version) {
123
134
  }
124
135
  ];
125
136
  }
126
- async function downloadTarball(name, version, timeoutMs) {
127
- const sources = tarballSources(name, version);
137
+ async function downloadTarball(name, version, timeoutMs, only) {
138
+ const sources = tarballSources(name, version, only);
128
139
  let lastError;
129
140
  for (const { source, url } of sources) try {
130
141
  const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
@@ -141,8 +152,8 @@ async function downloadTarball(name, version, timeoutMs) {
141
152
  }
142
153
  throw new Error(`Failed to fetch piece bundle ${name}@${version}: ${String(lastError)}`);
143
154
  }
144
- async function extractDownloadedTarball(name, version, timeoutMs, staging) {
145
- const { tgz, source } = await downloadTarball(name, version, timeoutMs);
155
+ async function extractDownloadedTarball(name, version, timeoutMs, staging, only) {
156
+ const { tgz, source } = await downloadTarball(name, version, timeoutMs, only);
146
157
  await extractTarball(tgz, staging);
147
158
  return source;
148
159
  }
@@ -163,10 +174,14 @@ async function downloadPackagePiece(entryUrl, staging, timeoutMs) {
163
174
  await fetchInto(`${base}${entry}`, entry);
164
175
  return "package";
165
176
  }
177
+ function bundleDirFor(options) {
178
+ const leaf = `${options.name.replace("/", "-")}-${options.version}`;
179
+ return options.cacheScope ? path.join(options.cacheDir, options.cacheScope, leaf) : path.join(options.cacheDir, leaf);
180
+ }
166
181
  async function fetchPieceBundle(options) {
167
182
  const { name, version, cacheDir, timeoutMs = 3e4 } = options;
168
183
  assertValidPackageCoordinate(name, version);
169
- const dir = path.join(cacheDir, `${name.replace("/", "-")}-${version}`);
184
+ const dir = bundleDirFor(options);
170
185
  assertWithinCacheDir(dir, cacheDir);
171
186
  if (existsSync(path.join(dir, "package.json"))) return {
172
187
  dir,
@@ -179,7 +194,7 @@ async function fetchPieceBundle(options) {
179
194
  recursive: true,
180
195
  force: true
181
196
  });
182
- const source = options.entryUrl ? await downloadPackagePiece(options.entryUrl, staging, timeoutMs) : await extractDownloadedTarball(name, version, timeoutMs, staging);
197
+ const source = options.entryUrl ? await downloadPackagePiece(options.entryUrl, staging, timeoutMs) : await extractDownloadedTarball(name, version, timeoutMs, staging, options.sources);
183
198
  await rm(dir, {
184
199
  recursive: true,
185
200
  force: true
@@ -202,7 +217,7 @@ async function fetchPieceBundle(options) {
202
217
  }
203
218
  const inFlight = /* @__PURE__ */ new Map();
204
219
  async function ensurePieceBundle(options) {
205
- const key = `${options.cacheDir}\u0000${options.name}@${options.version}`;
220
+ const key = bundleDirFor(options);
206
221
  const pending = inFlight.get(key);
207
222
  if (pending) return pending;
208
223
  const started = resolveBundle(options).finally(() => inFlight.delete(key));
@@ -217,7 +232,7 @@ async function resolveBundle(options) {
217
232
  async function installPieceBundle(options, fetched) {
218
233
  const { name, version, cacheDir } = options;
219
234
  const timeoutMs = options.installTimeoutMs ?? INSTALL_TIMEOUT_MS;
220
- const workspace = path.join(cacheDir, `${name.replace("/", "-")}-${version}.install`);
235
+ const workspace = `${bundleDirFor(options)}.install`;
221
236
  assertWithinCacheDir(workspace, cacheDir);
222
237
  const dir = path.join(workspace, "node_modules", name);
223
238
  if (existsSync(path.join(workspace, INSTALL_READY_MARKER)) && existsSync(path.join(dir, "package.json"))) return {
@@ -245,7 +260,7 @@ async function installPieceBundle(options, fetched) {
245
260
  };
246
261
  }
247
262
  async function stageInstallWorkspace(workspace, options) {
248
- const { tgz } = await downloadTarball(options.name, options.version, options.timeoutMs ?? 3e4);
263
+ const { tgz } = await downloadTarball(options.name, options.version, options.timeoutMs ?? 3e4, options.sources);
249
264
  await rm(workspace, {
250
265
  recursive: true,
251
266
  force: true
@@ -323,35 +338,63 @@ async function readDependencies(dir) {
323
338
  }
324
339
  //#endregion
325
340
  //#region src/pieces/activepieces/resolver.ts
326
- function bundleResolver(options) {
327
- return { async resolve(name, version, entryUrl) {
341
+ const DOWNLOADS = {
342
+ registry: ["registry"],
343
+ activepieces: ["cdn", "npm"],
344
+ npm: ["npm"]
345
+ };
346
+ var PieceNotInstalledError = class extends Error {
347
+ constructor(name, version) {
348
+ super(`Piece ${name}@${version} is not installed on this reactor`);
349
+ this.name = "PieceNotInstalledError";
350
+ }
351
+ };
352
+ function sourcedResolver(options) {
353
+ const fetch = (target, extra) => ensurePieceBundle({
354
+ name: target.name,
355
+ version: target.version,
356
+ cacheDir: options.cacheDir,
357
+ ...extra.entryUrl ? { entryUrl: extra.entryUrl } : {},
358
+ ...extra.sources ? { sources: extra.sources } : {},
359
+ ...extra.scope ? { cacheScope: extra.scope } : {},
360
+ ...options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}
361
+ });
362
+ return { async resolve(target) {
363
+ const { name, version, source } = target;
364
+ if (source === "local") {
365
+ const local = await options.lookup?.(name);
366
+ if (!local || local.version !== version) throw new PieceNotInstalledError(name, version);
367
+ if (local.entryPath || local.bundleDir) return {
368
+ name,
369
+ version,
370
+ ...local.entryPath ? { entryPath: local.entryPath } : {},
371
+ ...local.bundleDir ? { bundleDir: local.bundleDir } : {},
372
+ local: true
373
+ };
374
+ if (!local.entryUrl) throw new PieceNotInstalledError(name, version);
375
+ return {
376
+ name,
377
+ version,
378
+ bundleDir: (await fetch(target, {
379
+ entryUrl: local.entryUrl,
380
+ scope: "local"
381
+ })).dir,
382
+ local: true
383
+ };
384
+ }
328
385
  return {
329
386
  name,
330
387
  version,
331
- bundleDir: (await ensurePieceBundle({
332
- name,
333
- version,
334
- cacheDir: options.cacheDir,
335
- ...entryUrl ? { entryUrl } : {},
336
- ...options.timeoutMs ? { timeoutMs: options.timeoutMs } : {}
337
- })).dir,
388
+ bundleDir: (await fetch(target, source ? {
389
+ sources: DOWNLOADS[source],
390
+ scope: source
391
+ } : {})).dir,
338
392
  local: false
339
393
  };
340
394
  } };
341
395
  }
342
- function localFirstResolver(lookup, fallback) {
343
- return { async resolve(name, version) {
344
- const local = await lookup(name);
345
- if (!local) return fallback.resolve(name, version);
346
- if (!local.entryPath && !local.bundleDir && local.entryUrl) return fallback.resolve(name, local.version, local.entryUrl);
347
- return {
348
- name,
349
- version: local.version,
350
- ...local.entryPath ? { entryPath: local.entryPath } : {},
351
- ...local.bundleDir ? { bundleDir: local.bundleDir } : {},
352
- local: true
353
- };
354
- } };
396
+ function bundleResolver(options) {
397
+ return sourcedResolver(options);
355
398
  }
356
399
  function pieceModuleRef(piece) {
357
400
  return piece.entryPath ? { entryPath: piece.entryPath } : { bundleDir: piece.bundleDir };
@@ -724,6 +767,24 @@ var PieceWorkerPool = class {
724
767
  }
725
768
  };
726
769
  //#endregion
770
+ //#region src/pieces/engine/types.ts
771
+ function stepBlock(step) {
772
+ return {
773
+ pieceName: step.pieceName,
774
+ pieceVersion: step.pieceVersion,
775
+ kind: "action",
776
+ name: step.actionName
777
+ };
778
+ }
779
+ function triggerBlock(trigger) {
780
+ return {
781
+ pieceName: trigger.pieceName,
782
+ pieceVersion: trigger.pieceVersion,
783
+ kind: "trigger",
784
+ name: trigger.triggerName
785
+ };
786
+ }
787
+ //#endregion
727
788
  //#region src/pieces/engine/secrets.ts
728
789
  const SECRET_REF_PREFIX = "secret://v1:";
729
790
  const SECRET_ID_PATTERN = /^[0-9a-f]{32}$/;
@@ -769,43 +830,208 @@ var InMemorySecretProvider = class {
769
830
  };
770
831
  //#endregion
771
832
  //#region src/pieces/engine/expressions.ts
772
- const WHOLE_EXPRESSION = /^\{\{\s*([^{}]+?)\s*\}\}$/;
773
- const EMBEDDED_EXPRESSION = /\{\{\s*([^{}]+?)\s*\}\}/g;
774
- function lookupPath(scope, path) {
833
+ var ExpressionSyntaxError = class extends Error {
834
+ constructor(source, detail) {
835
+ super(`Invalid expression {{${source}}}: ${detail}`);
836
+ this.name = "ExpressionSyntaxError";
837
+ }
838
+ };
839
+ var UnresolvedReferenceError = class extends Error {
840
+ reference;
841
+ constructor(reference) {
842
+ super(`Unresolved reference {{${reference}}}`);
843
+ this.reference = reference;
844
+ this.name = "UnresolvedReferenceError";
845
+ }
846
+ };
847
+ const IDENT = /[A-Za-z0-9_$-]/;
848
+ function parseExpression(source) {
849
+ let i = 0;
850
+ const fail = (detail) => {
851
+ throw new ExpressionSyntaxError(source, detail);
852
+ };
853
+ const skipSpace = () => {
854
+ while (i < source.length && /\s/.test(source[i])) i++;
855
+ };
856
+ const readString = () => {
857
+ const quote = source[i++];
858
+ let out = "";
859
+ while (i < source.length && source[i] !== quote) {
860
+ if (source[i] === "\\" && i + 1 < source.length) {
861
+ out += source[i + 1];
862
+ i += 2;
863
+ continue;
864
+ }
865
+ out += source[i++];
866
+ }
867
+ if (source[i] !== quote) fail("unterminated string");
868
+ i++;
869
+ return out;
870
+ };
871
+ const readIdent = () => {
872
+ const start = i;
873
+ while (i < source.length && IDENT.test(source[i])) i++;
874
+ if (i === start) fail(`expected a name at position ${start}`);
875
+ return source.slice(start, i);
876
+ };
877
+ const readTerm = () => {
878
+ skipSpace();
879
+ const start = i;
880
+ if (source[i] === "'" || source[i] === "\"") return {
881
+ kind: "literal",
882
+ value: readString()
883
+ };
884
+ const segments = [readIdent()];
885
+ for (;;) {
886
+ if (source[i] === ".") {
887
+ i++;
888
+ segments.push(readIdent());
889
+ continue;
890
+ }
891
+ if (source[i] === "[") {
892
+ i++;
893
+ skipSpace();
894
+ if (source[i] === "'" || source[i] === "\"") segments.push(readString());
895
+ else {
896
+ const digits = /^\d+/.exec(source.slice(i));
897
+ if (!digits) fail("a bracket takes a quoted key or an index");
898
+ segments.push(Number(digits[0]));
899
+ i += digits[0].length;
900
+ }
901
+ skipSpace();
902
+ if (source[i] !== "]") fail("expected ]");
903
+ i++;
904
+ continue;
905
+ }
906
+ break;
907
+ }
908
+ const optional = source[i] === "?";
909
+ if (optional) i++;
910
+ return {
911
+ kind: "path",
912
+ segments,
913
+ optional,
914
+ source: source.slice(start, i)
915
+ };
916
+ };
917
+ const terms = [readTerm()];
918
+ for (;;) {
919
+ skipSpace();
920
+ if (i >= source.length) break;
921
+ if (source.startsWith("||", i)) {
922
+ i += 2;
923
+ terms.push(readTerm());
924
+ continue;
925
+ }
926
+ fail(`unexpected "${source[i]}" at position ${i}`);
927
+ }
928
+ return {
929
+ terms,
930
+ source: source.trim()
931
+ };
932
+ }
933
+ function splitTemplate(text) {
934
+ const out = [];
935
+ let pending = "";
936
+ let cursor = 0;
937
+ const flush = () => {
938
+ if (pending) out.push({
939
+ kind: "text",
940
+ text: pending
941
+ });
942
+ pending = "";
943
+ };
944
+ for (;;) {
945
+ const open = text.indexOf("{{", cursor);
946
+ if (open < 0) break;
947
+ if (open > 0 && text[open - 1] === "\\") {
948
+ pending += text.slice(cursor, open - 1) + "{{";
949
+ cursor = open + 2;
950
+ continue;
951
+ }
952
+ let i = open + 2;
953
+ let quote;
954
+ let close = -1;
955
+ for (; i < text.length; i++) {
956
+ const char = text[i];
957
+ if (quote) {
958
+ if (char === "\\") i++;
959
+ else if (char === quote) quote = void 0;
960
+ continue;
961
+ }
962
+ if (char === "'" || char === "\"") quote = char;
963
+ else if (text.startsWith("}}", i)) {
964
+ close = i;
965
+ break;
966
+ }
967
+ }
968
+ if (close < 0) break;
969
+ pending += text.slice(cursor, open);
970
+ flush();
971
+ out.push({
972
+ kind: "expression",
973
+ text: text.slice(open + 2, close)
974
+ });
975
+ cursor = close + 2;
976
+ }
977
+ pending += text.slice(cursor);
978
+ flush();
979
+ return out;
980
+ }
981
+ /** Every expression a string holds, parsed. */
982
+ function expressionsIn(text) {
983
+ return splitTemplate(text).filter((segment) => segment.kind === "expression").map((segment) => parseExpression(segment.text));
984
+ }
985
+ const MISSING = Symbol("missing");
986
+ function lookupPath(scope, segments) {
775
987
  let current = scope;
776
- for (const segment of path.split(".")) {
777
- if (current === null || typeof current !== "object") return void 0;
778
- current = current[segment];
988
+ for (const segment of segments) {
989
+ if (current === null || typeof current !== "object") return MISSING;
990
+ const record = current;
991
+ if (!Object.prototype.hasOwnProperty.call(record, segment)) return MISSING;
992
+ current = record[segment];
779
993
  }
780
- return current;
994
+ return current === void 0 ? MISSING : current;
781
995
  }
782
- const STRING_LITERAL = /^(['"])(.*)\1$/;
783
- function resolveExpression(scope, expression) {
784
- for (const term of expression.split("||")) {
785
- const trimmed = term.trim();
786
- if (!trimmed) continue;
787
- const literal = STRING_LITERAL.exec(trimmed);
788
- const value = literal ? literal[2] : lookupPath(scope, trimmed);
789
- if (value !== void 0 && value !== null && value !== "") return value;
996
+ const isEmpty = (value) => value === null || value === "";
997
+ function evaluateExpression(expression, scope) {
998
+ const last = expression.terms.length - 1;
999
+ let value = null;
1000
+ for (const [index, term] of expression.terms.entries()) {
1001
+ if (term.kind === "literal") value = term.value;
1002
+ else {
1003
+ const found = lookupPath(scope, term.segments);
1004
+ if (found === MISSING) {
1005
+ if (term.optional) value = null;
1006
+ else if (index === last) throw new UnresolvedReferenceError(term.source);
1007
+ else continue;
1008
+ } else value = found;
1009
+ }
1010
+ if (!isEmpty(value)) return value;
790
1011
  }
1012
+ return value;
791
1013
  }
792
1014
  function interpolate(value) {
793
1015
  if (value === void 0 || value === null) return "";
794
1016
  if (typeof value === "object") return JSON.stringify(value);
795
1017
  return String(value);
796
1018
  }
1019
+ function resolveTemplate(text, scope) {
1020
+ const segments = splitTemplate(text);
1021
+ if (!segments.some((segment) => segment.kind === "expression")) return segments.map((segment) => segment.text).join("");
1022
+ const meaningful = segments.filter((segment) => segment.kind === "expression" || segment.text.trim() !== "");
1023
+ if (meaningful.length === 1) return evaluateExpression(parseExpression(meaningful[0].text), scope);
1024
+ return segments.map((segment) => segment.kind === "text" ? segment.text : interpolate(evaluateExpression(parseExpression(segment.text), scope))).join("");
1025
+ }
1026
+ /** Evaluates every string in a value, nested ones included. */
797
1027
  function resolveExpressions(value, scope) {
798
- if (typeof value === "string") {
799
- const whole = WHOLE_EXPRESSION.exec(value);
800
- if (whole) return resolveExpression(scope, whole[1]);
801
- return value.replaceAll(EMBEDDED_EXPRESSION, (_, path) => interpolate(resolveExpression(scope, path)));
802
- }
1028
+ if (typeof value === "string") return resolveTemplate(value, scope);
803
1029
  if (Array.isArray(value)) return value.map((item) => resolveExpressions(item, scope));
804
1030
  if (value !== null && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, resolveExpressions(entry, scope)]));
805
1031
  return value;
806
1032
  }
807
1033
  function evaluateCondition(condition, scope) {
808
- const resolved = resolveExpressions(condition, scope);
1034
+ const resolved = resolveTemplate(condition, scope);
809
1035
  if (resolved === "false" || resolved === "0") return false;
810
1036
  return Boolean(resolved);
811
1037
  }
@@ -835,11 +1061,60 @@ async function resolveSecrets(source, secrets) {
835
1061
  }
836
1062
  async function shapeConnection(source, secrets) {
837
1063
  const resolved = await resolveSecrets(source, secrets);
1064
+ if (source.authType === "OAUTH2") return shapeOAuth2(source, resolved);
838
1065
  return {
839
1066
  auth: shapeAuth(source, resolved),
840
1067
  secretValues: Object.values(resolved)
841
1068
  };
842
1069
  }
1070
+ function shapeOAuth2(source, resolved) {
1071
+ const { client_secret: clientSecret, token, ...secretProps } = resolved;
1072
+ const { client_id: clientId, ...configProps } = source.config ?? {};
1073
+ if (!token) throw new Error("This OAuth2 connection is not signed in; connect it first");
1074
+ let tokens;
1075
+ try {
1076
+ tokens = JSON.parse(token);
1077
+ } catch {
1078
+ throw new Error("Stored OAuth2 token is malformed; reconnect");
1079
+ }
1080
+ const text = (value, fallback = "") => typeof value === "string" ? value : fallback;
1081
+ const auth = {
1082
+ type: AppConnectionType.OAUTH2,
1083
+ client_id: text(clientId),
1084
+ client_secret: text(clientSecret),
1085
+ redirect_url: text(tokens.redirect_url),
1086
+ access_token: text(tokens.access_token),
1087
+ refresh_token: text(tokens.refresh_token),
1088
+ token_type: text(tokens.token_type, "Bearer"),
1089
+ claimed_at: Number(tokens.claimed_at ?? 0),
1090
+ scope: text(tokens.scope),
1091
+ token_url: text(tokens.token_url),
1092
+ ...typeof tokens.expires_in === "number" ? { expires_in: tokens.expires_in } : {},
1093
+ data: tokens.data ?? {},
1094
+ props: {
1095
+ ...configProps,
1096
+ ...secretProps
1097
+ }
1098
+ };
1099
+ const secretValues = [
1100
+ clientSecret,
1101
+ auth.access_token,
1102
+ auth.refresh_token,
1103
+ ...Object.values(secretProps),
1104
+ ...tokenLikeValues(auth.data)
1105
+ ].filter((value) => Boolean(value));
1106
+ return {
1107
+ auth,
1108
+ secretValues: [...new Set(secretValues)]
1109
+ };
1110
+ }
1111
+ const TOKEN_KEY = /(token|secret)$/i;
1112
+ function tokenLikeValues(value, key = "") {
1113
+ if (typeof value === "string") return TOKEN_KEY.test(key) ? [value] : [];
1114
+ if (Array.isArray(value)) return value.flatMap((item) => tokenLikeValues(item, key));
1115
+ if (value !== null && typeof value === "object") return Object.entries(value).flatMap(([name, item]) => tokenLikeValues(item, name));
1116
+ return [];
1117
+ }
843
1118
  function shapeAuth(source, resolved) {
844
1119
  switch (source.authType) {
845
1120
  case "NONE": return;
@@ -921,49 +1196,589 @@ var BoundConnectionResolver = class {
921
1196
  }
922
1197
  };
923
1198
  //#endregion
924
- //#region src/pieces/engine/blocks.ts
925
- var UnknownBlockTypeError = class extends Error {
926
- constructor(blockType) {
927
- super(`No executor registered for block type "${blockType}"`);
928
- this.name = "UnknownBlockTypeError";
1199
+ //#region src/pieces/core/branch-operators.ts
1200
+ var BranchConfigError = class extends Error {
1201
+ constructor(message) {
1202
+ super(`Branch: ${message}`);
1203
+ this.name = "BranchConfigError";
929
1204
  }
930
1205
  };
931
- var TriggerBlockAsStepError = class extends Error {
932
- constructor(blockType) {
933
- super(`Trigger block type "${blockType}" cannot run as a workflow step`);
934
- this.name = "TriggerBlockAsStepError";
935
- }
1206
+ function describe(value) {
1207
+ if (value === void 0) return "nothing";
1208
+ const text = JSON.stringify(value);
1209
+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;
1210
+ }
1211
+ function asText(value, side, caseSensitive) {
1212
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw new BranchConfigError(`${side} must be text, got ${describe(value)}`);
1213
+ const text = String(value);
1214
+ return caseSensitive ? text : text.toLowerCase();
1215
+ }
1216
+ const DECIMAL = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?$/;
1217
+ function asNumber(value, side) {
1218
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1219
+ if (typeof value === "string" && DECIMAL.test(value.trim())) return Number(value.trim());
1220
+ throw new BranchConfigError(`${side} must be a number, got ${describe(value)}`);
1221
+ }
1222
+ function asBoolean(value, side) {
1223
+ if (typeof value === "boolean") return value;
1224
+ if (value === "true") return true;
1225
+ if (value === "false") return false;
1226
+ throw new BranchConfigError(`${side} must be true or false, got ${describe(value)}`);
1227
+ }
1228
+ function asDate(value, side) {
1229
+ const time = typeof value === "number" ? value : typeof value === "string" && value.trim() !== "" ? Date.parse(value) : NaN;
1230
+ if (!Number.isFinite(time)) throw new BranchConfigError(`${side} must be a date, got ${describe(value)}`);
1231
+ return time;
1232
+ }
1233
+ function asList(value, side) {
1234
+ if (Array.isArray(value)) return value;
1235
+ throw new BranchConfigError(`${side} must be a list, got ${describe(value)}`);
1236
+ }
1237
+ const blank = (value) => value === void 0 || value === null || value === "";
1238
+ function textOp(label, test) {
1239
+ return {
1240
+ label,
1241
+ left: "text",
1242
+ binary: true,
1243
+ text: true,
1244
+ test: (left, right, caseSensitive) => test(asText(left, "left", caseSensitive), asText(right, "right", caseSensitive))
1245
+ };
1246
+ }
1247
+ function numberOp(label, test) {
1248
+ return {
1249
+ label,
1250
+ left: "number",
1251
+ binary: true,
1252
+ text: false,
1253
+ test: (left, right) => test(asNumber(left, "left"), asNumber(right, "right"))
1254
+ };
1255
+ }
1256
+ function dateOp(label, test) {
1257
+ return {
1258
+ label,
1259
+ left: "date",
1260
+ binary: true,
1261
+ text: false,
1262
+ test: (left, right) => test(asDate(left, "left"), asDate(right, "right"))
1263
+ };
1264
+ }
1265
+ function unary(label, left, test) {
1266
+ return {
1267
+ label,
1268
+ left,
1269
+ binary: false,
1270
+ text: false,
1271
+ test
1272
+ };
1273
+ }
1274
+ function listHas(left, right, caseSensitive) {
1275
+ const wanted = asText(right, "right", caseSensitive);
1276
+ return asList(left, "left").some((item) => {
1277
+ if (typeof item === "object" && item !== null) return false;
1278
+ const text = String(item);
1279
+ return (caseSensitive ? text : text.toLowerCase()) === wanted;
1280
+ });
1281
+ }
1282
+ const BRANCH_OPERATORS = {
1283
+ TEXT_EXACTLY_MATCHES: textOp("Text is exactly", (a, b) => a === b),
1284
+ TEXT_DOES_NOT_EXACTLY_MATCH: textOp("Text is not exactly", (a, b) => a !== b),
1285
+ TEXT_CONTAINS: textOp("Text contains", (a, b) => a.includes(b)),
1286
+ TEXT_DOES_NOT_CONTAIN: textOp("Text does not contain", (a, b) => !a.includes(b)),
1287
+ TEXT_STARTS_WITH: textOp("Text starts with", (a, b) => a.startsWith(b)),
1288
+ TEXT_DOES_NOT_START_WITH: textOp("Text does not start with", (a, b) => !a.startsWith(b)),
1289
+ TEXT_ENDS_WITH: textOp("Text ends with", (a, b) => a.endsWith(b)),
1290
+ TEXT_DOES_NOT_END_WITH: textOp("Text does not end with", (a, b) => !a.endsWith(b)),
1291
+ NUMBER_IS_EQUAL_TO: numberOp("Number equals", (a, b) => a === b),
1292
+ NUMBER_IS_GREATER_THAN: numberOp("Number is greater than", (a, b) => a > b),
1293
+ NUMBER_IS_LESS_THAN: numberOp("Number is less than", (a, b) => a < b),
1294
+ DATE_IS_EQUAL: dateOp("Date is", (a, b) => a === b),
1295
+ DATE_IS_BEFORE: dateOp("Date is before", (a, b) => a < b),
1296
+ DATE_IS_AFTER: dateOp("Date is after", (a, b) => a > b),
1297
+ BOOLEAN_IS_TRUE: unary("Is true", "boolean", (v) => asBoolean(v, "left")),
1298
+ BOOLEAN_IS_FALSE: unary("Is false", "boolean", (v) => !asBoolean(v, "left")),
1299
+ LIST_CONTAINS: {
1300
+ label: "List contains",
1301
+ left: "list",
1302
+ binary: true,
1303
+ text: true,
1304
+ test: listHas
1305
+ },
1306
+ LIST_DOES_NOT_CONTAIN: {
1307
+ label: "List does not contain",
1308
+ left: "list",
1309
+ binary: true,
1310
+ text: true,
1311
+ test: (left, right, caseSensitive) => !listHas(left, right, caseSensitive)
1312
+ },
1313
+ LIST_IS_EMPTY: unary("List is empty", "list", (v) => asList(v, "left").length === 0),
1314
+ LIST_IS_NOT_EMPTY: unary("List is not empty", "list", (v) => asList(v, "left").length > 0),
1315
+ EXISTS: unary("Exists", "any", (v) => !blank(v)),
1316
+ DOES_NOT_EXIST: unary("Does not exist", "any", blank)
936
1317
  };
937
- var CoreBlockExecutor = class {
938
- static handles(blockType) {
939
- return blockType.startsWith("core#");
940
- }
941
- execute(execution) {
942
- if (execution.blockType === "core#branch") {
943
- const { condition, equals } = execution.config;
944
- const normalize = (value) => (typeof value === "string" ? value : value === void 0 || value === null ? "" : JSON.stringify(value)).trim().toLowerCase();
945
- const taken = typeof equals === "string" ? normalize(condition) === normalize(equals) : Boolean(condition) && condition !== "false" && condition !== "0";
946
- return Promise.resolve({
947
- output: { condition: condition ?? null },
948
- port: taken ? "true" : "false"
949
- });
950
- }
951
- if (execution.blockType === "core#assert") return this.assert(execution);
952
- return Promise.reject(new UnknownBlockTypeError(execution.blockType));
953
- }
954
- assert(execution) {
955
- const { value, rejectValues, allowValues, allowEmpty, message } = execution.config;
956
- const trimmed = (typeof value === "string" ? value : value === void 0 || value === null ? "" : JSON.stringify(value)).trim();
957
- const fail = (reason) => Promise.reject(new Error(typeof message === "string" && message ? message : `core#assert: ${reason}`));
1318
+ const OPERATORS = BRANCH_OPERATORS;
1319
+ const DEFAULT_BRANCH_OPERATOR = "TEXT_EXACTLY_MATCHES";
1320
+ function evaluateBranch(config) {
1321
+ if (config === null || typeof config !== "object" || Array.isArray(config)) throw new BranchConfigError("the config must be an object");
1322
+ const { operator, left, right, caseSensitive } = config;
1323
+ if (operator === void 0 || operator === null || operator === "") throw new BranchConfigError("an operator is required");
1324
+ if (typeof operator !== "string" || !Object.hasOwn(OPERATORS, operator)) throw new BranchConfigError(`unknown operator ${describe(operator)}`);
1325
+ if (caseSensitive !== void 0 && typeof caseSensitive !== "boolean") throw new BranchConfigError("caseSensitive must be true or false");
1326
+ const spec = OPERATORS[operator];
1327
+ const result = spec.test(left, right, caseSensitive === true);
1328
+ return {
1329
+ operator,
1330
+ left,
1331
+ ...spec.binary ? { right } : {},
1332
+ result
1333
+ };
1334
+ }
1335
+ //#endregion
1336
+ //#region src/pieces/core/hints.ts
1337
+ function withHints(property, hints) {
1338
+ return {
1339
+ ...property,
1340
+ ...hints
1341
+ };
1342
+ }
1343
+ const shownWhen = (prop, oneOf) => ({ showWhen: {
1344
+ prop,
1345
+ oneOf
1346
+ } });
1347
+ function withPorts(action, ported) {
1348
+ return Object.assign(action, ported);
1349
+ }
1350
+ function isPorted(action) {
1351
+ const candidate = action;
1352
+ return typeof candidate?.portOf === "function" && Array.isArray(candidate.ports);
1353
+ }
1354
+ function withDisplay(trigger, display) {
1355
+ return Object.assign(trigger, { display });
1356
+ }
1357
+ //#endregion
1358
+ //#region src/pieces/core/actions.ts
1359
+ const operators = Object.entries(BRANCH_OPERATORS);
1360
+ const BINARY_OPERATORS = operators.filter(([, spec]) => spec.binary).map(([name]) => name);
1361
+ const TEXT_OPERATORS = operators.filter(([, spec]) => spec.text).map(([name]) => name);
1362
+ const branchAction = withPorts(createAction({
1363
+ name: "branch",
1364
+ displayName: "Branch",
1365
+ description: "Takes the true port when the operator holds for its operands, else the false port. An operand of the wrong type (a number operator on text, a list operator on something that is not a list) fails the step.",
1366
+ requireAuth: false,
1367
+ props: {
1368
+ left: Property.ShortText({
1369
+ displayName: "Value",
1370
+ description: "What to test, usually an expression.",
1371
+ required: true,
1372
+ placeholder: "{{steps.fetch.output.status}}"
1373
+ }),
1374
+ operator: Property.StaticDropdown({
1375
+ displayName: "Condition",
1376
+ description: "How the value is tested.",
1377
+ required: true,
1378
+ defaultValue: DEFAULT_BRANCH_OPERATOR,
1379
+ options: { options: operators.map(([value, spec]) => ({
1380
+ value,
1381
+ label: spec.label
1382
+ })) }
1383
+ }),
1384
+ right: withHints(Property.ShortText({
1385
+ displayName: "Compared with",
1386
+ description: "The value the condition compares to.",
1387
+ required: true
1388
+ }), shownWhen("operator", BINARY_OPERATORS)),
1389
+ caseSensitive: withHints(Property.Checkbox({
1390
+ displayName: "Case sensitive",
1391
+ description: "Match letter case exactly.",
1392
+ required: false
1393
+ }), shownWhen("operator", TEXT_OPERATORS))
1394
+ },
1395
+ run: (ctx) => Promise.resolve(evaluateBranch(ctx.propsValue))
1396
+ }), {
1397
+ ports: BRANCH_PORTS,
1398
+ portOf: (output) => output.result ? "true" : "false"
1399
+ });
1400
+ function assertionText(value) {
1401
+ if (typeof value === "string") return value;
1402
+ if (value === void 0 || value === null) return "";
1403
+ return JSON.stringify(value);
1404
+ }
1405
+ function normalizedList(entries) {
1406
+ return (typeof entries === "string" ? [entries] : Array.isArray(entries) ? entries : []).map((entry) => String(entry).trim().toLowerCase()).filter(Boolean);
1407
+ }
1408
+ const assertAction = withPorts(createAction({
1409
+ name: "assert",
1410
+ displayName: "Assert",
1411
+ description: "Fails the step when its value is blank or rejected, so a bad value stops the run instead of reaching a step with a side effect.",
1412
+ requireAuth: false,
1413
+ props: {
1414
+ value: Property.ShortText({
1415
+ displayName: "Value",
1416
+ description: "e.g. {{steps.describe.output}} - the run fails when it is blank.",
1417
+ required: true
1418
+ }),
1419
+ rejectValues: Property.Array({
1420
+ displayName: "Rejected values",
1421
+ description: "One per line; the run fails when the value matches any of them.",
1422
+ required: false
1423
+ }),
1424
+ allowValues: Property.Array({
1425
+ displayName: "Allowed values",
1426
+ description: "One per line; when set, anything else fails. Safer than a reject list for model output.",
1427
+ required: false
1428
+ }),
1429
+ allowEmpty: Property.Checkbox({
1430
+ displayName: "Allow empty",
1431
+ description: "Accept a blank value instead of failing.",
1432
+ required: false
1433
+ }),
1434
+ message: Property.ShortText({
1435
+ displayName: "Failure message",
1436
+ description: "Replaces the default error.",
1437
+ required: false
1438
+ })
1439
+ },
1440
+ run: (ctx) => {
1441
+ const { value, rejectValues, allowValues, allowEmpty, message } = ctx.propsValue;
1442
+ const trimmed = assertionText(value).trim();
1443
+ const fail = (reason) => Promise.reject(new Error(typeof message === "string" && message ? message : `Assert: ${reason}`));
958
1444
  if (!trimmed && allowEmpty !== true) return fail("value is empty");
959
- const normalizeList = (entries) => (typeof entries === "string" ? [entries] : Array.isArray(entries) ? entries : []).map((entry) => String(entry).trim().toLowerCase()).filter(Boolean);
960
- if (normalizeList(rejectValues).includes(trimmed.toLowerCase())) return fail(`value is a rejected value ("${trimmed}")`);
961
- const allowed = normalizeList(allowValues);
1445
+ if (normalizedList(rejectValues).includes(trimmed.toLowerCase())) return fail(`value is a rejected value ("${trimmed}")`);
1446
+ const allowed = normalizedList(allowValues);
962
1447
  if (allowed.length > 0 && !allowed.includes(trimmed.toLowerCase())) return fail(`value "${trimmed}" is not one of the allowed values (${allowed.join(", ")})`);
963
- return Promise.resolve({
964
- output: { value },
965
- port: "next"
1448
+ return Promise.resolve({ value });
1449
+ }
1450
+ }), {
1451
+ ports: PIECE_ACTION_PORTS,
1452
+ portOf: () => NEXT_PORT
1453
+ });
1454
+ //#endregion
1455
+ //#region src/pieces/core/triggers.ts
1456
+ function hostFed(name) {
1457
+ return () => Promise.reject(/* @__PURE__ */ new Error(`The "${name}" trigger is fired by the host, not by its hooks`));
1458
+ }
1459
+ const hooks = (name) => ({
1460
+ onEnable: hostFed(name),
1461
+ onDisable: hostFed(name),
1462
+ run: hostFed(name)
1463
+ });
1464
+ const options = (entries) => ({ options: entries.map(([value, label]) => ({
1465
+ value,
1466
+ label
1467
+ })) });
1468
+ const scheduleTrigger = withDisplay(createTrigger({
1469
+ name: "schedule",
1470
+ displayName: "Schedule",
1471
+ description: "Fires on a five-field cron expression, or every so many minutes, hours or days.",
1472
+ type: TriggerStrategy.POLLING,
1473
+ requireAuth: false,
1474
+ props: {
1475
+ mode: Property.StaticDropdown({
1476
+ displayName: "Runs",
1477
+ description: "cron or interval.",
1478
+ required: true,
1479
+ defaultValue: "cron",
1480
+ options: options([[SCHEDULE_MODES[0], "On a cron schedule"], [SCHEDULE_MODES[1], "At a fixed interval"]])
1481
+ }),
1482
+ cron: withHints(Property.ShortText({
1483
+ displayName: "Cron expression",
1484
+ description: "Five fields, e.g. 0 9 * * 1-5 runs at 09:00 on weekdays.",
1485
+ required: true,
1486
+ defaultValue: "0 9 * * 1-5"
1487
+ }), shownWhen("mode", ["cron"])),
1488
+ every: withHints(Property.Number({
1489
+ displayName: "Every",
1490
+ description: "A whole number of units, at least 1.",
1491
+ required: true,
1492
+ defaultValue: 15
1493
+ }), shownWhen("mode", ["interval"])),
1494
+ unit: withHints(Property.StaticDropdown({
1495
+ displayName: "Unit",
1496
+ description: "minutes, hours or days.",
1497
+ required: true,
1498
+ defaultValue: "minutes",
1499
+ options: { options: Object.keys(SCHEDULE_UNIT_MS).map((unit) => ({
1500
+ value: unit,
1501
+ label: unit.charAt(0).toUpperCase() + unit.slice(1)
1502
+ })) }
1503
+ }), shownWhen("mode", ["interval"])),
1504
+ timezone: Property.ShortText({
1505
+ displayName: "Timezone",
1506
+ description: "An IANA name such as Europe/Lisbon. Defaults to UTC.",
1507
+ required: false,
1508
+ defaultValue: "UTC"
1509
+ })
1510
+ },
1511
+ sampleData: {
1512
+ scheduledFor: "2026-09-28T09:00:00.000Z",
1513
+ firedAt: "2026-09-28T09:00:00.120Z",
1514
+ timezone: "UTC",
1515
+ cron: "0 9 * * 1-5"
1516
+ },
1517
+ ...hooks("schedule")
1518
+ }), "schedule");
1519
+ const SIGNED_SCHEMES = [
1520
+ "token",
1521
+ "hmac",
1522
+ "hmac-prefixed",
1523
+ "hmac-timestamped"
1524
+ ];
1525
+ const HMAC_SCHEMES = [
1526
+ "hmac",
1527
+ "hmac-prefixed",
1528
+ "hmac-timestamped"
1529
+ ];
1530
+ const SECRET_REF_TYPE = "PH_SECRET_REF";
1531
+ const webhookTrigger = createTrigger({
1532
+ name: "webhook",
1533
+ displayName: "Webhook",
1534
+ description: "Fires on an HTTP delivery to the workflow's endpoint. Ask for the URL with the webhookEndpoint query rather than constructing it.",
1535
+ type: TriggerStrategy.WEBHOOK,
1536
+ requireAuth: false,
1537
+ props: {
1538
+ methods: Property.StaticDropdown({
1539
+ displayName: "Method",
1540
+ description: "The HTTP method a delivery must use.",
1541
+ required: true,
1542
+ defaultValue: "POST",
1543
+ options: options([
1544
+ ["POST", "POST"],
1545
+ ["ANY", "Any"],
1546
+ ["GET", "GET"],
1547
+ ["PUT", "PUT"],
1548
+ ["PATCH", "PATCH"],
1549
+ ["DELETE", "DELETE"]
1550
+ ])
1551
+ }),
1552
+ scheme: Property.StaticDropdown({
1553
+ displayName: "Verification",
1554
+ description: "How a delivery proves its sender.",
1555
+ required: true,
1556
+ defaultValue: "none",
1557
+ options: options([
1558
+ ["none", "None — the URL's token only"],
1559
+ ["token", "Shared token in a header"],
1560
+ ["hmac", "HMAC digest"],
1561
+ ["hmac-prefixed", "HMAC digest with a label (sha256=…)"],
1562
+ ["hmac-timestamped", "HMAC digest, timestamped (t=…,v1=…)"]
1563
+ ])
1564
+ }),
1565
+ secretRef: withHints({
1566
+ ...Property.ShortText({
1567
+ displayName: "Secret",
1568
+ description: "The shared secret: the value the header must equal, or the key the sender signs with",
1569
+ required: true
1570
+ }),
1571
+ type: SECRET_REF_TYPE
1572
+ }, shownWhen("scheme", SIGNED_SCHEMES)),
1573
+ header: withHints(Property.ShortText({
1574
+ displayName: "Header",
1575
+ description: "Where the token or signature is read from. Defaults to the header the chosen scheme conventionally uses; set it only if the sender differs",
1576
+ required: false,
1577
+ advanced: true
1578
+ }), shownWhen("scheme", SIGNED_SCHEMES)),
1579
+ toleranceSeconds: withHints(Property.Number({
1580
+ displayName: "Replay window (seconds)",
1581
+ description: "Rejects a delivery signed longer ago than this, so a captured request expires. Default 300",
1582
+ required: false,
1583
+ advanced: true
1584
+ }), shownWhen("scheme", ["hmac-timestamped"])),
1585
+ algorithm: withHints(Property.StaticDropdown({
1586
+ displayName: "Hash",
1587
+ description: "How the digest was computed.",
1588
+ required: false,
1589
+ advanced: true,
1590
+ options: options([
1591
+ ["sha256", "SHA-256 (default)"],
1592
+ ["sha1", "SHA-1"],
1593
+ ["sha512", "SHA-512"]
1594
+ ])
1595
+ }), shownWhen("scheme", HMAC_SCHEMES)),
1596
+ encoding: withHints(Property.StaticDropdown({
1597
+ displayName: "Digest encoding",
1598
+ description: "How the digest is written.",
1599
+ required: false,
1600
+ advanced: true,
1601
+ options: options([["hex", "Hexadecimal (default)"], ["base64", "Base64"]])
1602
+ }), shownWhen("scheme", HMAC_SCHEMES)),
1603
+ prefix: withHints(Property.ShortText({
1604
+ displayName: "Signature label",
1605
+ description: "The text before the digest. Left empty it is the hash name and an equals sign, e.g. sha256=. Tick No label when the sender sends the digest alone",
1606
+ required: false,
1607
+ advanced: true
1608
+ }), {
1609
+ emptyChoice: "No label",
1610
+ ...shownWhen("scheme", ["hmac-prefixed"])
1611
+ }),
1612
+ dedupeField: Property.ShortText({
1613
+ displayName: "Event id field",
1614
+ description: "Where the sender puts its own event id, so a redelivery is accepted without a second run. A bare name reads a query param or a top-level body field; prefix with header: or body: to read a header or a nested path (header:x-delivery-id, body:data.object.id)",
1615
+ required: false,
1616
+ advanced: true
1617
+ }),
1618
+ dedupeTtlSeconds: Property.Number({
1619
+ displayName: "Dedupe window (seconds)",
1620
+ description: "How long an event id is remembered. Default 300",
1621
+ required: false,
1622
+ advanced: true
1623
+ }),
1624
+ challengeField: Property.ShortText({
1625
+ displayName: "Challenge field",
1626
+ description: "Echo this field back instead of running, for senders that verify the endpoint before registering it. Same header:/body: prefixes as the event id field",
1627
+ required: false,
1628
+ advanced: true
1629
+ }),
1630
+ responseMode: Property.StaticDropdown({
1631
+ displayName: "Response",
1632
+ description: "Waiting holds the sender's socket open for the whole run",
1633
+ required: false,
1634
+ advanced: true,
1635
+ defaultValue: "async",
1636
+ options: options([["async", "Answer immediately (202)"], ["sync", "Wait for the run (200)"]])
1637
+ }),
1638
+ responseStatus: Property.Number({
1639
+ displayName: "Success status",
1640
+ description: "Status returned on acceptance. Default 202 async, 200 sync",
1641
+ required: false,
1642
+ advanced: true
1643
+ })
1644
+ },
1645
+ sampleData: {
1646
+ method: "POST",
1647
+ path: "/",
1648
+ headers: { "content-type": "application/json" },
1649
+ queryParams: {},
1650
+ body: { event: "ping" }
1651
+ },
1652
+ ...hooks("webhook")
1653
+ });
1654
+ const manualTrigger = createTrigger({
1655
+ name: "manual",
1656
+ displayName: "Manual",
1657
+ description: "Fires only when something asks it to, with the fire mutation. The trigger to use for a workflow driven by a test or a script.",
1658
+ type: TriggerStrategy.MANUAL,
1659
+ requireAuth: false,
1660
+ props: {},
1661
+ sampleData: null,
1662
+ ...hooks("manual")
1663
+ });
1664
+ //#endregion
1665
+ //#region src/pieces/core/version.ts
1666
+ const CORE_PIECE_VERSION = "6.2.3-dev.31";
1667
+ //#endregion
1668
+ //#region src/pieces/core/index.ts
1669
+ const corePiece = createPiece({
1670
+ displayName: "Core",
1671
+ description: "The engine's own blocks: branching, assertions, and the triggers that belong to no service.",
1672
+ logoUrl: "",
1673
+ authors: ["powerhouse"],
1674
+ auth: void 0,
1675
+ categories: [PieceCategory.CORE],
1676
+ actions: [branchAction, assertAction],
1677
+ triggers: [
1678
+ scheduleTrigger,
1679
+ webhookTrigger,
1680
+ manualTrigger
1681
+ ]
1682
+ });
1683
+ //#endregion
1684
+ //#region src/pieces/builtin.ts
1685
+ const BUILTIN_PIECES = [{
1686
+ name: CORE_PIECE_NAME,
1687
+ version: CORE_PIECE_VERSION,
1688
+ piece: corePiece
1689
+ }];
1690
+ function builtinPiece(name) {
1691
+ return BUILTIN_PIECES.find((entry) => entry.name === name);
1692
+ }
1693
+ function isBuiltinPiece(name) {
1694
+ return builtinPiece(name) !== void 0;
1695
+ }
1696
+ function builtinLocalPieces() {
1697
+ return BUILTIN_PIECES.map(({ name, version }) => ({
1698
+ name,
1699
+ version
1700
+ }));
1701
+ }
1702
+ const descriptors = /* @__PURE__ */ new Map();
1703
+ function describeBuiltinPiece(builtin) {
1704
+ let descriptor = descriptors.get(builtin.name);
1705
+ if (!descriptor) {
1706
+ descriptor = buildDescriptor(builtin.piece, {
1707
+ packageName: builtin.name,
1708
+ version: builtin.version
1709
+ }, {
1710
+ routed: true,
1711
+ hostFed: true
966
1712
  });
1713
+ descriptors.set(builtin.name, descriptor);
1714
+ }
1715
+ return descriptor;
1716
+ }
1717
+ function blockPorts(block) {
1718
+ const builtin = builtinPiece(block.pieceName);
1719
+ if (builtin) {
1720
+ const descriptor = describeBuiltinPiece(builtin);
1721
+ return (block.kind === "trigger" ? descriptor.triggers : descriptor.actions).find((entry) => entry.name === block.name)?.ports;
1722
+ }
1723
+ return block.kind === "trigger" ? TRIGGER_PORTS : PIECE_ACTION_PORTS;
1724
+ }
1725
+ var UnknownBuiltinActionError = class extends Error {
1726
+ constructor(piece, action) {
1727
+ super(`${piece} has no action "${action}"`);
1728
+ this.name = "UnknownBuiltinActionError";
1729
+ }
1730
+ };
1731
+ async function runBuiltinAction(builtin, actionName, propsValue) {
1732
+ const action = getActions(builtin.piece)[actionName];
1733
+ if (!action || typeof action.run !== "function") throw new UnknownBuiltinActionError(builtin.name, actionName);
1734
+ const output = await action.run({ propsValue });
1735
+ return {
1736
+ output,
1737
+ ...isPorted(action) ? { port: action.portOf(output) } : {}
1738
+ };
1739
+ }
1740
+ //#endregion
1741
+ //#region src/pieces/engine/resolution.ts
1742
+ function pieceRecord(resolution) {
1743
+ if (!resolution?.resolved) return void 0;
1744
+ return {
1745
+ version: resolution.resolved.version,
1746
+ ...resolution.resolved.source ? { source: resolution.resolved.source } : {},
1747
+ match: resolution.match,
1748
+ ...resolution.note ? { note: resolution.note } : {}
1749
+ };
1750
+ }
1751
+ function blockLabel(block) {
1752
+ const version = "pieceVersion" in block ? `@${block.pieceVersion}` : "";
1753
+ return `${block.pieceName}${version} ${block.kind} "${block.name}"`;
1754
+ }
1755
+ var UnknownBlockError = class extends Error {
1756
+ constructor(block, detail = `No executor registered for ${blockLabel(block)}`) {
1757
+ super(detail);
1758
+ this.name = "UnknownBlockError";
1759
+ }
1760
+ };
1761
+ function unpinnedNote(block) {
1762
+ return `${block.pieceName} ${block.kind} "${block.name}" pins "${block.pieceVersion}", which is not an exact semver version`;
1763
+ }
1764
+ function missingError(resolution) {
1765
+ return new UnknownBlockError(resolution.requested, resolution.note);
1766
+ }
1767
+ const RESOLUTION = Symbol.for("reactor-workflow.block-resolution");
1768
+ function withResolution(error, resolution) {
1769
+ if (resolution && error !== null && typeof error === "object") error[RESOLUTION] = resolution;
1770
+ return error;
1771
+ }
1772
+ function resolutionOf(error) {
1773
+ if (error === null || typeof error !== "object") return void 0;
1774
+ return error[RESOLUTION];
1775
+ }
1776
+ //#endregion
1777
+ //#region src/pieces/engine/blocks.ts
1778
+ var TriggerBlockAsStepError = class extends Error {
1779
+ constructor(block) {
1780
+ super(`${blockLabel(block)} is a trigger and cannot run as a workflow step`);
1781
+ this.name = "TriggerBlockAsStepError";
967
1782
  }
968
1783
  };
969
1784
  const ATTACHMENT_REF = /^attachment:\/\//i;
@@ -1108,46 +1923,30 @@ const REACTOR_PORT_PIECE = "@powerhousedao/piece-reactor";
1108
1923
  function servesReactorPort(packageName) {
1109
1924
  return packageName === REACTOR_PORT_PIECE;
1110
1925
  }
1111
- const TRIGGER_FRAGMENT = "trigger:";
1112
- function blockTypeParts(blockType) {
1113
- const separator = blockType.lastIndexOf("#");
1114
- if (separator <= 0) return void 0;
1115
- const packageSpec = blockType.slice(0, separator);
1116
- const fragment = blockType.slice(separator + 1);
1117
- const isTrigger = fragment.startsWith(TRIGGER_FRAGMENT);
1118
- const name = isTrigger ? fragment.slice(8) : fragment;
1119
- if (!name) return void 0;
1120
- const kind = isTrigger ? "trigger" : "action";
1121
- const versionAt = packageSpec.indexOf("@", 1);
1122
- if (versionAt > 0) return {
1123
- packageName: packageSpec.slice(0, versionAt),
1124
- version: packageSpec.slice(versionAt + 1),
1125
- kind,
1126
- name
1127
- };
1926
+ function isHostBound(packageName) {
1927
+ return servesReactorPort(packageName) || isBuiltinPiece(packageName);
1928
+ }
1929
+ function resolvedBlock(resolution) {
1930
+ const { requested, resolved } = resolution;
1931
+ if (!resolved || resolution.match === "missing") return void 0;
1128
1932
  return {
1129
- packageName: packageSpec,
1130
- kind,
1131
- name
1933
+ packageName: requested.pieceName,
1934
+ version: resolved.version,
1935
+ ...resolved.source ? { source: resolved.source } : {},
1936
+ kind: requested.kind,
1937
+ name: requested.name
1132
1938
  };
1133
1939
  }
1134
- function parseBlockType(blockType, packages = {}) {
1135
- const parts = blockTypeParts(blockType);
1136
- if (!parts) return void 0;
1137
- const { packageName, kind, name } = parts;
1138
- if (parts.version !== void 0) return {
1139
- packageName,
1140
- version: parts.version,
1141
- kind,
1142
- name
1940
+ function pinnedResolution(block) {
1941
+ if (!isExactVersion(block.pieceVersion)) return {
1942
+ requested: block,
1943
+ match: "missing",
1944
+ note: unpinnedNote(block)
1143
1945
  };
1144
- const version = packages[packageName];
1145
- if (!version) return void 0;
1146
1946
  return {
1147
- packageName,
1148
- version,
1149
- kind,
1150
- name
1947
+ requested: block,
1948
+ resolved: { version: block.pieceVersion },
1949
+ match: "exact"
1151
1950
  };
1152
1951
  }
1153
1952
  var ActivepiecesBlockExecutor = class {
@@ -1166,26 +1965,38 @@ var ActivepiecesBlockExecutor = class {
1166
1965
  } else if (supplied) return supplied;
1167
1966
  return this.own ??= new PieceWorker();
1168
1967
  }
1169
- packages() {
1170
- const supplied = this.options.packages;
1171
- return Promise.resolve(typeof supplied === "function" ? supplied() : supplied ?? {});
1172
- }
1173
1968
  async execute(execution) {
1174
- const parsed = parseBlockType(execution.blockType, await this.packages()) ?? await this.options.resolveBlockType?.(execution.blockType);
1175
- if (!parsed) throw new UnknownBlockTypeError(execution.blockType);
1176
- if (parsed.kind !== "action") throw new TriggerBlockAsStepError(execution.blockType);
1969
+ const resolution = this.options.resolveBlock ? await this.options.resolveBlock(execution.block) : pinnedResolution(execution.block);
1970
+ const parsed = resolvedBlock(resolution);
1971
+ if (!parsed) throw missingError(resolution);
1972
+ if (parsed.kind !== "action") throw new TriggerBlockAsStepError(execution.block);
1973
+ try {
1974
+ const builtin = builtinPiece(parsed.packageName);
1975
+ return {
1976
+ ...builtin ? await runBuiltinAction(builtin, parsed.name, execution.config) : await this.run(execution, parsed),
1977
+ resolution
1978
+ };
1979
+ } catch (error) {
1980
+ throw withResolution(error, resolution);
1981
+ }
1982
+ }
1983
+ async run(execution, parsed) {
1177
1984
  const stagingDir = this.options.stagingRoot ? path.join(this.options.stagingRoot, randomUUID()) : void 0;
1178
- let redactValues = [];
1985
+ const runSecrets = execution.redactValues ?? [];
1986
+ let redactValues = [...runSecrets];
1179
1987
  try {
1180
- const piece = await this.resolver.resolve(parsed.packageName, parsed.version);
1988
+ const piece = await this.resolver.resolve({
1989
+ name: parsed.packageName,
1990
+ version: parsed.version,
1991
+ ...parsed.source ? { source: parsed.source } : {}
1992
+ });
1181
1993
  const connection = await this.resolveConnection(execution.connectionId, {
1182
- blockType: execution.blockType,
1183
1994
  piecePackage: parsed.packageName,
1184
1995
  stepId: execution.step.id,
1185
1996
  stepKey: execution.step.key
1186
1997
  });
1187
1998
  const auth = connection?.auth;
1188
- redactValues = connection?.secretValues ?? [];
1999
+ redactValues = [...runSecrets, ...connection?.secretValues ?? []];
1189
2000
  const timeoutMs = execution.step.timeoutSeconds ? execution.step.timeoutSeconds * 1e3 : this.options.defaultTimeoutMs;
1190
2001
  const stagedInputs = await this.stageInputs(execution.config, stagingDir);
1191
2002
  const pieceStore = this.options.pieceStore;
@@ -1202,6 +2013,7 @@ var ActivepiecesBlockExecutor = class {
1202
2013
  stepName: execution.step.key
1203
2014
  },
1204
2015
  ...redactValues.length > 0 ? { redactValues } : {},
2016
+ ...this.options.stepTest?.() ? { stepTest: true } : {},
1205
2017
  ...stagingDir ? { stagingDir } : {},
1206
2018
  ...stagedInputs ? { stagedInputs } : {},
1207
2019
  ...pieceStore ? { durableStore: true } : {},
@@ -1285,20 +2097,107 @@ var ActivepiecesBlockExecutor = class {
1285
2097
  var CompositeBlockExecutor = class {
1286
2098
  pieces;
1287
2099
  handlers;
1288
- core = new CoreBlockExecutor();
1289
2100
  constructor(pieces, handlers = {}) {
1290
2101
  this.pieces = pieces;
1291
2102
  this.handlers = handlers;
1292
2103
  }
1293
2104
  execute(execution) {
1294
- const handler = this.handlers[execution.blockType];
2105
+ const handler = this.handlers[blockKey(execution.block)];
1295
2106
  if (handler) return handler.execute(execution);
1296
- if (CoreBlockExecutor.handles(execution.blockType)) return this.core.execute(execution);
1297
2107
  return this.pieces.execute(execution);
1298
2108
  }
1299
2109
  };
1300
2110
  //#endregion
2111
+ //#region src/pieces/engine/dynamic-props.ts
2112
+ var DynamicPropertiesError = class extends Error {
2113
+ prop;
2114
+ missing;
2115
+ constructor(message, prop, missing) {
2116
+ super(message);
2117
+ this.prop = prop;
2118
+ this.missing = missing;
2119
+ this.name = "DynamicPropertiesError";
2120
+ }
2121
+ };
2122
+ function isRecord(value) {
2123
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2124
+ }
2125
+ function requiredChildren(schema) {
2126
+ return (Array.isArray(schema) ? schema.filter(isRecord).filter((entry) => typeof entry.name === "string").map((entry) => [entry.name, entry]) : isRecord(schema) ? Object.entries(schema) : []).filter(([, prop]) => isRecord(prop) && prop.required === true).map(([name, prop]) => {
2127
+ const displayName = prop.displayName;
2128
+ return {
2129
+ name,
2130
+ label: typeof displayName === "string" && displayName !== "" ? `${displayName} (${name})` : name
2131
+ };
2132
+ });
2133
+ }
2134
+ function isBlank(value) {
2135
+ return value === void 0 || value === null || value === "";
2136
+ }
2137
+ /** Throws a DynamicPropertiesError naming the first prop whose value does not
2138
+ * satisfy its resolved children. Settings without a schema are ignored. */
2139
+ function checkDynamicProperties(config, settings) {
2140
+ if (!settings || settings.length === 0) return;
2141
+ const values = isRecord(config) ? config : {};
2142
+ for (const setting of settings) {
2143
+ if (setting.schema === void 0 || setting.schema === null) continue;
2144
+ const raw = values[setting.prop];
2145
+ if (!isBlank(raw) && !isRecord(raw)) throw new DynamicPropertiesError(`Property "${setting.prop}" must be an object of fields, received ${Array.isArray(raw) ? "array" : typeof raw}`, setting.prop, []);
2146
+ const value = isRecord(raw) ? raw : {};
2147
+ const missing = requiredChildren(setting.schema).filter((child) => isBlank(value[child.name]));
2148
+ if (missing.length > 0) throw new DynamicPropertiesError(`Property "${setting.prop}" is missing required fields: ${missing.map((child) => child.label).join(", ")}`, setting.prop, missing.map((child) => child.name));
2149
+ }
2150
+ }
2151
+ //#endregion
2152
+ //#region src/pieces/engine/canonical.ts
2153
+ function canonicalJson(value) {
2154
+ return JSON.stringify(sortKeys(value) ?? null);
2155
+ }
2156
+ function sortKeys(value) {
2157
+ if (Array.isArray(value)) return value.map(sortKeys);
2158
+ if (value === null || typeof value !== "object") return value;
2159
+ const record = value;
2160
+ return Object.fromEntries(Object.keys(record).sort().filter((key) => record[key] !== void 0).map((key) => [key, sortKeys(record[key])]));
2161
+ }
2162
+ function hashOf(...parts) {
2163
+ const hash = createHash("sha256");
2164
+ for (const part of parts) hash.update(part).update("\0");
2165
+ return hash.digest("hex").slice(0, 16);
2166
+ }
2167
+ function stepConfigHash(step) {
2168
+ const schemas = (step.propertySettings ?? []).filter((setting) => setting.schema !== null && setting.schema !== void 0).map((setting) => ({
2169
+ prop: setting.prop,
2170
+ schema: setting.schema
2171
+ }));
2172
+ return hashOf(step.pieceName, step.pieceVersion, step.actionName, canonicalJson({
2173
+ config: step.config ?? {},
2174
+ connectionId: step.connectionId ?? null,
2175
+ propertySettings: schemas
2176
+ }));
2177
+ }
2178
+ //#endregion
1301
2179
  //#region src/pieces/engine/coordinator.ts
2180
+ function deadPortWarnings(definition, declaredPorts) {
2181
+ const blocks = new Map(definition.steps.map((step) => [step.id, {
2182
+ key: step.key,
2183
+ block: stepBlock(step)
2184
+ }]));
2185
+ if (definition.trigger) blocks.set(definition.trigger.id, {
2186
+ key: "trigger",
2187
+ block: triggerBlock(definition.trigger)
2188
+ });
2189
+ return undeclaredPortEdges(definition.edges, (id) => {
2190
+ const source = blocks.get(id);
2191
+ return source ? declaredPorts(source.block) : void 0;
2192
+ }).map((edge) => {
2193
+ const source = blocks.get(edge.from);
2194
+ const target = blocks.get(edge.to)?.key ?? edge.to;
2195
+ return `Edge from "${source.key}" to "${target}" leaves on port "${edge.port}", which ${blockLabel(source.block)} never takes`;
2196
+ });
2197
+ }
2198
+ function withPiece(piece) {
2199
+ return piece ? { piece } : {};
2200
+ }
1302
2201
  function errorMessage(error) {
1303
2202
  if (error instanceof Error) return error.message;
1304
2203
  return String(error);
@@ -1308,9 +2207,10 @@ function journaled(value, values) {
1308
2207
  }
1309
2208
  async function runWorkflow(options) {
1310
2209
  const { definition, executor } = options;
2210
+ const runSecrets = options.redactValues ?? [];
1311
2211
  const scope = {
1312
2212
  trigger: { payload: options.triggerPayload },
1313
- steps: {},
2213
+ steps: { ...options.priorSteps },
1314
2214
  variables: Object.fromEntries((definition.variables ?? []).map((v) => [v.key, v.value ?? null]))
1315
2215
  };
1316
2216
  const records = /* @__PURE__ */ new Map();
@@ -1327,7 +2227,13 @@ async function runWorkflow(options) {
1327
2227
  const decideOutgoing = (sourceId, port) => {
1328
2228
  for (const edge of definition.edges) {
1329
2229
  if (edge.from !== sourceId) continue;
1330
- const taken = port !== void 0 && edge.port === port && (!edge.condition || evaluateCondition(edge.condition, scope));
2230
+ let taken = port !== void 0 && edge.port === port;
2231
+ if (taken && edge.condition) try {
2232
+ taken = evaluateCondition(edge.condition, scope);
2233
+ } catch (error) {
2234
+ taken = false;
2235
+ runFailed ??= `Condition of edge "${edge.id}": ${errorMessage(error)}`;
2236
+ }
1331
2237
  edgeDecisions.set(edge.id, taken);
1332
2238
  }
1333
2239
  };
@@ -1338,7 +2244,8 @@ async function runWorkflow(options) {
1338
2244
  records.set(step.id, {
1339
2245
  stepId: step.id,
1340
2246
  key: step.key,
1341
- blockType: step.blockType,
2247
+ pieceName: step.pieceName,
2248
+ blockName: step.actionName,
1342
2249
  status: "SKIPPED"
1343
2250
  });
1344
2251
  decideOutgoing(step.id, void 0);
@@ -1348,13 +2255,33 @@ async function runWorkflow(options) {
1348
2255
  records.set(step.id, {
1349
2256
  stepId: step.id,
1350
2257
  key: step.key,
1351
- blockType: step.blockType,
2258
+ pieceName: step.pieceName,
2259
+ blockName: step.actionName,
1352
2260
  status: "FAILED",
1353
2261
  error
1354
2262
  });
1355
2263
  runFailed = error;
1356
2264
  };
2265
+ const passStep = async (step) => {
2266
+ const record = {
2267
+ stepId: step.id,
2268
+ key: step.key,
2269
+ pieceName: step.pieceName,
2270
+ blockName: step.actionName,
2271
+ status: "SKIPPED",
2272
+ output: null,
2273
+ port: "next"
2274
+ };
2275
+ records.set(step.id, record);
2276
+ await journal(record);
2277
+ scope.steps[step.key] = { output: null };
2278
+ decideOutgoing(step.id, "next");
2279
+ };
1357
2280
  const executeStep = async (step) => {
2281
+ if (step.skip === true) {
2282
+ await passStep(step);
2283
+ return;
2284
+ }
1358
2285
  const replay = options.completedSteps?.get(step.id);
1359
2286
  if (replay) {
1360
2287
  if (containsRedactedMarker(replay.output)) {
@@ -1365,10 +2292,12 @@ async function runWorkflow(options) {
1365
2292
  const record = {
1366
2293
  stepId: step.id,
1367
2294
  key: step.key,
1368
- blockType: step.blockType,
2295
+ pieceName: step.pieceName,
2296
+ blockName: step.actionName,
1369
2297
  status: "REPLAYED",
1370
2298
  output: replay.output,
1371
- port
2299
+ port,
2300
+ configHash: stepConfigHash(step)
1372
2301
  };
1373
2302
  records.set(step.id, record);
1374
2303
  await journal(record);
@@ -1376,43 +2305,53 @@ async function runWorkflow(options) {
1376
2305
  decideOutgoing(step.id, port);
1377
2306
  return;
1378
2307
  }
1379
- const input = resolveExpressions(step.config, scope);
1380
2308
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2309
+ let input;
1381
2310
  try {
2311
+ input = resolveExpressions(step.config, scope);
2312
+ checkDynamicProperties(input, step.propertySettings);
1382
2313
  const result = await executor.execute({
1383
- blockType: step.blockType,
2314
+ block: stepBlock(step),
1384
2315
  config: input,
1385
2316
  connectionId: step.connectionId,
1386
- step
2317
+ step,
2318
+ ...runSecrets.length > 0 ? { redactValues: runSecrets } : {}
1387
2319
  });
1388
2320
  const port = result.port ?? "next";
2321
+ const values = [...runSecrets, ...result.redactValues ?? []];
1389
2322
  const record = {
1390
2323
  stepId: step.id,
1391
2324
  key: step.key,
1392
- blockType: step.blockType,
2325
+ pieceName: step.pieceName,
2326
+ blockName: step.actionName,
1393
2327
  status: "SUCCEEDED",
1394
- input: journaled(input, result.redactValues),
1395
- output: journaled(result.output, result.redactValues),
2328
+ input: journaled(input, values),
2329
+ output: journaled(result.output, values),
1396
2330
  port,
1397
2331
  startedAt,
1398
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
2332
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2333
+ ...withPiece(pieceRecord(result.resolution)),
2334
+ configHash: stepConfigHash(step)
1399
2335
  };
1400
2336
  records.set(step.id, record);
1401
2337
  await journal(record);
1402
2338
  scope.steps[step.key] = { output: result.output };
1403
2339
  decideOutgoing(step.id, port);
1404
2340
  } catch (error) {
1405
- const values = secretsFor(error);
2341
+ const values = [...runSecrets, ...secretsFor(error)];
1406
2342
  const detail = redactMessage(errorMessage(error), { values });
1407
2343
  const record = {
1408
2344
  stepId: step.id,
1409
2345
  key: step.key,
1410
- blockType: step.blockType,
2346
+ pieceName: step.pieceName,
2347
+ blockName: step.actionName,
1411
2348
  status: "FAILED",
1412
2349
  input: journaled(input, values),
1413
2350
  error: detail,
1414
2351
  startedAt,
1415
- endedAt: (/* @__PURE__ */ new Date()).toISOString()
2352
+ endedAt: (/* @__PURE__ */ new Date()).toISOString(),
2353
+ ...withPiece(pieceRecord(resolutionOf(error))),
2354
+ configHash: stepConfigHash(step)
1416
2355
  };
1417
2356
  records.set(step.id, record);
1418
2357
  await journal(record);
@@ -1443,23 +2382,37 @@ async function runWorkflow(options) {
1443
2382
  }
1444
2383
  for (const step of definition.steps) if (!records.has(step.id)) skipStep(step);
1445
2384
  const steps = definition.steps.map((step) => records.get(step.id));
2385
+ const warnings = options.declaredPorts ? deadPortWarnings(definition, options.declaredPorts) : [];
2386
+ const noted = warnings.length > 0 ? { warnings } : {};
1446
2387
  return runFailed ? {
1447
2388
  status: "FAILED",
1448
2389
  steps,
1449
- error: runFailed
2390
+ error: runFailed,
2391
+ ...noted
1450
2392
  } : {
1451
2393
  status: "SUCCEEDED",
1452
- steps
2394
+ steps,
2395
+ ...noted
1453
2396
  };
1454
2397
  }
1455
2398
  //#endregion
1456
2399
  //#region src/reactor/piece-registry.ts
1457
2400
  const logger = childLogger(["workflow", "piece-registry"]);
2401
+ function pieceLocation(piece) {
2402
+ return piece.entryPath ?? piece.bundleDir ?? piece.entryUrl ?? "?";
2403
+ }
1458
2404
  var PieceRegistry = class {
1459
2405
  byName = /* @__PURE__ */ new Map();
1460
2406
  setPieces(pieces) {
1461
2407
  const found = /* @__PURE__ */ new Map();
1462
- for (const piece of pieces) if (!found.has(piece.name)) found.set(piece.name, piece);
2408
+ for (const piece of pieces) {
2409
+ const held = found.get(piece.name);
2410
+ if (!held) {
2411
+ found.set(piece.name, piece);
2412
+ continue;
2413
+ }
2414
+ logger.warn("Piece @name is shipped twice; keeping @kept, ignoring @ignored", piece.name, `${held.version} (${pieceLocation(held)})`, `${piece.version} (${pieceLocation(piece)})`);
2415
+ }
1463
2416
  this.byName = found;
1464
2417
  const names = [...found.keys()].join(", ");
1465
2418
  const held = [...found.values()].filter((piece) => piece.entryPath ?? piece.bundleDir).length;
@@ -1482,7 +2435,13 @@ var PieceRegistry = class {
1482
2435
  }
1483
2436
  };
1484
2437
  const packagePieces = new PieceRegistry();
2438
+ function installedPiece(name) {
2439
+ return builtinLocalPieces().find((piece) => piece.name === name) ?? packagePieces.lookup(name);
2440
+ }
2441
+ function installedPieces() {
2442
+ return [...builtinLocalPieces(), ...packagePieces.entries().filter((piece) => !isBuiltinPiece(piece.name))];
2443
+ }
1485
2444
  //#endregion
1486
- export { setPieceRegistryUrl as A, PieceWorkerError as C, ensurePieceBundle as D, pieceModuleRef as E, fetchPieceBundle as O, PieceWorker as S, localFirstResolver as T, SecretDeletedError as _, CompositeBlockExecutor as a, secretRefFromId as b, parseBlockType as c, storeHandlers as d, BoundConnectionResolver as f, InMemorySecretProvider as g, shapeConnection as h, ActivepiecesBlockExecutor as i, pieceRegistrySource as k, reactorHandlers as l, declaredConnectionIds as m, packagePieces as n, REACTOR_PORT_PIECE as o, StaticConnectionResolver as p, runWorkflow as r, blockTypeParts as s, PieceRegistry as t, servesReactorPort as u, SecretNotFoundError as v, PieceWorkerTimeoutError as w, PieceWorkerPool as x, parseSecretRef as y };
2445
+ export { expressionsIn as A, PieceWorker as B, describeBuiltinPiece as C, StaticConnectionResolver as D, BoundConnectionResolver as E, parseSecretRef as F, sourcedResolver as G, PieceWorkerTimeoutError as H, secretRefFromId as I, npmRegistryBaseUrl as J, ensurePieceBundle as K, stepBlock as L, InMemorySecretProvider as M, SecretDeletedError as N, declaredConnectionIds as O, SecretNotFoundError as P, triggerBlock as R, builtinPiece as S, CORE_PIECE_VERSION as T, bundleResolver as U, PieceWorkerError as V, pieceModuleRef as W, setPieceRegistryUrl as X, pieceRegistrySource as Y, servesReactorPort as _, runWorkflow as a, unpinnedNote as b, stepConfigHash as c, ActivepiecesBlockExecutor as d, CompositeBlockExecutor as f, resolvedBlock as g, reactorHandlers as h, packagePieces as i, resolveExpressions as j, shapeConnection as k, DynamicPropertiesError as l, isHostBound as m, installedPiece as n, canonicalJson as o, REACTOR_PORT_PIECE as p, fetchPieceBundle as q, installedPieces as r, hashOf as s, PieceRegistry as t, checkDynamicProperties as u, storeHandlers as v, CORE_PIECE_NAME as w, blockPorts as x, blockLabel as y, PieceWorkerPool as z };
1487
2446
 
1488
- //# sourceMappingURL=piece-registry-CAS4wiSA.js.map
2447
+ //# sourceMappingURL=piece-registry-Du1_VVIg.js.map