@powerhousedao/reactor-workflow 6.2.3-dev.24 → 6.2.3-dev.26

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 +1 @@
1
- {"version":3,"file":"worker-entry.js","names":[],"sources":["../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/reactor.ts","../src/pieces/activepieces/context/check.ts","../src/pieces/activepieces/context/normalize.ts","../src/pieces/activepieces/context/props.ts","../src/pieces/activepieces/context/remote-store.ts","../src/pieces/activepieces/context/remote-output.ts","../src/pieces/activepieces/worker/logs.ts","../src/pieces/activepieces/worker/entry.ts"],"sourcesContent":["// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport type { HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip. Ten seconds is already pathological;\n// the step's own timeout is the outer bound and kills the worker outright.\nconst DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = DEFAULT_HOST_CALL_TIMEOUT_MS,\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new HostCallTimeoutError(method, timeoutMs));\n }, timeoutMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// `ctx.reactor` — the one way piece code reaches the reactor it runs inside.\n\n// Pieces are isolated from the host on purpose, so this is not a client: it is\n// the same call channel `ctx.store` uses (doc 08 §10), and every method is a\n// round trip the host answers. The host installs it only for a piece that came\n// from an installed reactor package; a bundle fetched from a registry gets the\n// throwing stub instead, and finds out by name that it has no reactor.\nimport { callHost } from \"../worker/host-call.js\";\nimport type {\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorService,\n} from \"@powerhousedao/pieces-framework\";\nimport {\n REACTOR_CREATE,\n REACTOR_EXECUTE,\n REACTOR_FIND,\n REACTOR_GET,\n REACTOR_MODEL,\n REACTOR_MODELS,\n} from \"../worker/protocol.js\";\n\n// The service contract and its input/output shapes live in the framework, so a\n// piece and the host it calls are typed against one declaration.\nexport type {\n ReactorActionInput,\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelActionSchema,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorService,\n} from \"@powerhousedao/pieces-framework\";\n\n// The worker's half: every method is one host call, named so a failure reads\n// as the operation the piece asked for.\nexport class RemoteReactorService implements ReactorService {\n models(): Promise<ReactorModelSummary[]> {\n return callHost<ReactorModelSummary[]>(REACTOR_MODELS, {});\n }\n\n model(documentType: string): Promise<ReactorModelDetail> {\n return callHost<ReactorModelDetail>(REACTOR_MODEL, { documentType });\n }\n\n get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_GET, input);\n }\n\n find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n return callHost<ReactorDocumentSummary[]>(REACTOR_FIND, input);\n }\n\n create(input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_CREATE, input);\n }\n\n execute(input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_EXECUTE, input);\n }\n}\n","// Context handed to a piece's auth.validate and auth.getConnectionIdentifier:\n// `{ auth, server }`, with auth as the flat property value.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { AuthValidationServerContext } from \"@powerhousedao/pieces-framework\";\n\nexport interface CheckConnectionContextOptions {\n auth?: unknown;\n // apiUrl / publicUrl when the host serves them; mintOidcToken always throws,\n // since no reactor mints tokens for a piece's connection check.\n server?: Omit<AuthValidationServerContext, \"mintOidcToken\">;\n onTouch?: (member: string) => void;\n}\n\nexport interface BuiltApCheckConnectionContext {\n auth: unknown;\n server: AuthValidationServerContext;\n}\n\nexport interface CheckConnectionContextHandle {\n context: BuiltApCheckConnectionContext;\n // Top-level members the check read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildCheckConnectionContext(\n options: CheckConnectionContextOptions = {},\n): CheckConnectionContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n auth: options.auth,\n server: options.server\n ? {\n ...options.server,\n mintOidcToken: throwingStub(\"server.mintOidcToken\"),\n }\n : throwingStub(\"server\"),\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApCheckConnectionContext,\n touched,\n };\n}\n","// Run-time coercion of stored config values into the shapes pieces expect: the\n// engine's own property processors, with our file hydration in front of theirs.\nimport type { PieceProperty } from \"@powerhousedao/pieces-framework\";\nimport {\n arrayZipperProcessor,\n processors,\n validateProperty,\n type ProcessorFn,\n} from \"@powerhousedao/pieces-framework/host\";\nimport type { ApProperty } from \"../types.js\";\nimport {\n assertWithinLimit,\n DEFAULT_MAX_FILE_BYTES,\n maxFileBytes,\n} from \"./limits.js\";\n\n// Framework ApFile (filename, data, extension, base64) as a plain object so\n// it survives IPC and structured cloning.\nexport interface ApFileValue {\n filename: string;\n extension?: string;\n base64: string;\n data: Buffer;\n}\n\nexport interface FetchedFile {\n data: Buffer;\n filename?: string;\n contentType?: string;\n}\n\nexport interface NormalizeOptions {\n // Resolves a URL-valued FILE prop; defaults to fetch() with a size cap.\n fetchFile?: (url: string) => Promise<FetchedFile>;\n // Resolves a reference-valued FILE prop (attachment:// or apfile://). The\n // worker resolves these from files the host staged on disk, so the bytes\n // never cross IPC.\n resolveRef?: (ref: string) => Promise<FetchedFile>;\n}\n\n// Re-exported for compatibility; the ceiling itself lives in limits.ts so the\n// inbound and outbound paths cannot drift apart.\nexport const MAX_FILE_BYTES = DEFAULT_MAX_FILE_BYTES;\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// A FILE prop whose value is a reference the host has to resolve.\nconst FILE_REF = /^(?:attachment|apfile):\\/\\//i;\n\nexport class FileFetchError extends Error {\n constructor(url: string, reason: string) {\n super(`Could not fetch FILE prop \"${url}\": ${reason}`);\n this.name = \"FileFetchError\";\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst DATA_URI = /^data:([^;,]*)((?:;[^;,]*)*),([\\s\\S]*)$/;\n\nfunction extensionOf(filename: string): string | undefined {\n const dot = filename.lastIndexOf(\".\");\n return dot > 0 && dot < filename.length - 1\n ? filename.slice(dot + 1)\n : undefined;\n}\n\nconst MIME_EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"application/pdf\": \"pdf\",\n \"application/json\": \"json\",\n \"text/plain\": \"txt\",\n \"text/csv\": \"csv\",\n};\n\nfunction toFileValue(\n data: Buffer,\n filename: string | undefined,\n contentType: string | undefined,\n): ApFileValue {\n const mime = contentType?.split(\";\")[0].trim().toLowerCase();\n const mimeExtension = mime ? MIME_EXTENSIONS[mime] : undefined;\n const name =\n filename && filename !== \"\"\n ? filename\n : `file${mimeExtension ? `.${mimeExtension}` : \"\"}`;\n const extension = extensionOf(name) ?? mimeExtension;\n return {\n filename: name,\n ...(extension ? { extension } : {}),\n base64: data.toString(\"base64\"),\n data,\n };\n}\n\nfunction filenameFromDisposition(header: string | null): string | undefined {\n if (!header) return undefined;\n const utf8 = /filename\\*=(?:UTF-8'')?([^;]+)/i.exec(header);\n if (utf8) {\n try {\n return decodeURIComponent(utf8[1].trim().replace(/^\"|\"$/g, \"\"));\n } catch {\n // fall through to the plain form\n }\n }\n const plain = /filename=\"?([^\";]+)\"?/i.exec(header);\n return plain ? plain[1].trim() : undefined;\n}\n\nasync function defaultFetchFile(url: string): Promise<FetchedFile> {\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!response.ok) throw new FileFetchError(url, `HTTP ${response.status}`);\n const limit = maxFileBytes();\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > limit) {\n throw new FileFetchError(url, `${declared} bytes exceeds ${limit}`);\n }\n const data = Buffer.from(await response.arrayBuffer());\n if (data.byteLength > limit) {\n throw new FileFetchError(url, `${data.byteLength} bytes exceeds ${limit}`);\n }\n let filename = filenameFromDisposition(\n response.headers.get(\"content-disposition\"),\n );\n if (!filename) {\n const segment = new URL(url).pathname.split(\"/\").filter(Boolean).pop();\n if (segment) filename = decodeURIComponent(segment);\n }\n return {\n data,\n filename,\n contentType: response.headers.get(\"content-type\") ?? undefined,\n };\n}\n\nfunction isFileShaped(value: unknown): value is ApFileValue {\n return (\n isRecord(value) &&\n typeof value.filename === \"string\" &&\n (typeof value.base64 === \"string\" || Buffer.isBuffer(value.data))\n );\n}\n\n// URL or data URI → ApFile shape; already-shaped objects are completed\n// (data/base64 derived from each other); anything else passes through.\nexport async function toApFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isFileShaped(value)) {\n const data = Buffer.isBuffer(value.data)\n ? value.data\n : Buffer.from(value.base64, \"base64\");\n // The cap applies to every branch, not just the fetched one: an oversized\n // data URI or file-shaped object would otherwise slip past it.\n assertWithinLimit(data.byteLength);\n const extension = value.extension ?? extensionOf(value.filename);\n return {\n ...value,\n ...(extension ? { extension } : {}),\n base64:\n typeof value.base64 === \"string\"\n ? value.base64\n : data.toString(\"base64\"),\n data,\n };\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const [, mime, params, payload] = dataUri;\n const isBase64 = /;base64/i.test(params);\n const data = isBase64\n ? Buffer.from(payload, \"base64\")\n : Buffer.from(decodeURIComponent(payload), \"utf8\");\n assertWithinLimit(data.byteLength);\n const nameParam = /;name=([^;]+)/i.exec(params)?.[1];\n return toFileValue(\n data,\n nameParam ? decodeURIComponent(nameParam) : undefined,\n mime || undefined,\n );\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.resolveRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const resolved = await options.resolveRef(trimmed);\n assertWithinLimit(resolved.data.byteLength);\n return toFileValue(resolved.data, resolved.filename, resolved.contentType);\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const fetched = await (options.fetchFile ?? defaultFetchFile)(trimmed);\n return toFileValue(fetched.data, fetched.filename, fetched.contentType);\n }\n return value;\n}\n\n// ARRAY has no entry in the processor table: the engine zips an object of\n// parallel arrays into rows itself, then processes each row's own props.\nasync function normalizeArray(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions,\n): Promise<unknown> {\n const fields = prop.properties;\n if (!fields) return value;\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, value);\n if (!Array.isArray(zipped)) return value;\n return Promise.all(\n (zipped as unknown[]).map((item) =>\n isRecord(item) ? normalizePropsValue(fields, item, options) : item,\n ),\n );\n}\n\n// An ApFile is a class instance whose base64 is a prototype getter, and no\n// structured clone carries either; flatten it at the boundary (see ApFileValue).\nfunction plainFile(value: unknown): unknown {\n if (!isRecord(value) || typeof value.filename !== \"string\") return value;\n const { data } = value;\n if (!Buffer.isBuffer(data)) return value;\n const extension =\n typeof value.extension === \"string\"\n ? value.extension\n : extensionOf(value.filename);\n return {\n filename: value.filename,\n ...(extension ? { extension } : {}),\n base64:\n typeof value.base64 === \"string\" ? value.base64 : data.toString(\"base64\"),\n data,\n };\n}\n\nconst table = processors as Record<string, ProcessorFn | undefined>;\n\n// The types whose processor failing means \"not JSON\", not \"not usable\".\nconst JSON_LIKE = new Set([\"JSON\", \"OBJECT\"]);\n\nexport async function normalizeValue(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (value === undefined || value === null) return value;\n if (prop.type === \"ARRAY\") return normalizeArray(prop, value, options);\n if (prop.type === \"FILE\") {\n // Our hydration owns the forms the engine's own processor cannot resolve:\n // attachment and apfile refs, the size cap, and a host-injected fetcher.\n const hydrated = await toApFile(value, options);\n if (typeof hydrated !== \"string\") return hydrated;\n return plainFile(await table.FILE?.(prop as PieceProperty, hydrated));\n }\n const type = prop.type;\n const processor = type ? table[type] : undefined;\n if (!processor) return value;\n const processed = plainFile(await processor(prop as PieceProperty, value));\n // Every other type keeps its promise to the piece: a DATE_TIME prop is an\n // ISO string or nothing, a NUMBER is a number or NaN. JSON is the exception,\n // because the thing most often routed into one is a model's answer, and a\n // model wraps its object in prose. jsonProcessor answers undefined for that,\n // which would drop the value entirely — so hand back what the author wrote\n // and let the piece parse it. The pieces that take model output this way\n // carry their own tolerant parsing for exactly this case.\n if (processed === undefined && type && JSON_LIKE.has(type) && value !== \"\") {\n return value;\n }\n return processed;\n}\n\n// Normalises every configured value with a matching prop schema; keys\n// without a schema (or props without a value) pass through untouched.\nexport async function normalizePropsValue(\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const out: Record<string, unknown> = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!(name in out) || !isRecord(prop)) continue;\n const normalized = await normalizeValue(prop, out[name], options);\n if (normalized === undefined) delete out[name];\n else out[name] = normalized;\n }\n return out;\n}\n\n// Upstream's error shape: a field's messages, or an ARRAY's per-row errors.\nexport interface PropsValidationErrors {\n [key: string]: string[] | { properties: PropsValidationErrors[] };\n}\n\nfunction hasErrors(errors: PropsValidationErrors): boolean {\n return Object.keys(errors).length > 0;\n}\n\n// normalizeValue hands a JSON prop's unparseable text back on purpose; the\n// validator would call that \"not JSON\".\nfunction isToleratedJson(\n prop: ApProperty,\n value: unknown,\n original: unknown,\n): boolean {\n return (\n prop.type !== undefined &&\n JSON_LIKE.has(prop.type) &&\n typeof value === \"string\" &&\n value === original\n );\n}\n\n// Upstream's validator over values our processors already coerced. Every\n// declared prop is checked, so a required one that is absent fails too.\nexport function validatePropsValue(\n props: Record<string, ApProperty> | undefined,\n processed: Record<string, unknown>,\n original: Record<string, unknown>,\n): PropsValidationErrors {\n const errors: PropsValidationErrors = {};\n if (!props) return errors;\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n const value = processed[name];\n const raw = original[name];\n if (prop.type === \"ARRAY\" && prop.properties && Array.isArray(value)) {\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, raw);\n const rawRows = Array.isArray(zipped) ? (zipped as unknown[]) : [];\n const rows = (value as unknown[]).map((row, index) => {\n const rawRow = rawRows[index];\n return isRecord(row)\n ? validatePropsValue(\n prop.properties,\n row,\n isRecord(rawRow) ? rawRow : row,\n )\n : {};\n });\n if (rows.some(hasErrors)) errors[name] = { properties: rows };\n continue;\n }\n if (isToleratedJson(prop, value, raw)) continue;\n const messages = validateProperty(prop as PieceProperty, value, raw);\n if (messages.length > 0) errors[name] = messages;\n }\n return errors;\n}\n\nfunction describeErrors(\n errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n path = \"\",\n): string[] {\n return Object.entries(errors).flatMap(([name, entry]) => {\n const label = path\n ? `${path}.${name}`\n : `${props?.[name]?.displayName ?? name} (${name})`;\n if (Array.isArray(entry)) return [`${label}: ${entry.join(\", \")}`];\n const rowProps = props?.[name]?.properties;\n return entry.properties.flatMap((row, index) =>\n describeErrors(row, rowProps, `${path ? label : name}[${index}]`),\n );\n });\n}\n\n// Thrown before piece code runs; `errors` carries upstream's shape.\nexport class PropsValidationError extends Error {\n constructor(\n owner: string,\n readonly errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n ) {\n super(\n `Invalid input for ${owner}: ${describeErrors(errors, props).join(\"; \")}`,\n );\n this.name = \"PropsValidationError\";\n }\n}\n\n// What the builder writes into a step upstream: a prop left unset takes its\n// defaultValue, the value the editor shows for it.\nfunction withDefaults(\n props: Record<string, ApProperty>,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n if (!(name in out)) {\n if (prop.defaultValue !== undefined) out[name] = prop.defaultValue;\n continue;\n }\n const fields = prop.properties;\n if (prop.type !== \"ARRAY\" || !fields) continue;\n const rows: unknown = arrayZipperProcessor(\n prop as PieceProperty,\n out[name],\n );\n if (Array.isArray(rows)) {\n out[name] = (rows as unknown[]).map((row) =>\n isRecord(row) ? withDefaults(fields, row) : row,\n );\n }\n }\n return out;\n}\n\n// Defaults, coercion, then validation: the values run() receives, or a\n// PropsValidationError naming each field that failed.\nexport async function preparePropsValue(\n owner: string,\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const original = withDefaults(props, values);\n const processed = await normalizePropsValue(props, original, options);\n const errors = validatePropsValue(props, processed, original);\n if (hasErrors(errors)) {\n throw new PropsValidationError(owner, errors, props);\n }\n return processed;\n}\n","// Design-time channel (doc 06 §2.5): builds the PropertyContext handed to\n// DROPDOWN options() / DYNAMIC props() resolvers, and invokes them out-of-band.\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n} from \"../types.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type {\n ConnectionsManager,\n FlowsContext,\n PropertyContext,\n ReactorService,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// The framework's FlowsContext.list, minus the SeekPage cursors the host does\n// not serve: a resolver only ever reads `data`.\nexport interface FlowsProvider {\n list(\n ...params: Parameters<FlowsContext[\"list\"]>\n ): Promise<{ data: unknown[] }>;\n}\n\n// The framework's ConnectionsManager with its return widened: the host serves\n// whatever a connection resolved to, not only the shapes upstream enumerates.\nexport interface ConnectionsProvider {\n get(...params: Parameters<ConnectionsManager[\"get\"]>): Promise<unknown>;\n}\n\nexport type BuiltApPropertyContext = Omit<\n PropertyContext,\n \"flows\" | \"connections\"\n> & {\n flows: FlowsProvider;\n connections: ConnectionsProvider;\n // ctx.reactor: the Powerhouse capability the framework has no member for.\n reactor: ReactorService;\n};\n\nexport interface PropertyContextOptions {\n searchValue?: string;\n // Injected capabilities; anything omitted throws with its member path.\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n projectId?: string;\n // ctx.reactor for a design-time resolver, on the same terms as at run time:\n // offered to a package piece, a throwing stub to every other.\n reactor?: ReactorService;\n onTouch?: (member: string) => void;\n}\n\nexport interface PropertyContextHandle {\n context: BuiltApPropertyContext;\n // Top-level members the resolver read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildPropertyContext(\n options: PropertyContextOptions = {},\n): PropertyContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n searchValue: options.searchValue,\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n server: options.server ?? throwingStub(\"server\"),\n project: {\n id: options.projectId ?? \"project\",\n externalId: () => Promise.resolve(options.projectId ?? \"project\"),\n },\n flows: options.flows ?? { list: throwingStub(\"flows.list\") },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApPropertyContext, touched };\n}\n\nexport class NotDynamicPropertyError extends Error {\n constructor(actionName: string, propName: string) {\n super(`Property \"${actionName}.${propName}\" has no dynamic resolver`);\n this.name = \"NotDynamicPropertyError\";\n }\n}\n\nfunction pickResolver(\n prop: ApProperty,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof prop.options === \"function\") return prop.options;\n if (typeof prop.props === \"function\") return prop.props;\n return undefined;\n}\n\nexport interface ResolveDynamicPropertyParams {\n piece: ApPiece;\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n // Resolved values of the prop's refresher inputs (auth and sibling props).\n refresherValues?: Record<string, unknown>;\n context: BuiltApPropertyContext;\n}\n\n// Props map of an action or trigger; throws when the owner is unknown.\nexport function ownerProps(\n piece: ApPiece,\n actionName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): Record<string, ApProperty> {\n const owner =\n kind === \"trigger\"\n ? (getTriggers(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined)\n : (getActions(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined);\n if (!owner) throw new Error(`No ${kind} \"${actionName}\" on piece`);\n return owner.props ?? {};\n}\n\nexport function findProperty(\n piece: ApPiece,\n actionName: string,\n propName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): ApProperty {\n const prop = ownerProps(piece, actionName, kind)[propName] as\n | ApProperty\n | undefined;\n if (!prop)\n throw new Error(`No prop \"${propName}\" on ${kind} \"${actionName}\"`);\n return prop;\n}\n\n// Invokes a DROPDOWN options() or DYNAMIC props() resolver. The result is\n// returned untouched: pieces may soft-fail with a disabled DropdownState.\nexport async function resolveDynamicProperty(\n params: ResolveDynamicPropertyParams,\n): Promise<unknown> {\n const { piece, actionName, propName, kind = \"action\" } = params;\n const prop = findProperty(piece, actionName, propName, kind);\n const resolver = pickResolver(prop);\n if (!resolver) throw new NotDynamicPropertyError(actionName, propName);\n return await resolver(params.refresherValues ?? {}, params.context);\n}\n\nexport interface ParsedResolverId {\n packageName: string;\n actionName: string;\n propName: string;\n}\n\n// Inverse of the descriptor's id scheme: activepieces:<pkg>#<action>.<prop>.\nexport function parseDynamicResolverId(id: string): ParsedResolverId {\n const match = /^activepieces:(.+)#(.+)\\.([^.]+)$/.exec(id);\n if (!match) throw new Error(`Invalid dynamic resolver id: ${id}`);\n return { packageName: match[1], actionName: match[2], propName: match[3] };\n}\n\nexport async function resolveByResolverId(\n piece: ApPiece,\n resolverId: string,\n refresherValues: Record<string, unknown>,\n context: BuiltApPropertyContext,\n): Promise<unknown> {\n const { actionName, propName } = parseDynamicResolverId(resolverId);\n return resolveDynamicProperty({\n piece,\n actionName,\n propName,\n refresherValues,\n context,\n });\n}\n","// `ctx.store` served by the host, one call per operation, so a value a piece\n// writes is durable the moment it writes it rather than when the step ends.\n\n// This is the semantic Activepieces pieces are written against — theirs is an\n// HTTP call per get/put/delete — so a loop that checkpoints its cursor resumes.\nimport type { KeyValueStore } from \"./action.js\";\nimport type { StoreScopeName } from \"./store-scope.js\";\nimport { STORE_DELETE, STORE_GET, STORE_PUT } from \"../worker/protocol.js\";\nimport { callHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\n\n// The host writes JSON, so a value is flattened here rather than at the point\n// it lands. A piece that stores a Date reads back a string either way, whether\n// or not a durable store is configured — and whatever carries the message.\nexport class RemoteKeyValueStore implements KeyValueStore {\n async put(\n key: string,\n value: unknown,\n scope?: StoreScopeName,\n ): Promise<unknown> {\n const stored = jsonSafe(value);\n await callHost(STORE_PUT, { key, value: stored, scope });\n return stored;\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return callHost(STORE_GET, { key, scope });\n }\n\n async delete(key: string, scope?: StoreScopeName): Promise<void> {\n await callHost(STORE_DELETE, { key, scope });\n }\n}\n","// ctx.output.update: the piece reporting progress before it returns. A long\n// step is otherwise opaque until the moment it finishes.\nimport { notifyHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { OUTPUT_UPDATE } from \"../worker/protocol.js\";\n\nexport interface PartialOutput {\n update(output: unknown): Promise<void>;\n}\n\n// Resolves immediately: a tap the step waits on is a tap that can stall it,\n// which is the one thing plan/08 §7.8 rules out.\n\n// A notification carries no request id, and the worker is reused. A piece that\n// keeps `ctx` and updates from a timer would otherwise report progress against\n// whichever step is running by then, so the tap is closed when its step ends.\nexport class RemoteOutput implements PartialOutput {\n private open = true;\n\n update(output: unknown): Promise<void> {\n if (this.open) notifyHost(OUTPUT_UPDATE, jsonSafe(output));\n return Promise.resolve();\n }\n\n close(): void {\n this.open = false;\n }\n}\n","// Piece console output, forwarded to the host while the step runs. The child\n// is forked with its stdio discarded, so without this a piece's logs vanish.\nimport { format } from \"node:util\";\nimport { notifyHost } from \"./host-call.js\";\nimport { LOG_WRITE, type PieceLogEntry } from \"./protocol.js\";\n\n// A runaway piece can log in a loop; the channel is shared with the step's own\n// result, so both the size of an entry and the number of them are capped.\n\n// Without the count, a loop enqueues IPC messages faster than the host drains\n// them and the result waits behind the backlog until the step times out.\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ENTRIES_PER_REQUEST = 1_000;\n\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n// Installs the patch for one request and returns its undo. Logs written after\n// the step returned belong to no step, which is why the scope is this narrow.\nexport function captureConsole(): () => void {\n const original = new Map<Level, (...args: unknown[]) => void>();\n let sent = 0;\n\n for (const level of LEVELS) {\n const previous = console[level] as (...args: unknown[]) => void;\n original.set(level, previous);\n console[level] = (...args: unknown[]) => {\n if (sent > MAX_ENTRIES_PER_REQUEST) return;\n sent += 1;\n // The last one says why the rest are missing, so a truncated log does\n // not read as a step that fell silent.\n const message =\n sent > MAX_ENTRIES_PER_REQUEST\n ? `[log truncated after ${MAX_ENTRIES_PER_REQUEST} entries]`\n : format(...args).slice(0, MAX_MESSAGE_LENGTH);\n notifyHost(LOG_WRITE, {\n level,\n message,\n at: Date.now(),\n } satisfies PieceLogEntry);\n };\n }\n\n return () => {\n for (const [level, previous] of original) {\n console[level] = previous as typeof console.log;\n }\n };\n}\n","// Worker child: loads piece bundles and executes actions in an isolated\n// process, so piece side-effects (TLS env poisoning, crashes) never reach the host.\nimport {\n buildActionContext,\n InMemoryConnectionsProvider,\n InMemoryKeyValueStore,\n UnsupportedContextMemberError,\n} from \"../context/action.js\";\nimport { RemoteKeyValueStore } from \"../context/remote-store.js\";\nimport { RemoteReactorService } from \"../context/reactor.js\";\nimport { RemoteOutput } from \"../context/remote-output.js\";\nimport { captureConsole } from \"./logs.js\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { formatPieceError } from \"@powerhousedao/pieces-framework/host\";\nimport { redactError, redactMessage } from \"./redact.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { buildCheckConnectionContext } from \"../context/check.js\";\nimport { DataUriFilesService, StagedFilesService } from \"../context/files.js\";\nimport { setMaxFileBytes } from \"../context/limits.js\";\nimport {\n normalizePropsValue,\n preparePropsValue,\n PropsValidationError,\n type NormalizeOptions,\n type PropsValidationErrors,\n} from \"../context/normalize.js\";\nimport {\n buildPropertyContext,\n findProperty,\n resolveDynamicProperty,\n} from \"../context/props.js\";\nimport { buildTriggerContext, runTriggerHook } from \"../context/trigger.js\";\nimport { buildDescriptor, describeProperties } from \"../descriptor.js\";\nimport { loadPiece, loadPieceFromDir, type LoadedPiece } from \"../loader.js\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApTrigger,\n} from \"../types.js\";\nimport {\n unsupportedAuth,\n unsupportedTrigger,\n UnsupportedPieceFeatureError,\n} from \"../unsupported.js\";\nimport { installEgressGuard, runWithEgressPolicy } from \"./egress.js\";\nimport type {\n StagedInput,\n PieceModuleRef,\n CheckConnectionMessage,\n CheckConnectionOutcome,\n DescribePieceMessage,\n ResolveOptionsMessage,\n RunMessage,\n SerializedPieceError,\n TriggerHookMessage,\n WorkerRequestMessage,\n WorkerResponse,\n} from \"./protocol.js\";\n\n// Before any piece module is loaded, so a piece cannot keep a pristine copy of\n// the socket layer from a request that carried no policy.\ninstallEgressGuard();\n\nconst loadedPieces = new Map<string, Promise<LoadedPiece>>();\n// One store per scope, alive for the worker's lifetime (in-memory phase:\n// state survives runs but not worker replacement).\nconst stores = new Map<string, InMemoryKeyValueStore>();\n\nfunction storeForScope(scope: string): InMemoryKeyValueStore {\n let store = stores.get(scope);\n if (!store) {\n store = new InMemoryKeyValueStore();\n stores.set(scope, store);\n }\n return store;\n}\n\n// The module this request names, and the cache key for it. A package piece\n// arrives as one file; a fetched bundle as the directory holding it.\nfunction pieceRefKey(ref: PieceModuleRef): string {\n const key = ref.entryPath ?? ref.bundleDir;\n if (!key) {\n throw new Error(\"Request names no piece module (entryPath or bundleDir)\");\n }\n return key;\n}\n\nfunction loadCached(ref: PieceModuleRef): Promise<LoadedPiece> {\n const key = pieceRefKey(ref);\n let loading = loadedPieces.get(key);\n if (!loading) {\n loading = ref.entryPath ? loadPiece(key) : loadPieceFromDir(key);\n loadedPieces.set(key, loading);\n }\n return loading;\n}\n\n// The secret values this request carried, if any. Redacting here rather than\n// on the host means the host process never holds them in an error object.\nfunction redactValuesOf(message: WorkerRequestMessage): string[] {\n const request = message.request as { redactValues?: string[] };\n return request.redactValues ?? [];\n}\n\nfunction serializeError(\n error: unknown,\n values: string[] = [],\n): SerializedPieceError {\n const properties: Record<string, unknown> = {};\n if (typeof error === \"object\" && error !== null) {\n for (const key of Object.keys(error)) {\n properties[key] = jsonSafe((error as Record<string, unknown>)[key]);\n }\n }\n // The framework's own formatter first: it lifts an HTTP status, the request\n // and response, and a message out of an HTML error page. Redaction stays last.\n const { __apErrorVersion, message, errorName, ...http } =\n formatPieceError(error);\n return {\n name:\n (typeof error === \"object\" && error !== null && error.constructor.name) ||\n errorName ||\n \"Error\",\n message: redactMessage(message, { values }),\n properties: redactError(\n { ...properties, ...(jsonSafe(http) as Record<string, unknown>) },\n { values },\n ) as Record<string, unknown>,\n unsupportedMember:\n error instanceof UnsupportedContextMemberError ? error.member : undefined,\n ...(error instanceof UnsupportedPieceFeatureError\n ? { unsupportedFeature: error.feature }\n : {}),\n ...(error instanceof PropsValidationError\n ? { invalidProps: jsonSafe(error.errors) as PropsValidationErrors }\n : {}),\n };\n}\n\n// Read-and-clear the piece-set TLS override so each run reports its own poisoning.\nfunction consumeTlsFlag(): boolean {\n const poisoned = process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\";\n delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;\n return poisoned;\n}\n\nasync function handleResolveOptions(\n message: ResolveOptionsMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const { context, touched } = buildPropertyContext({\n searchValue: request.searchValue,\n projectId: request.projectId,\n // Design-time default: an empty flows listing instead of a throwing stub.\n flows: { list: () => Promise.resolve({ data: [] }) },\n ...(request.reactorAccess ? { reactor: new RemoteReactorService() } : {}),\n });\n const refresherValues = {\n ...(request.auth !== undefined ? { auth: request.auth } : {}),\n ...request.refresherValues,\n };\n const prop = findProperty(\n piece,\n request.actionName,\n request.propName,\n request.kind,\n );\n const output = await resolveDynamicProperty({\n piece,\n actionName: request.actionName,\n kind: request.kind,\n propName: request.propName,\n refresherValues,\n context,\n });\n // DYNAMIC props() yields raw piece properties (with resolver functions);\n // the editor only ever sees descriptors, so translate before crossing IPC.\n const isDynamic =\n typeof prop.props === \"function\" && typeof prop.options !== \"function\";\n return {\n id: message.id,\n type: \"result\",\n output: isDynamic\n ? describeProperties(output as Record<string, ApProperty> | undefined)\n : jsonSafe(output),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\n// Reads a FILE prop's attachment ref from the copy the host staged on disk.\n// The fork shares the filesystem with its parent, so this is what keeps a\n// 50 MB scan out of the IPC channel in both directions.\nfunction stagedInputResolver(\n inputs: StagedInput[] | undefined,\n): NormalizeOptions[\"resolveRef\"] {\n // An empty list is not the same as no list: it means the host has a store\n // and tried, so a FILE prop that still comes up short is told which\n // reference failed rather than that the context has no resolver.\n if (!inputs) return undefined;\n const byRef = new Map(inputs.map((input) => [input.ref, input]));\n return async (ref: string) => {\n const staged = byRef.get(ref);\n if (!staged) {\n throw new Error(`No staged file for reference \"${ref}\"`);\n }\n return {\n data: await readFile(staged.path),\n filename: staged.fileName,\n contentType: staged.contentType,\n };\n };\n}\n\n// The same refusal describe records, for a step or hook that reaches the\n// worker anyway: a workflow saved before the check, or built over the API.\nfunction assertRunnable(\n piece: ApPiece,\n pieceName: string,\n trigger?: { name: string; trigger: ApTrigger },\n): void {\n const pieceFeature = unsupportedAuth(piece.auth);\n if (pieceFeature) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${pieceName}\"`,\n pieceFeature,\n );\n }\n const triggerFeature = trigger && unsupportedTrigger(trigger.trigger);\n if (triggerFeature) {\n throw new UnsupportedPieceFeatureError(\n `Trigger \"${trigger.name}\" of \"${pieceName}\"`,\n triggerFeature,\n );\n }\n}\n\nasync function handleRun(message: RunMessage): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const action = getActions(piece)[request.actionName] as\n | ReturnType<typeof getActions>[string]\n | undefined;\n if (!action) {\n throw new Error(\n `No action \"${request.actionName}\" in ${pieceRefKey(request)}`,\n );\n }\n assertRunnable(piece, piece.displayName);\n const files = request.stagingDir\n ? new StagedFilesService(request.stagingDir)\n : new DataUriFilesService();\n // A durable store answers every get/put over the call channel, so a write\n // survives this worker; without one the value lives only in this heap.\n const durableStore = request.durableStore\n ? new RemoteKeyValueStore()\n : undefined;\n const liveOutput = request.liveOutput ? new RemoteOutput() : undefined;\n // Host-served reactor access, for a piece that ships inside a reactor package.\n const reactor = request.reactorAccess\n ? new RemoteReactorService()\n : undefined;\n // Before the props are normalised, not after: a processor that cannot coerce\n // says so on console.error, and the worker's stdio goes nowhere.\n const restoreConsole = request.captureLogs ? captureConsole() : undefined;\n const { context, touched } = buildActionContext({\n propsValue: await preparePropsValue(\n `action \"${request.actionName}\"`,\n action.props,\n request.propsValue,\n { resolveRef: stagedInputResolver(request.stagedInputs) },\n ),\n auth: request.auth,\n store:\n durableStore ??\n (request.storeScope ? storeForScope(request.storeScope) : undefined),\n files,\n connections: request.connections\n ? new InMemoryConnectionsProvider(request.connections)\n : undefined,\n output: liveOutput,\n reactor,\n executionType: request.executionType,\n identity: request.identity,\n });\n let output: unknown;\n try {\n output = await action.run(context);\n } finally {\n restoreConsole?.();\n liveOutput?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n ...(files instanceof StagedFilesService && files.staged().length > 0\n ? { files: files.staged() }\n : {}),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleTriggerHook(\n message: TriggerHookMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const trigger = getTriggers(piece)[request.triggerName] as\n | ReturnType<typeof getTriggers>[string]\n | undefined;\n if (!trigger) {\n throw new Error(\n `No trigger \"${request.triggerName}\" in bundle ${request.bundleDir}`,\n );\n }\n // Teardown still runs, so a registration made before the check is released.\n if (request.hook !== \"onDisable\") {\n assertRunnable(piece, piece.displayName, {\n name: request.triggerName,\n trigger,\n });\n }\n // The durable store answers every get/put over the call channel, so a long\n // onEnable checkpoints: registration ids survive a crash mid-hook.\n const snapshot = request.durableStore\n ? undefined\n : new InMemoryKeyValueStore(request.storeState);\n const runsPiece = request.hook === \"run\" || request.hook === \"test\";\n // Teardown is never refused: a config that no longer validates must still\n // release what onEnable registered.\n const propsValue =\n request.hook === \"onDisable\"\n ? await normalizePropsValue(trigger.props, request.propsValue)\n : await preparePropsValue(\n `trigger \"${request.triggerName}\"`,\n trigger.props,\n request.propsValue,\n );\n const handle = buildTriggerContext({\n propsValue,\n auth: request.auth,\n store: snapshot ?? new RemoteKeyValueStore(),\n hostPartitionedStore: request.durableStore,\n // Test hooks write under a separate prefix, never the live cursor.\n storePrefix: request.hook === \"test\" ? \"test\" : \"\",\n identity: request.identity,\n isRepublish: request.isRepublish,\n payload: request.payload,\n webhookUrl: request.webhookUrl,\n server: request.server,\n files: runsPiece ? new DataUriFilesService() : undefined,\n });\n const output = await runTriggerHook(trigger, request.hook, handle);\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n touched: [...handle.touched],\n tlsPoisoned: consumeTlsFlag(),\n // Only the snapshot path has state to hand back; a durable store already\n // committed everything the hook wrote.\n ...(snapshot\n ? { storeState: jsonSafe(snapshot.snapshot()) as Record<string, unknown> }\n : {}),\n schedules: handle.schedules,\n listeners: handle.listeners,\n };\n}\n\n// What auth.validate and auth.getConnectionIdentifier are handed upstream: the\n// property values themselves, not the connection envelope an action receives.\nfunction authForValidate(auth: unknown): unknown {\n if (auth === null || typeof auth !== \"object\") return auth;\n const value = auth as Record<string, unknown>;\n switch (value.type) {\n case \"CUSTOM_AUTH\":\n return value.props;\n case \"SECRET_TEXT\":\n return value.secret_text;\n case \"BASIC_AUTH\":\n return { username: value.username, password: value.password };\n default:\n return auth;\n }\n}\n\n// `{ valid: false, error }` (or a bare `false`) fails the check.\nfunction fromValidateResult(\n result: unknown,\n): Pick<CheckConnectionOutcome, \"valid\" | \"detail\"> {\n if (result === false) return { valid: false };\n if (result === null || typeof result !== \"object\") return { valid: true };\n const value = result as { valid?: unknown; error?: unknown };\n if (value.valid !== false) return { valid: true };\n return {\n valid: false,\n ...(typeof value.error === \"string\" && value.error\n ? { detail: value.error }\n : {}),\n };\n}\n\n// Best-effort: a label failure is reported beside a passing check.\nasync function connectionIdentifier(\n getConnectionIdentifier: (context: unknown) => unknown,\n context: unknown,\n): Promise<Pick<CheckConnectionOutcome, \"accountLabel\" | \"identifierError\">> {\n try {\n const label = await getConnectionIdentifier(context);\n return typeof label === \"string\" && label !== \"\"\n ? { accountLabel: label }\n : {};\n } catch (error) {\n return {\n identifierError: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n // An auth array has no hooks here: a connection records no choice among them.\n const auth = (piece as { auth?: unknown }).auth as\n | {\n validate?: (context: unknown) => unknown;\n getConnectionIdentifier?: (context: unknown) => unknown;\n }\n | undefined;\n const validate = auth?.validate;\n const getConnectionIdentifier = auth?.getConnectionIdentifier;\n const { context, touched } = buildCheckConnectionContext({\n auth: authForValidate(request.auth),\n });\n let outcome: CheckConnectionOutcome =\n typeof validate === \"function\"\n ? { declared: true, ...fromValidateResult(await validate(context)) }\n : { declared: false, valid: true };\n if (outcome.valid && typeof getConnectionIdentifier === \"function\") {\n outcome = {\n ...outcome,\n ...(await connectionIdentifier(getConnectionIdentifier, context)),\n };\n }\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleDescribe(\n message: DescribePieceMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const descriptor = buildDescriptor(piece, {\n packageName: request.packageName,\n version: request.version,\n });\n return {\n id: message.id,\n type: \"result\",\n // A prop's defaultValue is piece-authored; jsonSafe keeps a non-cloneable\n // one from failing the IPC send.\n output: jsonSafe(descriptor),\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nfunction isWorkerMessage(value: unknown): value is WorkerRequestMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === \"run\" ||\n type === \"resolve-options\" ||\n type === \"trigger-hook\" ||\n type === \"check-connection\" ||\n type === \"describe\"\n );\n}\n\nfunction dispatch(message: WorkerRequestMessage): Promise<WorkerResponse> {\n switch (message.type) {\n case \"run\":\n return handleRun(message);\n case \"resolve-options\":\n return handleResolveOptions(message);\n case \"trigger-hook\":\n return handleTriggerHook(message);\n case \"check-connection\":\n return handleCheckConnection(message);\n case \"describe\":\n return handleDescribe(message);\n }\n}\n\nprocess.on(\"message\", (message: unknown) => {\n if (!isWorkerMessage(message)) return;\n // Deferred so a synchronous throw — a malformed egress policy — becomes a\n // rejection the handler below reports, instead of killing the child.\n const handler = Promise.resolve().then(() => {\n setMaxFileBytes(message.request.maxFileBytes);\n return runWithEgressPolicy(message.request.egress, () => dispatch(message));\n });\n handler\n .catch((error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(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Q,aAAa;AAC7C,SAAO,oBAAoB,QAAQ,QAAQ,cAAc,SAAS,QAAQ,CAAC;GAC3E,CAEC,OAAO,WAAoC;EAC1C,IAAI,QAAQ;EACZ,MAAM;EACN,OAAO,eAAe,OAAO,eAAe,QAAQ,CAAC;EACrD,aAAa,gBAAgB;EAC9B,EAAE,CACF,MAAM,aAAa,QAAQ,OAAO,SAAS,CAAC,CAC5C,YAAY,QAAQ,KAAK,EAAE,CAAC;EAC/B"}
1
+ {"version":3,"file":"worker-entry.js","names":[],"sources":["../src/pieces/activepieces/worker/host-call.ts","../src/pieces/activepieces/context/reactor.ts","../src/pieces/activepieces/context/check.ts","../src/pieces/activepieces/context/normalize.ts","../src/pieces/activepieces/context/props.ts","../src/pieces/activepieces/context/remote-store.ts","../src/pieces/activepieces/context/remote-output.ts","../src/pieces/activepieces/worker/logs.ts","../src/pieces/activepieces/worker/entry.ts"],"sourcesContent":["// The child's half of the call channel: how piece code reaches durable host\n// state mid-step, instead of handing everything back when the step returns.\n\n// Modelled on their engine RPC (createRpcClient): a method name, a payload, an\n// id, and failures returned as data rather than thrown across the boundary.\nimport type { HostCallResponse } from \"./protocol.js\";\n\n// A host call is a local IPC round trip. Ten seconds is already pathological;\n// the step's own timeout is the outer bound and kills the worker outright.\nconst DEFAULT_HOST_CALL_TIMEOUT_MS = 10_000;\n\ninterface Pending {\n method: string;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n timer: NodeJS.Timeout;\n}\n\nconst pending = new Map<number, Pending>();\nlet nextId = 1;\nlet listening = false;\n\nexport class HostCallError extends Error {\n constructor(method: string, detail: string) {\n super(`Host call \"${method}\" failed: ${detail}`);\n this.name = \"HostCallError\";\n }\n}\n\nexport class HostCallTimeoutError extends Error {\n constructor(method: string, timeoutMs: number) {\n super(`Host call \"${method}\" got no answer within ${timeoutMs}ms`);\n this.name = \"HostCallTimeoutError\";\n }\n}\n\nfunction isHostCallResponse(value: unknown): value is HostCallResponse {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { type?: unknown }).type === \"host-result\"\n );\n}\n\n// Registered once, on the same channel the job messages arrive on. The job\n// dispatcher ignores `host-result` because it only knows its own request types.\nfunction ensureListening(): void {\n if (listening) return;\n listening = true;\n process.on(\"message\", (message: unknown) => {\n if (!isHostCallResponse(message)) return;\n const entry = pending.get(message.id);\n if (!entry) return;\n pending.delete(message.id);\n clearTimeout(entry.timer);\n if (message.error !== undefined) {\n entry.reject(new HostCallError(entry.method, message.error));\n return;\n }\n entry.resolve(message.value);\n });\n}\n\nexport function callHost<T = unknown>(\n method: string,\n payload: unknown,\n timeoutMs: number = DEFAULT_HOST_CALL_TIMEOUT_MS,\n): Promise<T> {\n if (!process.send) {\n return Promise.reject(\n new HostCallError(method, \"the worker has no channel to its host\"),\n );\n }\n ensureListening();\n const id = nextId++;\n return new Promise<T>((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(id);\n reject(new HostCallTimeoutError(method, timeoutMs));\n }, timeoutMs);\n pending.set(id, {\n method,\n resolve: resolve as (value: unknown) => void,\n reject,\n timer,\n });\n process.send?.({ id, type: \"host-call\", method, payload });\n });\n}\n\n// Test seam: a worker replaced between suites must not inherit pending calls.\nexport function resetHostCalls(): void {\n for (const entry of pending.values()) clearTimeout(entry.timer);\n pending.clear();\n}\n\n// The one-way half: a report with no answer to wait for. It cannot fail from\n// the piece's side, so a missing channel is dropped rather than raised.\nexport function notifyHost(method: string, payload: unknown): void {\n try {\n process.send?.({ type: \"host-notify\", method, payload });\n } catch {\n // `process.send` stays defined after the channel closes and throws. A tap\n // that threw here would be a tap that changed the step.\n }\n}\n","// `ctx.reactor` — the one way piece code reaches the reactor it runs inside.\n\n// Pieces are isolated from the host on purpose, so this is not a client: it is\n// the same call channel `ctx.store` uses (doc 08 §10), and every method is a\n// round trip the host answers. The host installs it only for a piece that came\n// from an installed reactor package; a bundle fetched from a registry gets the\n// throwing stub instead, and finds out by name that it has no reactor.\nimport { callHost } from \"../worker/host-call.js\";\nimport type {\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorService,\n} from \"@powerhousedao/pieces-framework\";\nimport {\n REACTOR_CREATE,\n REACTOR_EXECUTE,\n REACTOR_FIND,\n REACTOR_GET,\n REACTOR_MODEL,\n REACTOR_MODELS,\n} from \"../worker/protocol.js\";\n\n// The service contract and its input/output shapes live in the framework, so a\n// piece and the host it calls are typed against one declaration.\nexport type {\n ReactorActionInput,\n ReactorCreateInput,\n ReactorDocumentSummary,\n ReactorExecuteInput,\n ReactorFindInput,\n ReactorModelActionSchema,\n ReactorModelDetail,\n ReactorModelSummary,\n ReactorService,\n} from \"@powerhousedao/pieces-framework\";\n\n// The worker's half: every method is one host call, named so a failure reads\n// as the operation the piece asked for.\nexport class RemoteReactorService implements ReactorService {\n models(): Promise<ReactorModelSummary[]> {\n return callHost<ReactorModelSummary[]>(REACTOR_MODELS, {});\n }\n\n model(documentType: string): Promise<ReactorModelDetail> {\n return callHost<ReactorModelDetail>(REACTOR_MODEL, { documentType });\n }\n\n get(input: {\n documentId: string;\n branch?: string;\n }): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_GET, input);\n }\n\n find(input: ReactorFindInput): Promise<ReactorDocumentSummary[]> {\n return callHost<ReactorDocumentSummary[]>(REACTOR_FIND, input);\n }\n\n create(input: ReactorCreateInput): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_CREATE, input);\n }\n\n execute(input: ReactorExecuteInput): Promise<ReactorDocumentSummary> {\n return callHost<ReactorDocumentSummary>(REACTOR_EXECUTE, input);\n }\n}\n","// Context handed to a piece's auth.validate and auth.getConnectionIdentifier:\n// `{ auth, server }`, with auth as the flat property value.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { AuthValidationServerContext } from \"@powerhousedao/pieces-framework\";\n\nexport interface CheckConnectionContextOptions {\n auth?: unknown;\n // apiUrl / publicUrl when the host serves them; mintOidcToken always throws,\n // since no reactor mints tokens for a piece's connection check.\n server?: Omit<AuthValidationServerContext, \"mintOidcToken\">;\n onTouch?: (member: string) => void;\n}\n\nexport interface BuiltApCheckConnectionContext {\n auth: unknown;\n server: AuthValidationServerContext;\n}\n\nexport interface CheckConnectionContextHandle {\n context: BuiltApCheckConnectionContext;\n // Top-level members the check read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildCheckConnectionContext(\n options: CheckConnectionContextOptions = {},\n): CheckConnectionContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n auth: options.auth,\n server: options.server\n ? {\n ...options.server,\n mintOidcToken: throwingStub(\"server.mintOidcToken\"),\n }\n : throwingStub(\"server\"),\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApCheckConnectionContext,\n touched,\n };\n}\n","// Run-time coercion of stored config values into the shapes pieces expect: the\n// engine's own property processors, with our file hydration in front of theirs.\nimport type { PieceProperty } from \"@powerhousedao/pieces-framework\";\nimport {\n arrayZipperProcessor,\n processors,\n validateProperty,\n type ProcessorFn,\n} from \"@powerhousedao/pieces-framework/host\";\nimport type { ApProperty } from \"../types.js\";\nimport {\n assertWithinLimit,\n DEFAULT_MAX_FILE_BYTES,\n maxFileBytes,\n} from \"./limits.js\";\n\n// Framework ApFile (filename, data, extension, base64) as a plain object so\n// it survives IPC and structured cloning.\nexport interface ApFileValue {\n filename: string;\n extension?: string;\n base64: string;\n data: Buffer;\n}\n\nexport interface FetchedFile {\n data: Buffer;\n filename?: string;\n contentType?: string;\n}\n\nexport interface NormalizeOptions {\n // Resolves a URL-valued FILE prop; defaults to fetch() with a size cap.\n fetchFile?: (url: string) => Promise<FetchedFile>;\n // Resolves a reference-valued FILE prop (attachment:// or apfile://). The\n // worker resolves these from files the host staged on disk, so the bytes\n // never cross IPC.\n resolveRef?: (ref: string) => Promise<FetchedFile>;\n}\n\n// Re-exported for compatibility; the ceiling itself lives in limits.ts so the\n// inbound and outbound paths cannot drift apart.\nexport const MAX_FILE_BYTES = DEFAULT_MAX_FILE_BYTES;\nconst FETCH_TIMEOUT_MS = 30_000;\n\n// A FILE prop whose value is a reference the host has to resolve.\nconst FILE_REF = /^(?:attachment|apfile):\\/\\//i;\n\nexport class FileFetchError extends Error {\n constructor(url: string, reason: string) {\n super(`Could not fetch FILE prop \"${url}\": ${reason}`);\n this.name = \"FileFetchError\";\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst DATA_URI = /^data:([^;,]*)((?:;[^;,]*)*),([\\s\\S]*)$/;\n\nfunction extensionOf(filename: string): string | undefined {\n const dot = filename.lastIndexOf(\".\");\n return dot > 0 && dot < filename.length - 1\n ? filename.slice(dot + 1)\n : undefined;\n}\n\nconst MIME_EXTENSIONS: Record<string, string> = {\n \"image/png\": \"png\",\n \"image/jpeg\": \"jpg\",\n \"image/gif\": \"gif\",\n \"image/webp\": \"webp\",\n \"image/svg+xml\": \"svg\",\n \"application/pdf\": \"pdf\",\n \"application/json\": \"json\",\n \"text/plain\": \"txt\",\n \"text/csv\": \"csv\",\n};\n\nfunction toFileValue(\n data: Buffer,\n filename: string | undefined,\n contentType: string | undefined,\n): ApFileValue {\n const mime = contentType?.split(\";\")[0].trim().toLowerCase();\n const mimeExtension = mime ? MIME_EXTENSIONS[mime] : undefined;\n const name =\n filename && filename !== \"\"\n ? filename\n : `file${mimeExtension ? `.${mimeExtension}` : \"\"}`;\n const extension = extensionOf(name) ?? mimeExtension;\n return {\n filename: name,\n ...(extension ? { extension } : {}),\n base64: data.toString(\"base64\"),\n data,\n };\n}\n\nfunction filenameFromDisposition(header: string | null): string | undefined {\n if (!header) return undefined;\n const utf8 = /filename\\*=(?:UTF-8'')?([^;]+)/i.exec(header);\n if (utf8) {\n try {\n return decodeURIComponent(utf8[1].trim().replace(/^\"|\"$/g, \"\"));\n } catch {\n // fall through to the plain form\n }\n }\n const plain = /filename=\"?([^\";]+)\"?/i.exec(header);\n return plain ? plain[1].trim() : undefined;\n}\n\nasync function defaultFetchFile(url: string): Promise<FetchedFile> {\n let response: Response;\n try {\n response = await fetch(url, {\n signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),\n });\n } catch (error) {\n throw new FileFetchError(\n url,\n error instanceof Error ? error.message : String(error),\n );\n }\n if (!response.ok) throw new FileFetchError(url, `HTTP ${response.status}`);\n const limit = maxFileBytes();\n const declared = Number(response.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > limit) {\n throw new FileFetchError(url, `${declared} bytes exceeds ${limit}`);\n }\n const data = Buffer.from(await response.arrayBuffer());\n if (data.byteLength > limit) {\n throw new FileFetchError(url, `${data.byteLength} bytes exceeds ${limit}`);\n }\n let filename = filenameFromDisposition(\n response.headers.get(\"content-disposition\"),\n );\n if (!filename) {\n const segment = new URL(url).pathname.split(\"/\").filter(Boolean).pop();\n if (segment) filename = decodeURIComponent(segment);\n }\n return {\n data,\n filename,\n contentType: response.headers.get(\"content-type\") ?? undefined,\n };\n}\n\nfunction isFileShaped(value: unknown): value is ApFileValue {\n return (\n isRecord(value) &&\n typeof value.filename === \"string\" &&\n (typeof value.base64 === \"string\" || Buffer.isBuffer(value.data))\n );\n}\n\n// URL or data URI → ApFile shape; already-shaped objects are completed\n// (data/base64 derived from each other); anything else passes through.\nexport async function toApFile(\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (isFileShaped(value)) {\n const data = Buffer.isBuffer(value.data)\n ? value.data\n : Buffer.from(value.base64, \"base64\");\n // The cap applies to every branch, not just the fetched one: an oversized\n // data URI or file-shaped object would otherwise slip past it.\n assertWithinLimit(data.byteLength);\n const extension = value.extension ?? extensionOf(value.filename);\n return {\n ...value,\n ...(extension ? { extension } : {}),\n base64:\n typeof value.base64 === \"string\"\n ? value.base64\n : data.toString(\"base64\"),\n data,\n };\n }\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n const dataUri = DATA_URI.exec(trimmed);\n if (dataUri) {\n const [, mime, params, payload] = dataUri;\n const isBase64 = /;base64/i.test(params);\n const data = isBase64\n ? Buffer.from(payload, \"base64\")\n : Buffer.from(decodeURIComponent(payload), \"utf8\");\n assertWithinLimit(data.byteLength);\n const nameParam = /;name=([^;]+)/i.exec(params)?.[1];\n return toFileValue(\n data,\n nameParam ? decodeURIComponent(nameParam) : undefined,\n mime || undefined,\n );\n }\n if (FILE_REF.test(trimmed)) {\n if (!options.resolveRef) {\n throw new FileFetchError(\n trimmed,\n \"no attachment resolver is available in this context\",\n );\n }\n const resolved = await options.resolveRef(trimmed);\n assertWithinLimit(resolved.data.byteLength);\n return toFileValue(resolved.data, resolved.filename, resolved.contentType);\n }\n if (/^https?:\\/\\//i.test(trimmed)) {\n const fetched = await (options.fetchFile ?? defaultFetchFile)(trimmed);\n return toFileValue(fetched.data, fetched.filename, fetched.contentType);\n }\n return value;\n}\n\n// ARRAY has no entry in the processor table: the engine zips an object of\n// parallel arrays into rows itself, then processes each row's own props.\nasync function normalizeArray(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions,\n): Promise<unknown> {\n const fields = prop.properties;\n if (!fields) return value;\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, value);\n if (!Array.isArray(zipped)) return value;\n return Promise.all(\n (zipped as unknown[]).map((item) =>\n isRecord(item) ? normalizePropsValue(fields, item, options) : item,\n ),\n );\n}\n\n// An ApFile is a class instance whose base64 is a prototype getter, and no\n// structured clone carries either; flatten it at the boundary (see ApFileValue).\nfunction plainFile(value: unknown): unknown {\n if (!isRecord(value) || typeof value.filename !== \"string\") return value;\n const { data } = value;\n if (!Buffer.isBuffer(data)) return value;\n const extension =\n typeof value.extension === \"string\"\n ? value.extension\n : extensionOf(value.filename);\n return {\n filename: value.filename,\n ...(extension ? { extension } : {}),\n base64:\n typeof value.base64 === \"string\" ? value.base64 : data.toString(\"base64\"),\n data,\n };\n}\n\nconst table = processors as Record<string, ProcessorFn | undefined>;\n\n// The types whose processor failing means \"not JSON\", not \"not usable\".\nconst JSON_LIKE = new Set([\"JSON\", \"OBJECT\"]);\n\nexport async function normalizeValue(\n prop: ApProperty,\n value: unknown,\n options: NormalizeOptions = {},\n): Promise<unknown> {\n if (value === undefined || value === null) return value;\n if (prop.type === \"ARRAY\") return normalizeArray(prop, value, options);\n if (prop.type === \"FILE\") {\n // Our hydration owns the forms the engine's own processor cannot resolve:\n // attachment and apfile refs, the size cap, and a host-injected fetcher.\n const hydrated = await toApFile(value, options);\n if (typeof hydrated !== \"string\") return hydrated;\n return plainFile(await table.FILE?.(prop as PieceProperty, hydrated));\n }\n const type = prop.type;\n const processor = type ? table[type] : undefined;\n if (!processor) return value;\n const processed = plainFile(await processor(prop as PieceProperty, value));\n // Every other type keeps its promise to the piece: a DATE_TIME prop is an\n // ISO string or nothing, a NUMBER is a number or NaN. JSON is the exception,\n // because the thing most often routed into one is a model's answer, and a\n // model wraps its object in prose. jsonProcessor answers undefined for that,\n // which would drop the value entirely — so hand back what the author wrote\n // and let the piece parse it. The pieces that take model output this way\n // carry their own tolerant parsing for exactly this case.\n if (processed === undefined && type && JSON_LIKE.has(type) && value !== \"\") {\n return value;\n }\n return processed;\n}\n\n// Normalises every configured value with a matching prop schema; keys\n// without a schema (or props without a value) pass through untouched.\nexport async function normalizePropsValue(\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const out: Record<string, unknown> = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!(name in out) || !isRecord(prop)) continue;\n const normalized = await normalizeValue(prop, out[name], options);\n if (normalized === undefined) delete out[name];\n else out[name] = normalized;\n }\n return out;\n}\n\n// Upstream's error shape: a field's messages, or an ARRAY's per-row errors.\nexport interface PropsValidationErrors {\n [key: string]: string[] | { properties: PropsValidationErrors[] };\n}\n\nfunction hasErrors(errors: PropsValidationErrors): boolean {\n return Object.keys(errors).length > 0;\n}\n\n// normalizeValue hands a JSON prop's unparseable text back on purpose; the\n// validator would call that \"not JSON\".\nfunction isToleratedJson(\n prop: ApProperty,\n value: unknown,\n original: unknown,\n): boolean {\n return (\n prop.type !== undefined &&\n JSON_LIKE.has(prop.type) &&\n typeof value === \"string\" &&\n value === original\n );\n}\n\n// Upstream's validator over values our processors already coerced. Every\n// declared prop is checked, so a required one that is absent fails too.\nexport function validatePropsValue(\n props: Record<string, ApProperty> | undefined,\n processed: Record<string, unknown>,\n original: Record<string, unknown>,\n): PropsValidationErrors {\n const errors: PropsValidationErrors = {};\n if (!props) return errors;\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n const value = processed[name];\n const raw = original[name];\n if (prop.type === \"ARRAY\" && prop.properties && Array.isArray(value)) {\n const zipped: unknown = arrayZipperProcessor(prop as PieceProperty, raw);\n const rawRows = Array.isArray(zipped) ? (zipped as unknown[]) : [];\n const rows = (value as unknown[]).map((row, index) => {\n const rawRow = rawRows[index];\n return isRecord(row)\n ? validatePropsValue(\n prop.properties,\n row,\n isRecord(rawRow) ? rawRow : row,\n )\n : {};\n });\n if (rows.some(hasErrors)) errors[name] = { properties: rows };\n continue;\n }\n if (isToleratedJson(prop, value, raw)) continue;\n const messages = validateProperty(prop as PieceProperty, value, raw);\n if (messages.length > 0) errors[name] = messages;\n }\n return errors;\n}\n\nfunction describeErrors(\n errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n path = \"\",\n): string[] {\n return Object.entries(errors).flatMap(([name, entry]) => {\n const label = path\n ? `${path}.${name}`\n : `${props?.[name]?.displayName ?? name} (${name})`;\n if (Array.isArray(entry)) return [`${label}: ${entry.join(\", \")}`];\n const rowProps = props?.[name]?.properties;\n return entry.properties.flatMap((row, index) =>\n describeErrors(row, rowProps, `${path ? label : name}[${index}]`),\n );\n });\n}\n\n// Thrown before piece code runs; `errors` carries upstream's shape.\nexport class PropsValidationError extends Error {\n constructor(\n owner: string,\n readonly errors: PropsValidationErrors,\n props: Record<string, ApProperty> | undefined,\n ) {\n super(\n `Invalid input for ${owner}: ${describeErrors(errors, props).join(\"; \")}`,\n );\n this.name = \"PropsValidationError\";\n }\n}\n\n// What the builder writes into a step upstream: a prop left unset takes its\n// defaultValue, the value the editor shows for it.\nfunction withDefaults(\n props: Record<string, ApProperty>,\n values: Record<string, unknown>,\n): Record<string, unknown> {\n const out = { ...values };\n for (const [name, prop] of Object.entries(props)) {\n if (!isRecord(prop)) continue;\n if (!(name in out)) {\n if (prop.defaultValue !== undefined) out[name] = prop.defaultValue;\n continue;\n }\n const fields = prop.properties;\n if (prop.type !== \"ARRAY\" || !fields) continue;\n const rows: unknown = arrayZipperProcessor(\n prop as PieceProperty,\n out[name],\n );\n if (Array.isArray(rows)) {\n out[name] = (rows as unknown[]).map((row) =>\n isRecord(row) ? withDefaults(fields, row) : row,\n );\n }\n }\n return out;\n}\n\n// Defaults, coercion, then validation: the values run() receives, or a\n// PropsValidationError naming each field that failed.\nexport async function preparePropsValue(\n owner: string,\n props: Record<string, ApProperty> | undefined,\n values: Record<string, unknown>,\n options: NormalizeOptions = {},\n): Promise<Record<string, unknown>> {\n if (!props || !isRecord(values)) return values;\n const original = withDefaults(props, values);\n const processed = await normalizePropsValue(props, original, options);\n const errors = validatePropsValue(props, processed, original);\n if (hasErrors(errors)) {\n throw new PropsValidationError(owner, errors, props);\n }\n return processed;\n}\n","// Design-time channel (doc 06 §2.5): builds the PropertyContext handed to\n// DROPDOWN options() / DYNAMIC props() resolvers, and invokes them out-of-band.\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n} from \"../types.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type {\n ConnectionsManager,\n FlowsContext,\n PropertyContext,\n ReactorService,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// The framework's FlowsContext.list, minus the SeekPage cursors the host does\n// not serve: a resolver only ever reads `data`.\nexport interface FlowsProvider {\n list(\n ...params: Parameters<FlowsContext[\"list\"]>\n ): Promise<{ data: unknown[] }>;\n}\n\n// The framework's ConnectionsManager with its return widened: the host serves\n// whatever a connection resolved to, not only the shapes upstream enumerates.\nexport interface ConnectionsProvider {\n get(...params: Parameters<ConnectionsManager[\"get\"]>): Promise<unknown>;\n}\n\nexport type BuiltApPropertyContext = Omit<\n PropertyContext,\n \"flows\" | \"connections\"\n> & {\n flows: FlowsProvider;\n connections: ConnectionsProvider;\n // ctx.reactor: the Powerhouse capability the framework has no member for.\n reactor: ReactorService;\n};\n\nexport interface PropertyContextOptions {\n searchValue?: string;\n // Injected capabilities; anything omitted throws with its member path.\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n projectId?: string;\n // ctx.reactor for a design-time resolver, on the same terms as at run time:\n // offered to a package piece, a throwing stub to every other.\n reactor?: ReactorService;\n onTouch?: (member: string) => void;\n}\n\nexport interface PropertyContextHandle {\n context: BuiltApPropertyContext;\n // Top-level members the resolver read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildPropertyContext(\n options: PropertyContextOptions = {},\n): PropertyContextHandle {\n const touched = new Set<string>();\n const base: Record<string, unknown> = {\n searchValue: options.searchValue,\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n server: options.server ?? throwingStub(\"server\"),\n project: {\n id: options.projectId ?? \"project\",\n externalId: () => Promise.resolve(options.projectId ?? \"project\"),\n },\n flows: options.flows ?? { list: throwingStub(\"flows.list\") },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n };\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApPropertyContext, touched };\n}\n\nexport class NotDynamicPropertyError extends Error {\n constructor(actionName: string, propName: string) {\n super(`Property \"${actionName}.${propName}\" has no dynamic resolver`);\n this.name = \"NotDynamicPropertyError\";\n }\n}\n\nfunction pickResolver(\n prop: ApProperty,\n): ((...args: unknown[]) => unknown) | undefined {\n if (typeof prop.options === \"function\") return prop.options;\n if (typeof prop.props === \"function\") return prop.props;\n return undefined;\n}\n\nexport interface ResolveDynamicPropertyParams {\n piece: ApPiece;\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n // Resolved values of the prop's refresher inputs (auth and sibling props).\n refresherValues?: Record<string, unknown>;\n context: BuiltApPropertyContext;\n}\n\n// Props map of an action or trigger; throws when the owner is unknown.\nexport function ownerProps(\n piece: ApPiece,\n actionName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): Record<string, ApProperty> {\n const owner =\n kind === \"trigger\"\n ? (getTriggers(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined)\n : (getActions(piece)[actionName] as\n | { props?: Record<string, ApProperty> }\n | undefined);\n if (!owner) throw new Error(`No ${kind} \"${actionName}\" on piece`);\n return owner.props ?? {};\n}\n\nexport function findProperty(\n piece: ApPiece,\n actionName: string,\n propName: string,\n kind: \"action\" | \"trigger\" = \"action\",\n): ApProperty {\n const prop = ownerProps(piece, actionName, kind)[propName] as\n | ApProperty\n | undefined;\n if (!prop)\n throw new Error(`No prop \"${propName}\" on ${kind} \"${actionName}\"`);\n return prop;\n}\n\n// Invokes a DROPDOWN options() or DYNAMIC props() resolver. The result is\n// returned untouched: pieces may soft-fail with a disabled DropdownState.\nexport async function resolveDynamicProperty(\n params: ResolveDynamicPropertyParams,\n): Promise<unknown> {\n const { piece, actionName, propName, kind = \"action\" } = params;\n const prop = findProperty(piece, actionName, propName, kind);\n const resolver = pickResolver(prop);\n if (!resolver) throw new NotDynamicPropertyError(actionName, propName);\n return await resolver(params.refresherValues ?? {}, params.context);\n}\n\nexport interface ParsedResolverId {\n packageName: string;\n actionName: string;\n propName: string;\n}\n\n// Inverse of the descriptor's id scheme: activepieces:<pkg>#<action>.<prop>.\nexport function parseDynamicResolverId(id: string): ParsedResolverId {\n const match = /^activepieces:(.+)#(.+)\\.([^.]+)$/.exec(id);\n if (!match) throw new Error(`Invalid dynamic resolver id: ${id}`);\n return { packageName: match[1], actionName: match[2], propName: match[3] };\n}\n\nexport async function resolveByResolverId(\n piece: ApPiece,\n resolverId: string,\n refresherValues: Record<string, unknown>,\n context: BuiltApPropertyContext,\n): Promise<unknown> {\n const { actionName, propName } = parseDynamicResolverId(resolverId);\n return resolveDynamicProperty({\n piece,\n actionName,\n propName,\n refresherValues,\n context,\n });\n}\n","// `ctx.store` served by the host, one call per operation, so a value a piece\n// writes is durable the moment it writes it rather than when the step ends.\n\n// This is the semantic Activepieces pieces are written against — theirs is an\n// HTTP call per get/put/delete — so a loop that checkpoints its cursor resumes.\nimport type { KeyValueStore } from \"./action.js\";\nimport type { StoreScopeName } from \"./store-scope.js\";\nimport { STORE_DELETE, STORE_GET, STORE_PUT } from \"../worker/protocol.js\";\nimport { callHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\n\n// The host writes JSON, so a value is flattened here rather than at the point\n// it lands. A piece that stores a Date reads back a string either way, whether\n// or not a durable store is configured — and whatever carries the message.\nexport class RemoteKeyValueStore implements KeyValueStore {\n async put(\n key: string,\n value: unknown,\n scope?: StoreScopeName,\n ): Promise<unknown> {\n const stored = jsonSafe(value);\n await callHost(STORE_PUT, { key, value: stored, scope });\n return stored;\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return callHost(STORE_GET, { key, scope });\n }\n\n async delete(key: string, scope?: StoreScopeName): Promise<void> {\n await callHost(STORE_DELETE, { key, scope });\n }\n}\n","// ctx.output.update: the piece reporting progress before it returns. A long\n// step is otherwise opaque until the moment it finishes.\nimport { notifyHost } from \"../worker/host-call.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { OUTPUT_UPDATE } from \"../worker/protocol.js\";\n\nexport interface PartialOutput {\n update(output: unknown): Promise<void>;\n}\n\n// Resolves immediately: a tap the step waits on is a tap that can stall it,\n// which is the one thing plan/08 §7.8 rules out.\n\n// A notification carries no request id, and the worker is reused. A piece that\n// keeps `ctx` and updates from a timer would otherwise report progress against\n// whichever step is running by then, so the tap is closed when its step ends.\nexport class RemoteOutput implements PartialOutput {\n private open = true;\n\n update(output: unknown): Promise<void> {\n if (this.open) notifyHost(OUTPUT_UPDATE, jsonSafe(output));\n return Promise.resolve();\n }\n\n close(): void {\n this.open = false;\n }\n}\n","// Piece console output, forwarded to the host while the step runs. The child\n// is forked with its stdio discarded, so without this a piece's logs vanish.\nimport { format } from \"node:util\";\nimport { notifyHost } from \"./host-call.js\";\nimport { LOG_WRITE, type PieceLogEntry } from \"./protocol.js\";\n\n// A runaway piece can log in a loop; the channel is shared with the step's own\n// result, so both the size of an entry and the number of them are capped.\n\n// Without the count, a loop enqueues IPC messages faster than the host drains\n// them and the result waits behind the backlog until the step times out.\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ENTRIES_PER_REQUEST = 1_000;\n\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n// Installs the patch for one request and returns its undo. Logs written after\n// the step returned belong to no step, which is why the scope is this narrow.\nexport function captureConsole(): () => void {\n const original = new Map<Level, (...args: unknown[]) => void>();\n let sent = 0;\n\n for (const level of LEVELS) {\n const previous = console[level] as (...args: unknown[]) => void;\n original.set(level, previous);\n console[level] = (...args: unknown[]) => {\n if (sent > MAX_ENTRIES_PER_REQUEST) return;\n sent += 1;\n // The last one says why the rest are missing, so a truncated log does\n // not read as a step that fell silent.\n const message =\n sent > MAX_ENTRIES_PER_REQUEST\n ? `[log truncated after ${MAX_ENTRIES_PER_REQUEST} entries]`\n : format(...args).slice(0, MAX_MESSAGE_LENGTH);\n notifyHost(LOG_WRITE, {\n level,\n message,\n at: Date.now(),\n } satisfies PieceLogEntry);\n };\n }\n\n return () => {\n for (const [level, previous] of original) {\n console[level] = previous as typeof console.log;\n }\n };\n}\n","// Worker child: loads piece bundles and executes actions in an isolated\n// process, so piece side-effects (TLS env poisoning, crashes) never reach the host.\nimport {\n buildActionContext,\n InMemoryConnectionsProvider,\n InMemoryKeyValueStore,\n UnsupportedContextMemberError,\n} from \"../context/action.js\";\nimport { RemoteKeyValueStore } from \"../context/remote-store.js\";\nimport { RemoteReactorService } from \"../context/reactor.js\";\nimport { RemoteOutput } from \"../context/remote-output.js\";\nimport { captureConsole } from \"./logs.js\";\nimport { jsonSafe } from \"./json-safe.js\";\nimport { formatPieceError } from \"@powerhousedao/pieces-framework/host\";\nimport { redactError, redactMessage } from \"./redact.js\";\nimport { readFile } from \"node:fs/promises\";\nimport { buildCheckConnectionContext } from \"../context/check.js\";\nimport { DataUriFilesService, StagedFilesService } from \"../context/files.js\";\nimport { setMaxFileBytes } from \"../context/limits.js\";\nimport {\n normalizePropsValue,\n preparePropsValue,\n PropsValidationError,\n type NormalizeOptions,\n type PropsValidationErrors,\n} from \"../context/normalize.js\";\nimport {\n buildPropertyContext,\n findProperty,\n resolveDynamicProperty,\n} from \"../context/props.js\";\nimport { buildTriggerContext, runTriggerHook } from \"../context/trigger.js\";\nimport { buildDescriptor, describeProperties } from \"../descriptor.js\";\nimport { loadPiece, loadPieceFromDir, type LoadedPiece } from \"../loader.js\";\nimport {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApTrigger,\n} from \"../types.js\";\nimport {\n authMethodFor,\n unsupportedAuth,\n unsupportedTrigger,\n UnsupportedPieceFeatureError,\n} from \"../unsupported.js\";\nimport { installEgressGuard, runWithEgressPolicy } from \"./egress.js\";\nimport type {\n StagedInput,\n PieceModuleRef,\n CheckConnectionMessage,\n CheckConnectionOutcome,\n DescribePieceMessage,\n ResolveOptionsMessage,\n RunMessage,\n SerializedPieceError,\n TriggerHookMessage,\n WorkerRequestMessage,\n WorkerResponse,\n} from \"./protocol.js\";\n\n// Before any piece module is loaded, so a piece cannot keep a pristine copy of\n// the socket layer from a request that carried no policy.\ninstallEgressGuard();\n\nconst loadedPieces = new Map<string, Promise<LoadedPiece>>();\n// One store per scope, alive for the worker's lifetime (in-memory phase:\n// state survives runs but not worker replacement).\nconst stores = new Map<string, InMemoryKeyValueStore>();\n\nfunction storeForScope(scope: string): InMemoryKeyValueStore {\n let store = stores.get(scope);\n if (!store) {\n store = new InMemoryKeyValueStore();\n stores.set(scope, store);\n }\n return store;\n}\n\n// The module this request names, and the cache key for it. A package piece\n// arrives as one file; a fetched bundle as the directory holding it.\nfunction pieceRefKey(ref: PieceModuleRef): string {\n const key = ref.entryPath ?? ref.bundleDir;\n if (!key) {\n throw new Error(\"Request names no piece module (entryPath or bundleDir)\");\n }\n return key;\n}\n\nfunction loadCached(ref: PieceModuleRef): Promise<LoadedPiece> {\n const key = pieceRefKey(ref);\n let loading = loadedPieces.get(key);\n if (!loading) {\n loading = ref.entryPath ? loadPiece(key) : loadPieceFromDir(key);\n loadedPieces.set(key, loading);\n }\n return loading;\n}\n\n// The secret values this request carried, if any. Redacting here rather than\n// on the host means the host process never holds them in an error object.\nfunction redactValuesOf(message: WorkerRequestMessage): string[] {\n const request = message.request as { redactValues?: string[] };\n return request.redactValues ?? [];\n}\n\nfunction serializeError(\n error: unknown,\n values: string[] = [],\n): SerializedPieceError {\n const properties: Record<string, unknown> = {};\n if (typeof error === \"object\" && error !== null) {\n for (const key of Object.keys(error)) {\n properties[key] = jsonSafe((error as Record<string, unknown>)[key]);\n }\n }\n // The framework's own formatter first: it lifts an HTTP status, the request\n // and response, and a message out of an HTML error page. Redaction stays last.\n const { __apErrorVersion, message, errorName, ...http } =\n formatPieceError(error);\n return {\n name:\n (typeof error === \"object\" && error !== null && error.constructor.name) ||\n errorName ||\n \"Error\",\n message: redactMessage(message, { values }),\n properties: redactError(\n { ...properties, ...(jsonSafe(http) as Record<string, unknown>) },\n { values },\n ) as Record<string, unknown>,\n unsupportedMember:\n error instanceof UnsupportedContextMemberError ? error.member : undefined,\n ...(error instanceof UnsupportedPieceFeatureError\n ? { unsupportedFeature: error.feature }\n : {}),\n ...(error instanceof PropsValidationError\n ? { invalidProps: jsonSafe(error.errors) as PropsValidationErrors }\n : {}),\n };\n}\n\n// Read-and-clear the piece-set TLS override so each run reports its own poisoning.\nfunction consumeTlsFlag(): boolean {\n const poisoned = process.env.NODE_TLS_REJECT_UNAUTHORIZED === \"0\";\n delete process.env.NODE_TLS_REJECT_UNAUTHORIZED;\n return poisoned;\n}\n\nasync function handleResolveOptions(\n message: ResolveOptionsMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const { context, touched } = buildPropertyContext({\n searchValue: request.searchValue,\n projectId: request.projectId,\n // Design-time default: an empty flows listing instead of a throwing stub.\n flows: { list: () => Promise.resolve({ data: [] }) },\n ...(request.reactorAccess ? { reactor: new RemoteReactorService() } : {}),\n });\n const refresherValues = {\n ...(request.auth !== undefined ? { auth: request.auth } : {}),\n ...request.refresherValues,\n };\n const prop = findProperty(\n piece,\n request.actionName,\n request.propName,\n request.kind,\n );\n const output = await resolveDynamicProperty({\n piece,\n actionName: request.actionName,\n kind: request.kind,\n propName: request.propName,\n refresherValues,\n context,\n });\n // DYNAMIC props() yields raw piece properties (with resolver functions);\n // the editor only ever sees descriptors, so translate before crossing IPC.\n const isDynamic =\n typeof prop.props === \"function\" && typeof prop.options !== \"function\";\n return {\n id: message.id,\n type: \"result\",\n output: isDynamic\n ? describeProperties(output as Record<string, ApProperty> | undefined)\n : jsonSafe(output),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\n// Reads a FILE prop's attachment ref from the copy the host staged on disk.\n// The fork shares the filesystem with its parent, so this is what keeps a\n// 50 MB scan out of the IPC channel in both directions.\nfunction stagedInputResolver(\n inputs: StagedInput[] | undefined,\n): NormalizeOptions[\"resolveRef\"] {\n // An empty list is not the same as no list: it means the host has a store\n // and tried, so a FILE prop that still comes up short is told which\n // reference failed rather than that the context has no resolver.\n if (!inputs) return undefined;\n const byRef = new Map(inputs.map((input) => [input.ref, input]));\n return async (ref: string) => {\n const staged = byRef.get(ref);\n if (!staged) {\n throw new Error(`No staged file for reference \"${ref}\"`);\n }\n return {\n data: await readFile(staged.path),\n filename: staged.fileName,\n contentType: staged.contentType,\n };\n };\n}\n\n// The same refusal describe records, for a step or hook that reaches the\n// worker anyway: a workflow saved before the check, or built over the API.\nfunction assertRunnable(\n piece: ApPiece,\n pieceName: string,\n auth: unknown,\n trigger?: { name: string; trigger: ApTrigger },\n): void {\n // With several methods, the one this connection signs in with decides.\n const type = (auth as { type?: unknown } | null | undefined)?.type;\n const method =\n Array.isArray(piece.auth) && type !== undefined\n ? authMethodFor(piece.auth, type)\n : piece.auth;\n if (Array.isArray(piece.auth) && type !== undefined && !method) {\n throw new Error(\n `Piece \"${pieceName}\" has no ${String(type)} sign-in method for this connection`,\n );\n }\n const pieceFeature = unsupportedAuth(method);\n if (pieceFeature) {\n throw new UnsupportedPieceFeatureError(\n `Piece \"${pieceName}\"`,\n pieceFeature,\n );\n }\n const triggerFeature = trigger && unsupportedTrigger(trigger.trigger);\n if (triggerFeature) {\n throw new UnsupportedPieceFeatureError(\n `Trigger \"${trigger.name}\" of \"${pieceName}\"`,\n triggerFeature,\n );\n }\n}\n\nasync function handleRun(message: RunMessage): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const action = getActions(piece)[request.actionName] as\n | ReturnType<typeof getActions>[string]\n | undefined;\n if (!action) {\n throw new Error(\n `No action \"${request.actionName}\" in ${pieceRefKey(request)}`,\n );\n }\n assertRunnable(piece, piece.displayName, request.auth);\n const files = request.stagingDir\n ? new StagedFilesService(request.stagingDir)\n : new DataUriFilesService();\n // A durable store answers every get/put over the call channel, so a write\n // survives this worker; without one the value lives only in this heap.\n const durableStore = request.durableStore\n ? new RemoteKeyValueStore()\n : undefined;\n const liveOutput = request.liveOutput ? new RemoteOutput() : undefined;\n // Host-served reactor access, for a piece that ships inside a reactor package.\n const reactor = request.reactorAccess\n ? new RemoteReactorService()\n : undefined;\n // Before the props are normalised, not after: a processor that cannot coerce\n // says so on console.error, and the worker's stdio goes nowhere.\n const restoreConsole = request.captureLogs ? captureConsole() : undefined;\n const { context, touched } = buildActionContext({\n propsValue: await preparePropsValue(\n `action \"${request.actionName}\"`,\n action.props,\n request.propsValue,\n { resolveRef: stagedInputResolver(request.stagedInputs) },\n ),\n auth: request.auth,\n store:\n durableStore ??\n (request.storeScope ? storeForScope(request.storeScope) : undefined),\n files,\n connections: request.connections\n ? new InMemoryConnectionsProvider(request.connections)\n : undefined,\n output: liveOutput,\n reactor,\n executionType: request.executionType,\n identity: request.identity,\n });\n let output: unknown;\n try {\n output = await action.run(context);\n } finally {\n restoreConsole?.();\n liveOutput?.close();\n }\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n ...(files instanceof StagedFilesService && files.staged().length > 0\n ? { files: files.staged() }\n : {}),\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleTriggerHook(\n message: TriggerHookMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const trigger = getTriggers(piece)[request.triggerName] as\n | ReturnType<typeof getTriggers>[string]\n | undefined;\n if (!trigger) {\n throw new Error(\n `No trigger \"${request.triggerName}\" in bundle ${request.bundleDir}`,\n );\n }\n // Teardown still runs, so a registration made before the check is released.\n if (request.hook !== \"onDisable\") {\n assertRunnable(piece, piece.displayName, request.auth, {\n name: request.triggerName,\n trigger,\n });\n }\n // The durable store answers every get/put over the call channel, so a long\n // onEnable checkpoints: registration ids survive a crash mid-hook.\n const snapshot = request.durableStore\n ? undefined\n : new InMemoryKeyValueStore(request.storeState);\n const runsPiece = request.hook === \"run\" || request.hook === \"test\";\n // Teardown is never refused: a config that no longer validates must still\n // release what onEnable registered.\n const propsValue =\n request.hook === \"onDisable\"\n ? await normalizePropsValue(trigger.props, request.propsValue)\n : await preparePropsValue(\n `trigger \"${request.triggerName}\"`,\n trigger.props,\n request.propsValue,\n );\n const handle = buildTriggerContext({\n propsValue,\n auth: request.auth,\n store: snapshot ?? new RemoteKeyValueStore(),\n hostPartitionedStore: request.durableStore,\n // Test hooks write under a separate prefix, never the live cursor.\n storePrefix: request.hook === \"test\" ? \"test\" : \"\",\n identity: request.identity,\n isRepublish: request.isRepublish,\n payload: request.payload,\n webhookUrl: request.webhookUrl,\n server: request.server,\n files: runsPiece ? new DataUriFilesService() : undefined,\n });\n const output = await runTriggerHook(trigger, request.hook, handle);\n return {\n id: message.id,\n type: \"result\",\n output: jsonSafe(output),\n touched: [...handle.touched],\n tlsPoisoned: consumeTlsFlag(),\n // Only the snapshot path has state to hand back; a durable store already\n // committed everything the hook wrote.\n ...(snapshot\n ? { storeState: jsonSafe(snapshot.snapshot()) as Record<string, unknown> }\n : {}),\n schedules: handle.schedules,\n listeners: handle.listeners,\n };\n}\n\n// What auth.validate and auth.getConnectionIdentifier are handed upstream: the\n// property values themselves, not the connection envelope an action receives.\nfunction authForValidate(auth: unknown): unknown {\n if (auth === null || typeof auth !== \"object\") return auth;\n const value = auth as Record<string, unknown>;\n switch (value.type) {\n case \"CUSTOM_AUTH\":\n return value.props;\n case \"SECRET_TEXT\":\n return value.secret_text;\n case \"BASIC_AUTH\":\n return { username: value.username, password: value.password };\n default:\n return auth;\n }\n}\n\n// `{ valid: false, error }` (or a bare `false`) fails the check.\nfunction fromValidateResult(\n result: unknown,\n): Pick<CheckConnectionOutcome, \"valid\" | \"detail\"> {\n if (result === false) return { valid: false };\n if (result === null || typeof result !== \"object\") return { valid: true };\n const value = result as { valid?: unknown; error?: unknown };\n if (value.valid !== false) return { valid: true };\n return {\n valid: false,\n ...(typeof value.error === \"string\" && value.error\n ? { detail: value.error }\n : {}),\n };\n}\n\n// Best-effort: a label failure is reported beside a passing check.\nasync function connectionIdentifier(\n getConnectionIdentifier: (context: unknown) => unknown,\n context: unknown,\n): Promise<Pick<CheckConnectionOutcome, \"accountLabel\" | \"identifierError\">> {\n try {\n const label = await getConnectionIdentifier(context);\n return typeof label === \"string\" && label !== \"\"\n ? { accountLabel: label }\n : {};\n } catch (error) {\n return {\n identifierError: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n // With several methods, the hooks are the ones of the connection's method.\n const auth = authMethodFor(\n (piece as { auth?: unknown }).auth,\n (request.auth as { type?: unknown } | null | undefined)?.type,\n ) as\n | {\n validate?: (context: unknown) => unknown;\n getConnectionIdentifier?: (context: unknown) => unknown;\n }\n | undefined;\n const validate = auth?.validate;\n const getConnectionIdentifier = auth?.getConnectionIdentifier;\n const { context, touched } = buildCheckConnectionContext({\n auth: authForValidate(request.auth),\n });\n let outcome: CheckConnectionOutcome =\n typeof validate === \"function\"\n ? { declared: true, ...fromValidateResult(await validate(context)) }\n : { declared: false, valid: true };\n if (outcome.valid && typeof getConnectionIdentifier === \"function\") {\n outcome = {\n ...outcome,\n ...(await connectionIdentifier(getConnectionIdentifier, context)),\n };\n }\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [...touched],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nasync function handleDescribe(\n message: DescribePieceMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const descriptor = buildDescriptor(piece, {\n packageName: request.packageName,\n version: request.version,\n });\n return {\n id: message.id,\n type: \"result\",\n // A prop's defaultValue is piece-authored; jsonSafe keeps a non-cloneable\n // one from failing the IPC send.\n output: jsonSafe(descriptor),\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n}\n\nfunction isWorkerMessage(value: unknown): value is WorkerRequestMessage {\n if (typeof value !== \"object\" || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === \"run\" ||\n type === \"resolve-options\" ||\n type === \"trigger-hook\" ||\n type === \"check-connection\" ||\n type === \"describe\"\n );\n}\n\nfunction dispatch(message: WorkerRequestMessage): Promise<WorkerResponse> {\n switch (message.type) {\n case \"run\":\n return handleRun(message);\n case \"resolve-options\":\n return handleResolveOptions(message);\n case \"trigger-hook\":\n return handleTriggerHook(message);\n case \"check-connection\":\n return handleCheckConnection(message);\n case \"describe\":\n return handleDescribe(message);\n }\n}\n\nprocess.on(\"message\", (message: unknown) => {\n if (!isWorkerMessage(message)) return;\n // Deferred so a synchronous throw — a malformed egress policy — becomes a\n // rejection the handler below reports, instead of killing the child.\n const handler = Promise.resolve().then(() => {\n setMaxFileBytes(message.request.maxFileBytes);\n return runWithEgressPolicy(message.request.egress, () => dispatch(message));\n });\n handler\n .catch((error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(message)),\n tlsPoisoned: consumeTlsFlag(),\n }))\n .then((response) => process.send?.(response))\n .catch(() => process.exit(1));\n});\n"],"mappings":";;;;;;AASA,MAAM,+BAA+B;AASrC,MAAM,0BAAU,IAAI,IAAqB;AACzC,IAAI,SAAS;AACb,IAAI,YAAY;AAEhB,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,QAAgB,QAAgB;EAC1C,MAAM,cAAc,OAAO,YAAY,QAAQ;EAC/C,KAAK,OAAO;CACd;AACF;AAEA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,QAAgB,WAAmB;EAC7C,MAAM,cAAc,OAAO,yBAAyB,UAAU,GAAG;EACjE,KAAK,OAAO;CACd;AACF;AAEA,SAAS,mBAAmB,OAA2C;CACrE,OACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS;AAE3C;AAIA,SAAS,kBAAwB;CAC/B,IAAI,WAAW;CACf,YAAY;CACZ,QAAQ,GAAG,YAAY,YAAqB;EAC1C,IAAI,CAAC,mBAAmB,OAAO,GAAG;EAClC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,EAAE;EACpC,IAAI,CAAC,OAAO;EACZ,QAAQ,OAAO,QAAQ,EAAE;EACzB,aAAa,MAAM,KAAK;EACxB,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AC1C,IAAI,CAAC,gBAAgB,OAAO,GAAG;CAO/B,QAJwB,QAAQ,CAAC,CAAC,WAAW;EAC3C,gBAAgB,QAAQ,QAAQ,YAAY;EAC5C,OAAO,oBAAoB,QAAQ,QAAQ,cAAc,SAAS,OAAO,CAAC;CAC5E,CACM,CAAC,CACJ,OAAO,WAAoC;EAC1C,IAAI,QAAQ;EACZ,MAAM;EACN,OAAO,eAAe,OAAO,eAAe,OAAO,CAAC;EACpD,aAAa,eAAe;CAC9B,EAAE,CAAC,CACF,MAAM,aAAa,QAAQ,OAAO,QAAQ,CAAC,CAAC,CAC5C,YAAY,QAAQ,KAAK,CAAC,CAAC;AAChC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerhousedao/reactor-workflow",
3
- "version": "6.2.3-dev.24",
3
+ "version": "6.2.3-dev.26",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -29,12 +29,12 @@
29
29
  "./package.json": "./package.json"
30
30
  },
31
31
  "dependencies": {
32
- "@powerhousedao/pieces-framework": "6.2.3-dev.24",
33
- "@powerhousedao/reactor": "6.2.3-dev.24",
34
- "@powerhousedao/shared": "6.2.3-dev.24",
35
- "@powerhousedao/workflow": "6.2.3-dev.24",
32
+ "@powerhousedao/pieces-framework": "6.2.3-dev.26",
33
+ "@powerhousedao/reactor": "6.2.3-dev.26",
34
+ "@powerhousedao/shared": "6.2.3-dev.26",
35
+ "@powerhousedao/workflow": "6.2.3-dev.26",
36
36
  "croner": "10.0.1",
37
- "document-model": "6.2.3-dev.24",
37
+ "document-model": "6.2.3-dev.26",
38
38
  "graphql": "^16"
39
39
  },
40
40
  "devDependencies": {
@@ -42,7 +42,7 @@
42
42
  "@types/node": "25.2.3",
43
43
  "kysely": "0.28.16",
44
44
  "kysely-pglite-dialect": "1.2.0",
45
- "tsdown": "0.21.1",
45
+ "tsdown": "0.23.0",
46
46
  "vitest": "4.1.1"
47
47
  },
48
48
  "description": "The Powerhouse workflow engine: the reactor-side runtime that runs workflow documents, and the piece loader, worker pool and executor beneath it.",
@@ -1 +0,0 @@
1
- {"version":3,"file":"descriptor-E4swpRpd.js","names":[],"sources":["../src/pieces/activepieces/loader.ts","../src/pieces/activepieces/descriptor.ts"],"sourcesContent":["import { readFileSync, realpathSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { ApPiece } from \"./types.js\";\n\nexport interface LoadedPiece {\n piece: ApPiece;\n entryPath: string;\n // Which duck-type check identified the export.\n check: \"constructor-name\" | \"structural\";\n}\n\n// Resolves a bundle's entry file. Published bundles typically carry only\n// `main` (no `exports`, no `type` — they are CJS).\nexport function resolveEntry(pieceDir: string): string {\n const raw = readFileSync(path.join(pieceDir, \"package.json\"), \"utf8\");\n const pkg = JSON.parse(raw) as {\n main?: string;\n module?: string;\n exports?: Record<string, unknown>;\n };\n const dotExport = pkg.exports?.[\".\"];\n const candidates: (string | undefined)[] = [];\n if (typeof dotExport === \"string\") candidates.push(dotExport);\n if (dotExport && typeof dotExport === \"object\") {\n const cond = dotExport as Record<string, unknown>;\n for (const key of [\"import\", \"require\", \"default\"]) {\n const value = cond[key];\n if (typeof value === \"string\") candidates.push(value);\n }\n }\n candidates.push(pkg.main, pkg.module, \"src/index.js\", \"index.js\", \"main.js\");\n // A bundle's manifest (or a symlink inside it) must not point the entry\n // outside pieceDir; realpath so a symlink can't launder the escape.\n const root = realpathSync(pieceDir);\n const rootWithSep = root + path.sep;\n for (const candidate of candidates) {\n if (!candidate) continue;\n const abs = path.resolve(pieceDir, candidate);\n let real: string;\n try {\n real = realpathSync(abs);\n } catch {\n continue; // candidate doesn't exist; try the next one\n }\n if (real !== root && !real.startsWith(rootWithSep)) continue;\n return abs;\n }\n throw new Error(`No entry file found for piece bundle at ${pieceDir}`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n// Identify the piece by constructor name (their own loader's check), falling\n// back to structure for bundles minified without keepNames. No `instanceof`.\nfunction findPiece(\n mod: Record<string, unknown>,\n): Pick<LoadedPiece, \"piece\" | \"check\"> | undefined {\n const candidates: unknown[] = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n // `constructor?.name`: a bundle may export an Object.create(null), and the\n // real piece is usually beside it in the same module.\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return {\n piece: candidate as unknown as ApPiece,\n check: \"constructor-name\",\n };\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return { piece: candidate as unknown as ApPiece, check: \"structural\" };\n }\n }\n return undefined;\n}\n\n// A module the piece names and node cannot find. Dependencies are installed\n// with scripts disabled, so a native or downloaded one looks like this.\nfunction missingModule(entryPath: string, error: unknown): Error | undefined {\n const code = (error as { code?: unknown } | null)?.code;\n if (code !== \"ERR_MODULE_NOT_FOUND\" && code !== \"MODULE_NOT_FOUND\") {\n return undefined;\n }\n const detail = error instanceof Error ? error.message : String(error);\n return new Error(\n `Piece at ${entryPath} could not be loaded: it imports a module that is ` +\n `not there. Its dependencies are installed with lifecycle scripts ` +\n `disabled, so one that compiles or downloads on install -- a native ` +\n `addon, a browser download -- cannot be prepared here. ${detail}`,\n );\n}\n\n// ESM-first `import()` — Node's CJS interop handles the typical CJS bundle —\n// with a `require` fallback.\nexport async function loadPiece(entryPath: string): Promise<LoadedPiece> {\n let mod: Record<string, unknown>;\n try {\n mod = (await import(\n /* @vite-ignore */ pathToFileURL(entryPath).href\n )) as Record<string, unknown>;\n } catch (imported) {\n try {\n const require = createRequire(import.meta.url);\n mod = require(entryPath) as Record<string, unknown>;\n } catch (required) {\n // The import's error names the missing module; require's often names\n // only the entry it was handed.\n throw (\n missingModule(entryPath, imported) ??\n missingModule(entryPath, required) ??\n required\n );\n }\n }\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n `No Piece export found in ${entryPath}. Export keys: ${Object.keys(mod).join(\", \")}`,\n );\n }\n return { ...found, entryPath };\n}\n\nexport async function loadPieceFromDir(pieceDir: string): Promise<LoadedPiece> {\n return loadPiece(resolveEntry(pieceDir));\n}\n","import {\n getActions,\n getTriggers,\n type ApPiece,\n type ApProperty,\n type ApPropertyType,\n type ApDropdownOption,\n type ApTrigger,\n type ApTriggerStrategy,\n} from \"./types.js\";\nimport {\n unsupportedAuth,\n unsupportedTrigger,\n type UnsupportedFeature,\n} from \"./unsupported.js\";\n\nexport interface PiecePropDescriptor {\n name: string;\n displayName: string;\n description?: string;\n placeholder?: string;\n type: ApPropertyType;\n required: boolean;\n defaultValue?: unknown;\n // STATIC_DROPDOWN choices, extracted so the editor needs no runtime call.\n staticOptions?: ApDropdownOption[];\n // True when the prop carries a design-time resolver (DROPDOWN options() / DYNAMIC props()).\n hasDynamicResolver: boolean;\n // Synthesised domain-provider id: activepieces:<pkg>#<action>.<prop> (doc 08 §6.3).\n // Only top-level props get one; nested resolvers are not addressable yet.\n dynamicResolverId?: string;\n // Sibling prop names whose values feed the resolver; the editor re-runs\n // it when any of them changes.\n refreshers?: string[];\n // Nested shape: an ARRAY item's fields, or the props a DYNAMIC resolver\n // produced (see describeProperties). OBJECT props are free-form and carry none.\n properties?: PiecePropDescriptor[];\n}\n\nexport interface PieceActionDescriptor {\n name: string;\n displayName: string;\n description?: string;\n // UI metadata only — not a credential contract (spike finding).\n requireAuth: boolean;\n props: PiecePropDescriptor[];\n // Carried verbatim: it is what the expression picker builds a later step's\n // field list from, and a package piece has no published listing to read.\n outputSchema?: unknown;\n // Orders the action picker, so a package piece that declares it must be\n // ordered by it too rather than counting as unset.\n audience?: string;\n}\n\nexport interface PieceTriggerDescriptor {\n name: string;\n displayName: string;\n description?: string;\n strategy: ApTriggerStrategy;\n testStrategy?: string;\n requireAuth: boolean;\n props: PiecePropDescriptor[];\n outputSchema?: unknown;\n hasSampleData: boolean;\n // The sample itself, not just whether there is one: a trigger that declares\n // no outputSchema is read for its shape instead.\n sampleData?: unknown;\n // How the sender proves the endpoint exists before it will register it.\n // Absent when the trigger declares no handshake, or declares NONE.\n handshake?: { strategy: string; paramName?: string };\n // A trigger feature the engine cannot run; the piece's own is on the piece.\n unsupported?: UnsupportedFeature;\n}\n\nexport interface PieceAuthDescriptor {\n type: ApPropertyType;\n displayName?: string;\n description?: string;\n required?: boolean;\n // CUSTOM_AUTH's own fields. Without them a connection form has nothing to\n // ask for, which is what a piece read from a package rather than a published\n // listing would otherwise leave the editor with.\n props?: PiecePropDescriptor[];\n}\n\n// NONE is how the framework spells \"no handshake\", so it is not carried:\n// a caller checking the field would otherwise have to know that too.\nfunction describeHandshake(\n trigger: ApTrigger,\n): { strategy: string; paramName?: string } | undefined {\n const strategy = trigger.handshakeConfiguration?.strategy;\n if (!strategy || strategy === \"NONE\") return undefined;\n return { strategy, paramName: trigger.handshakeConfiguration?.paramName };\n}\n\nexport interface PieceSource {\n packageName: string;\n version: string;\n}\n\n// Serializable descriptor of an adapted piece; the engine never learns\n// Activepieces exists (doc 08 §6.2).\nexport interface PieceDescriptor {\n id: string;\n source: PieceSource;\n displayName: string;\n description?: string;\n logoUrl?: string;\n categories?: string[];\n auth?: PieceAuthDescriptor;\n minimumSupportedRelease?: string;\n maximumSupportedRelease?: string;\n actions: PieceActionDescriptor[];\n triggers: PieceTriggerDescriptor[];\n // Set when no block of the piece can run here, e.g. an OAuth2 piece.\n unsupported?: UnsupportedFeature;\n}\n\nfunction hasResolver(prop: ApProperty): boolean {\n return typeof prop.options === \"function\" || typeof prop.props === \"function\";\n}\n\nfunction toPropDescriptor(\n name: string,\n prop: ApProperty,\n resolverId?: string,\n): PiecePropDescriptor {\n const dynamic = hasResolver(prop);\n const descriptor: PiecePropDescriptor = {\n name,\n displayName: prop.displayName ?? name,\n type: prop.type ?? \"UNKNOWN\",\n required: prop.required ?? false,\n hasDynamicResolver: dynamic,\n };\n if (typeof prop.description === \"string\" && prop.description !== \"\") {\n descriptor.description = prop.description;\n }\n if (typeof prop.placeholder === \"string\" && prop.placeholder !== \"\") {\n descriptor.placeholder = prop.placeholder;\n }\n if (prop.defaultValue !== undefined) {\n descriptor.defaultValue = prop.defaultValue;\n }\n if (dynamic && resolverId) {\n descriptor.dynamicResolverId = resolverId;\n }\n if (dynamic && Array.isArray(prop.refreshers)) {\n descriptor.refreshers = prop.refreshers.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n }\n if (typeof prop.options === \"object\" && Array.isArray(prop.options.options)) {\n descriptor.staticOptions = prop.options.options.map((o) => ({\n label: o.label,\n value: o.value,\n }));\n }\n if (prop.properties && typeof prop.properties === \"object\") {\n const nested = describeProperties(prop.properties);\n if (nested.length > 0) descriptor.properties = nested;\n }\n return descriptor;\n}\n\n// Descriptor list for a props map: nested ARRAY items and what a DYNAMIC\n// resolver returns, so the editor never sees raw piece properties.\nexport function describeProperties(\n props: Record<string, ApProperty> | null | undefined,\n resolverIdFor?: (propName: string) => string,\n): PiecePropDescriptor[] {\n if (!props || typeof props !== \"object\") return [];\n return Object.entries(props)\n .filter((entry): entry is [string, ApProperty] =>\n isPropertyObject(entry[1]),\n )\n .map(([propName, prop]) =>\n toPropDescriptor(propName, prop, resolverIdFor?.(propName)),\n );\n}\n\n// Bundles are duck-typed; a props map may carry non-object junk.\nfunction isPropertyObject(value: unknown): value is ApProperty {\n return value !== null && typeof value === \"object\";\n}\n\nfunction withUnsupported(feature: UnsupportedFeature | undefined): {\n unsupported?: UnsupportedFeature;\n} {\n return feature ? { unsupported: feature } : {};\n}\n\n// Pure translation over a loaded piece; performs no I/O and never executes\n// piece code beyond the actions()/triggers() accessors.\nexport function buildDescriptor(\n piece: ApPiece,\n source: PieceSource,\n): PieceDescriptor {\n const actions = Object.entries(getActions(piece)).map(\n ([actionName, action]): PieceActionDescriptor => ({\n name: action.name ?? actionName,\n displayName: action.displayName ?? actionName,\n description: action.description,\n requireAuth: action.requireAuth ?? false,\n props: describeProperties(\n action.props,\n (propName) =>\n `activepieces:${source.packageName}#${actionName}.${propName}`,\n ),\n ...(action.outputSchema !== undefined\n ? { outputSchema: action.outputSchema }\n : {}),\n ...(action.audience !== undefined ? { audience: action.audience } : {}),\n }),\n );\n\n const triggers = Object.entries(getTriggers(piece)).map(\n ([triggerName, trigger]): PieceTriggerDescriptor => ({\n name: trigger.name ?? triggerName,\n displayName: trigger.displayName ?? triggerName,\n description: trigger.description,\n strategy: trigger.type ?? \"UNKNOWN\",\n testStrategy: trigger.testStrategy,\n requireAuth: trigger.requireAuth ?? false,\n props: describeProperties(\n trigger.props,\n (propName) =>\n `activepieces:${source.packageName}#${triggerName}.${propName}`,\n ),\n ...(trigger.outputSchema !== undefined\n ? { outputSchema: trigger.outputSchema }\n : {}),\n hasSampleData:\n trigger.sampleData !== undefined && trigger.sampleData !== null,\n ...(trigger.sampleData !== undefined && trigger.sampleData !== null\n ? { sampleData: trigger.sampleData }\n : {}),\n handshake: describeHandshake(trigger),\n ...withUnsupported(unsupportedTrigger(trigger)),\n }),\n );\n\n const descriptor: PieceDescriptor = {\n id: `activepieces:${source.packageName}`,\n source,\n displayName: piece.displayName,\n description: piece.description,\n logoUrl: piece.logoUrl,\n categories: piece.categories,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n actions,\n triggers,\n ...withUnsupported(unsupportedAuth(piece.auth)),\n };\n if (Array.isArray(piece.auth)) return descriptor;\n if (piece.auth && typeof piece.auth === \"object\") {\n // CUSTOM_AUTH carries a record here; a DYNAMIC prop would carry a\n // resolver function, which is not an auth shape at all.\n const authProps =\n piece.auth.props && typeof piece.auth.props === \"object\"\n ? describeProperties(piece.auth.props)\n : [];\n descriptor.auth = {\n type: piece.auth.type ?? \"UNKNOWN\",\n displayName: piece.auth.displayName,\n description: piece.auth.description,\n required: piece.auth.required,\n ...(authProps.length > 0 ? { props: authProps } : {}),\n };\n }\n return descriptor;\n}\n"],"mappings":";;;;;;AAeA,SAAgB,aAAa,UAA0B;CACrD,MAAM,MAAM,aAAa,KAAK,KAAK,UAAU,eAAe,EAAE,OAAO;CACrE,MAAM,MAAM,KAAK,MAAM,IAAI;CAK3B,MAAM,YAAY,IAAI,UAAU;CAChC,MAAM,aAAqC,EAAE;AAC7C,KAAI,OAAO,cAAc,SAAU,YAAW,KAAK,UAAU;AAC7D,KAAI,aAAa,OAAO,cAAc,UAAU;EAC9C,MAAM,OAAO;AACb,OAAK,MAAM,OAAO;GAAC;GAAU;GAAW;GAAU,EAAE;GAClD,MAAM,QAAQ,KAAK;AACnB,OAAI,OAAO,UAAU,SAAU,YAAW,KAAK,MAAM;;;AAGzD,YAAW,KAAK,IAAI,MAAM,IAAI,QAAQ,gBAAgB,YAAY,UAAU;CAG5E,MAAM,OAAO,aAAa,SAAS;CACnC,MAAM,cAAc,OAAO,KAAK;AAChC,MAAK,MAAM,aAAa,YAAY;AAClC,MAAI,CAAC,UAAW;EAChB,MAAM,MAAM,KAAK,QAAQ,UAAU,UAAU;EAC7C,IAAI;AACJ,MAAI;AACF,UAAO,aAAa,IAAI;UAClB;AACN;;AAEF,MAAI,SAAS,QAAQ,CAAC,KAAK,WAAW,YAAY,CAAE;AACpD,SAAO;;AAET,OAAM,IAAI,MAAM,2CAA2C,WAAW;;AAGxE,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAKhD,SAAS,UACP,KACkD;CAClD,MAAM,aAAwB;EAC5B,GAAG,OAAO,OAAO,IAAI;EACrB,GAAI,SAAS,IAAI,QAAQ,GAAG,OAAO,OAAO,IAAI,QAAQ,GAAG,EAAE;EAC3D,IAAI;EACL;AACD,MAAK,MAAM,aAAa,WAGtB,KAAI,SAAS,UAAU,IAAI,UAAU,aAAa,SAAS,QACzD,QAAO;EACL,OAAO;EACP,OA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K,CAAE,QAAO;AACtC,KAAI,MAAM,QAAQ,OAAO,MAAM,SAAS,UAAU;EAGhD,MAAM,YACJ,MAAM,KAAK,SAAS,OAAO,MAAM,KAAK,UAAU,WAC5C,mBAAmB,MAAM,KAAK,MAAM,GACpC,EAAE;AACR,aAAW,OAAO;GAChB,MAAM,MAAM,KAAK,QAAQ;GACzB,aAAa,MAAM,KAAK;GACxB,aAAa,MAAM,KAAK;GACxB,UAAU,MAAM,KAAK;GACrB,GAAI,UAAU,SAAS,IAAI,EAAE,OAAO,WAAW,GAAG,EAAE;GACrD;;AAEH,QAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"piece-registry-q4bgYbXa.d.ts","names":[],"sources":["../src/pieces/activepieces/types.ts","../src/pieces/activepieces/fetch.ts","../src/pieces/activepieces/loader.ts","../src/pieces/activepieces/unsupported.ts","../src/pieces/activepieces/descriptor.ts","../src/pieces/activepieces/context/store-scope.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/action.ts","../src/pieces/activepieces/context/trigger.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/resolver.ts","../src/pieces/activepieces/worker/transport.ts","../src/pieces/activepieces/worker/host.ts","../src/pieces/activepieces/worker/pool.ts","../src/pieces/engine/types.ts","../src/pieces/engine/secrets.ts","../src/pieces/engine/connections.ts","../src/pieces/engine/blocks.ts","../src/pieces/engine/coordinator.ts","../src/reactor/piece-registry.ts"],"mappings":";;;KAiBY,cAAA;AAAA,KAEA,gBAAA,GAAmB,IAAA,CAAK,cAAA;AAAA,KAGxB,qBAAA,GAAwB,IAAA,CAClC,aAAA;EAEI,OAAA,EAAS,gBAAA;AAAA;AAAA,KAIH,UAAA,GAAa,OAAA,CACvB,IAAA,CAAK,kBAAA,oDAEL,OAAA,CAAQ,IAAA,CAAK,gBAAA;EACX,IAAA,GAAO,cAAA;EACP,QAAA;EACA,YAAA;EACA,OAAA,GAAU,qBAAA,QAA6B,IAAA;EAEvC,KAAA,OA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