@powerhousedao/reactor-workflow 6.2.3-dev.19 → 6.2.3-dev.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -16
- package/dist/{descriptor-CRkDqx3C.js → descriptor-Doax7KPd.js} +19 -5
- package/dist/descriptor-Doax7KPd.js.map +1 -0
- package/dist/index.d.ts +15 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +380 -61
- package/dist/index.js.map +1 -1
- package/dist/{piece-registry-DWTQoft_.d.ts → piece-registry-BH39cD-k.d.ts} +30 -9
- package/dist/piece-registry-BH39cD-k.d.ts.map +1 -0
- package/dist/{piece-registry-WukyH-O-.js → piece-registry-lsGsY9fT.js} +178 -35
- package/dist/piece-registry-lsGsY9fT.js.map +1 -0
- package/dist/{redact-C7LWgAyD.js → redact-ChAU8USo.js} +16 -12
- package/dist/redact-ChAU8USo.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +3 -3
- package/dist/worker-entry.js +6 -3
- package/dist/worker-entry.js.map +1 -1
- package/package.json +6 -6
- package/dist/descriptor-CRkDqx3C.js.map +0 -1
- package/dist/piece-registry-DWTQoft_.d.ts.map +0 -1
- package/dist/piece-registry-WukyH-O-.js.map +0 -1
- package/dist/redact-C7LWgAyD.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redact-ChAU8USo.js","names":[],"sources":["../src/pieces/activepieces/types.ts","../src/pieces/activepieces/context/stubs.ts","../src/pieces/activepieces/worker/protocol.ts","../src/pieces/activepieces/worker/json-safe.ts","../src/pieces/activepieces/context/store-scope.ts","../src/pieces/activepieces/context/action.ts","../src/pieces/activepieces/context/limits.ts","../src/pieces/activepieces/context/files.ts","../src/pieces/activepieces/context/trigger.ts","../src/pieces/activepieces/worker/egress.ts","../src/pieces/activepieces/worker/redact.ts"],"sourcesContent":["// Structural types for published Activepieces bundles (Path B). Bundles inline\n// their framework, so all typing is duck-typed — see ../../10-spike-notes-s6a.md.\nimport type {\n ActionBase,\n BasePropertySchema,\n DropdownOption,\n DropdownProperty,\n DropdownState,\n PieceBase,\n TriggerBase,\n WebhookHandshakeConfiguration,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { DEDUPE_KEY_PROPERTY } from \"@powerhousedao/pieces-framework\";\n\n// Widened from the framework's PropertyType: a bundle inlines its own copy of\n// the enum, so a value read off one is compared as a string, never by identity.\nexport type ApPropertyType = string;\n\nexport type ApDropdownOption = Pick<DropdownOption<unknown>, \"label\" | \"value\">;\n\n// STATIC_DROPDOWN options are plain data; DROPDOWN options is a resolver function.\nexport type ApStaticDropdownState = Pick<\n DropdownState<unknown>,\n \"disabled\" | \"placeholder\"\n> & { options: ApDropdownOption[] };\n\n// Every field optional: an unknown bundle version may omit any of them, and a\n// missing field must read as absent rather than fail the descriptor.\nexport type ApProperty = Partial<\n Pick<BasePropertySchema, \"displayName\" | \"description\" | \"placeholder\">\n> &\n Partial<Pick<DropdownProperty<unknown, boolean>, \"refreshers\">> & {\n type?: ApPropertyType;\n required?: boolean;\n defaultValue?: unknown;\n options?: ApStaticDropdownState | ((...args: unknown[]) => unknown);\n // Resolver function on DYNAMIC properties.\n props?: (...args: unknown[]) => unknown;\n // ARRAY: schema of each item's fields; absent for plain value arrays.\n properties?: Record<string, ApProperty>;\n };\n\n// requireAuth is UI metadata only — pieces run without auth despite it (spike finding).\nexport type ApAction = Partial<\n Pick<ActionBase, \"name\" | \"displayName\" | \"description\" | \"requireAuth\">\n> & {\n props?: Record<string, ApProperty>;\n // Authored shape of run()'s return, for the expression picker. Plain data,\n // and never validated against — a piece may return whatever it likes.\n outputSchema?: unknown;\n // \"human\" | \"ai\" | \"both\"; absent counts as human-visible.\n audience?: string;\n run: (ctx: unknown) => Promise<unknown>;\n};\n\n// Widened from TriggerStrategy for the same reason as ApPropertyType:\n// WEBHOOK | POLLING | MANUAL | APP_WEBHOOK, read off a foreign bundle's enum.\nexport type ApTriggerStrategy = string;\n\n// strategy widened from WebhookHandshakeStrategy: NONE | HEADER_PRESENT |\n// QUERY_PRESENT | BODY_PARAM_PRESENT | HEAD_REQUEST.\nexport type ApHandshakeConfiguration = Partial<\n Omit<WebhookHandshakeConfiguration, \"strategy\">\n> & { strategy?: string };\n\nexport type ApTrigger = Partial<\n Pick<\n TriggerBase,\n \"name\" | \"displayName\" | \"description\" | \"requireAuth\" | \"sampleData\"\n >\n> & {\n type?: ApTriggerStrategy;\n // Widened from TriggerTestStrategy: SIMULATION | TEST_FUNCTION.\n testStrategy?: string;\n props?: Record<string, ApProperty>;\n outputSchema?: unknown;\n handshakeConfiguration?: ApHandshakeConfiguration;\n onEnable?: (ctx: unknown) => Promise<void>;\n onDisable?: (ctx: unknown) => Promise<void>;\n onStart?: (ctx: unknown) => Promise<unknown>;\n run?: (ctx: unknown) => Promise<unknown[]>;\n test?: (ctx: unknown) => Promise<unknown[]>;\n onHandshake?: (ctx: unknown) => Promise<unknown>;\n onRenew?: (ctx: unknown) => Promise<void>;\n};\n\n// `categories` is widened from PieceCategory[] for the cross-bundle reason\n// above; `auth` is the raw property, not the framework's PieceAuthProperty.\nexport type ApPiece = Pick<PieceBase, \"displayName\"> &\n Partial<\n Pick<\n PieceBase,\n | \"description\"\n | \"logoUrl\"\n | \"authors\"\n | \"minimumSupportedRelease\"\n | \"maximumSupportedRelease\"\n >\n > & {\n categories?: string[];\n auth?: ApProperty;\n // A bundle exposes these as the built record or as a zero-arg method; the\n // framework's own Piece class only ever has the method.\n actions?: Record<string, ApAction> | (() => Record<string, ApAction>);\n triggers?: Record<string, ApTrigger> | (() => Record<string, ApTrigger>);\n getAction?: (name: string) => ApAction | undefined;\n getTrigger?: (name: string) => ApTrigger | undefined;\n metadata?: () => Record<string, unknown>;\n };\n\n// Normalizes the record-vs-method variants of `piece.actions`.\nexport function getActions(piece: ApPiece): Record<string, ApAction> {\n const actions =\n typeof piece.actions === \"function\" ? piece.actions() : piece.actions;\n return actions ?? {};\n}\n\n// Normalizes the record-vs-method variants of `piece.triggers`.\nexport function getTriggers(piece: ApPiece): Record<string, ApTrigger> {\n const triggers =\n typeof piece.triggers === \"function\" ? piece.triggers() : piece.triggers;\n return triggers ?? {};\n}\n","export class UnsupportedContextMemberError extends Error {\n readonly member: string;\n\n constructor(member: string) {\n super(\n `Piece used unimplemented context member \"${member}\". ` +\n `Implement it in the adapter or reject the piece at conformance time.`,\n );\n this.name = \"UnsupportedContextMemberError\";\n this.member = member;\n }\n}\n\n// Traps calls and member reads so both `ctx.files.write(...)` and\n// `ctx.server.apiUrl` throw with the full member path.\nexport function throwingStub(memberPath: string): unknown {\n return new Proxy(function stub() {}, {\n get(_target, prop) {\n // `then` and symbols stay inert so `await`/inspection don't false-trip.\n if (typeof prop !== \"string\" || prop === \"then\") return undefined;\n throw new UnsupportedContextMemberError(`${memberPath}.${prop}`);\n },\n apply() {\n throw new UnsupportedContextMemberError(memberPath);\n },\n });\n}\n\n// Wraps a context object so every top-level read is recorded; reads of\n// members outside the documented surface are flagged as UNDOCUMENTED.\nexport function withTouchTracking<T extends object>(\n base: T,\n touched: Set<string>,\n onTouch?: (member: string) => void,\n): T {\n return new Proxy(base, {\n get(target, prop, receiver) {\n if (typeof prop === \"string\" && prop !== \"then\") {\n const member = prop in target ? prop : `UNDOCUMENTED:${prop}`;\n touched.add(member);\n onTouch?.(member);\n }\n return Reflect.get(target, prop, receiver) as unknown;\n },\n });\n}\n","import type { ActionContextIdentity } from \"../context/action.js\";\nimport type { StagedFile } from \"../context/files.js\";\nimport type {\n ExecutionType,\n ServerContext,\n} from \"@powerhousedao/pieces-framework\";\nimport type { RecordedListener, RecordedSchedule } from \"../context/trigger.js\";\n\n// One FILE-prop value the host resolved to a path before the run, so the\n// bytes reach the worker through the shared filesystem instead of JSON IPC.\nexport interface StagedInput {\n ref: string;\n path: string;\n fileName?: string;\n contentType?: string;\n}\n\n// Where a piece may connect to while this request runs. Enforced in the child\n// at socket-connect time; absent means unrestricted, which is the old behaviour.\nexport interface EgressPolicy {\n // Hostnames (or literal IPs) the piece may reach; a leading \"*.\" matches\n // subdomains. Omitted or empty allows any host the address rules permit.\n allowHosts?: string[];\n // Addresses or CIDRs reachable even though they are private — a service on\n // the operator's own network, say.\n allowAddresses?: string[];\n // Lifts the private-address block, for an operator whose isolation lives\n // elsewhere. Local sockets, UDP and listening stay refused under any policy.\n allowPrivateAddresses?: boolean;\n // TCP ports the piece may reach; omitted or empty allows any.\n allowPorts?: number[];\n}\n\n// The child is forked with an empty env, so what the host's environment decides\n// can only arrive on the wire: every request carries what is in force for the\n// work it asks for.\nexport interface HostScopedRequest {\n egress?: EgressPolicy;\n // Ceiling for FILE-prop hydration and ctx.files.write, from the host's\n // PH_WORKFLOWS_PIECE_MAX_FILE_BYTES. Absent leaves the built-in default.\n maxFileBytes?: number;\n}\n\n// Where the worker finds the piece module: a bundle directory in npm shape, as\n// a registry fetch extracts it, or the module file of an installed package.\n\n// Exactly one is set; a request carrying neither is refused before any load.\nexport interface PieceModuleRef {\n bundleDir?: string;\n entryPath?: string;\n}\n\nexport interface RunActionRequest extends HostScopedRequest, PieceModuleRef {\n actionName: string;\n propsValue: Record<string, unknown>;\n auth?: unknown;\n // Where ctx.files.write() puts bytes for the host to ingest. Without it the\n // action gets the data-URI service instead.\n stagingDir?: string;\n // Attachment refs in propsValue, already materialized by the host.\n stagedInputs?: StagedInput[];\n // Resolved connection values served to ctx.connections.get(key).\n connections?: Record<string, unknown>;\n // Store partition; runs sharing a scope share state for the worker's lifetime.\n storeScope?: string;\n // Serve `ctx.store` from the host over the call channel instead of the\n // in-memory partition above, so a write survives this worker.\n durableStore?: boolean;\n // Forward the piece's console output to the host as it is written. Off by\n // default: a chatty piece would otherwise pay IPC for logs nobody reads.\n captureLogs?: boolean;\n // Implement `ctx.output.update`, which reports progress mid-step. Without\n // it the member keeps throwing, so a piece that needs it fails loudly.\n liveOutput?: boolean;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n // Concrete secret values resolved for this step, so the child can strip them\n // from an error before it crosses back; they already travel inside `auth`.\n redactValues?: string[];\n // Serve `ctx.reactor` over the call channel. Set only for a piece the host\n // loaded from an installed reactor package; a fetched bundle never gets it.\n reactorAccess?: boolean;\n}\n\nexport interface RunMessage {\n id: number;\n type: \"run\";\n request: RunActionRequest;\n}\n\n// Design-time resolution of a DROPDOWN options() / DYNAMIC props() resolver.\nexport interface ResolveOptionsRequest\n extends HostScopedRequest, PieceModuleRef {\n // Action or trigger name, per kind (default \"action\").\n actionName: string;\n kind?: \"action\" | \"trigger\";\n propName: string;\n refresherValues?: Record<string, unknown>;\n auth?: unknown;\n searchValue?: string;\n // As on a run: an options() resolver of a package piece may read the reactor\n // it is offering choices from.\n reactorAccess?: boolean;\n}\n\nexport interface ResolveOptionsMessage {\n id: number;\n type: \"resolve-options\";\n request: ResolveOptionsRequest;\n}\n\n// One trigger lifecycle hook. With `durableStore` its `ctx.store` is the same\n// host-served store an action gets, so a write lands as the hook makes it.\n\n// Without one it runs statelessly: `storeState` seeds an in-memory store and\n// the whole snapshot comes back in the response for the caller to persist.\nexport interface TriggerHookRequest extends HostScopedRequest, PieceModuleRef {\n triggerName: string;\n hook: \"onEnable\" | \"onDisable\" | \"run\" | \"test\" | \"onHandshake\";\n propsValue: Record<string, unknown>;\n auth?: unknown;\n storeState?: Record<string, unknown>;\n // Serve `ctx.store` from the host over the call channel, exactly as\n // RunActionRequest does, instead of seeding and returning the snapshot above.\n durableStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable of an unchanged trigger; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK payloads; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n server?: ServerContext;\n // As on a run request: secrets stripped from errors before they cross back.\n redactValues?: string[];\n}\n\nexport interface TriggerHookMessage {\n id: number;\n type: \"trigger-hook\";\n request: TriggerHookRequest;\n}\n\n// A connection credential check. Auth crosses into the worker and stays\n// there: the piece code that reads it never runs in the host process.\nexport interface CheckConnectionRequest\n extends HostScopedRequest, PieceModuleRef {\n auth?: unknown;\n}\n\nexport interface CheckConnectionMessage {\n id: number;\n type: \"check-connection\";\n request: CheckConnectionRequest;\n}\n\n// `output` of a check-connection result.\nexport interface CheckConnectionOutcome {\n // False when the piece declares no app.checkConnection.\n declared: boolean;\n // Its return value: void | boolean | { name | username | email | sub }.\n result?: unknown;\n}\n\n// Design-time descriptor of a piece: its actions, triggers and auth shape.\n// Building one requires the piece module, whose top-level code runs on load,\n// so it is built in the worker and only the plain descriptor crosses back.\nexport interface DescribePieceRequest\n extends HostScopedRequest, PieceModuleRef {\n // Carried through into the descriptor's `source` and its resolver ids.\n packageName: string;\n version: string;\n}\n\nexport interface DescribePieceMessage {\n id: number;\n type: \"describe\";\n request: DescribePieceRequest;\n}\n\nexport type WorkerRequestMessage =\n | RunMessage\n | ResolveOptionsMessage\n | TriggerHookMessage\n | CheckConnectionMessage\n | DescribePieceMessage;\n\n// Piece errors cross the IPC boundary as data; classify on these fields.\nexport interface SerializedPieceError {\n name: string;\n message: string;\n // The error's own enumerable properties, plus the HTTP status, request and\n // response the framework's error formatter recovered from it.\n properties: Record<string, unknown>;\n // Set when the piece hit an unimplemented context member.\n unsupportedMember?: string;\n}\n\nexport interface ResultResponse {\n id: number;\n type: \"result\";\n output: unknown;\n touched: string[];\n // True when the piece set NODE_TLS_REJECT_UNAUTHORIZED=0 (contained to the worker).\n tlsPoisoned: boolean;\n // Files the piece wrote through ctx.files during this request. The host\n // ingests each one, then rewrites its provisional token in `output`.\n files?: StagedFile[];\n // trigger-hook only: final store contents plus captured context calls.\n storeState?: Record<string, unknown>;\n schedules?: RecordedSchedule[];\n listeners?: RecordedListener[];\n}\n\nexport interface ErrorResponse {\n id: number;\n type: \"error\";\n error: SerializedPieceError;\n tlsPoisoned: boolean;\n}\n\nexport type WorkerResponse = ResultResponse | ErrorResponse;\n\n// A request the child makes of its host while a step is running: the reverse\n// direction of everything above, and the only way a piece reaches durable state.\n\n// Ids are the child's own counter, a separate space from the host's, which is\n// why every handler dispatches on `type` before comparing an id.\nexport interface HostCallMessage {\n id: number;\n type: \"host-call\";\n method: string;\n payload: unknown;\n}\n\n// `error` carries the failure as data: a rejected promise cannot cross IPC,\n// so the reply always arrives and the child rethrows.\nexport interface HostCallResponse {\n id: number;\n type: \"host-result\";\n value?: unknown;\n error?: string;\n}\n\n// What the host will answer for the request in flight. Registered per request,\n// so a call arriving after the step returned finds nothing and is refused.\nexport type HostCallHandlers = Record<\n string,\n (payload: unknown) => Promise<unknown>\n>;\n\n// The one-way half of the channel: a report the host may act on, with no\n// answer to wait for. Their engine splits the same way (rpc vs rpc-notify).\n\n// A tap must never stall the step, so these carry no id and no reply. Node's\n// IPC preserves order, which is what drains them before the result lands.\nexport interface HostNotifyMessage {\n type: \"host-notify\";\n method: string;\n payload: unknown;\n}\n\n// Handlers registered per request, like HostCallHandlers. A throw here is\n// swallowed: a failed tap must not fail the step it was reporting on.\nexport type HostNotifyHandlers = Record<string, (payload: unknown) => void>;\n\n// One console call the piece made, already flattened to a string in the child.\nexport interface PieceLogEntry {\n level: \"log\" | \"info\" | \"warn\" | \"error\" | \"debug\";\n message: string;\n at: number;\n}\n\nexport const LOG_WRITE = \"log.write\";\nexport const OUTPUT_UPDATE = \"output.update\";\n\n// A store call carries `{ key, value?, scope }`. The scope is a name the host\n// partitions on, never a prefix the child bakes into the key.\nexport const STORE_GET = \"store.get\";\nexport const STORE_PUT = \"store.put\";\nexport const STORE_DELETE = \"store.delete\";\n\n// A reactor call carries the operation's own input object; the host answers\n// with documents already projected to summaries (see context/reactor.ts).\nexport const REACTOR_MODELS = \"reactor.models\";\nexport const REACTOR_MODEL = \"reactor.model\";\nexport const REACTOR_GET = \"reactor.get\";\nexport const REACTOR_FIND = \"reactor.find\";\nexport const REACTOR_CREATE = \"reactor.create\";\nexport const REACTOR_EXECUTE = \"reactor.execute\";\n","// Everything the child sends crosses a structured-clone boundary. A piece's\n// own objects routinely do not survive it, so they are flattened first.\nexport function jsonSafe(value: unknown): unknown {\n try {\n return JSON.parse(JSON.stringify(value)) as unknown;\n } catch {\n return String(value);\n }\n}\n","// Their StoreScope, as a name the host can partition on.\nimport { StoreScope } from \"@powerhousedao/pieces-framework\";\n\n// The enum's PROJECT member carries the legacy value \"COLLECTION\", and an\n// omitted scope means FLOW, so both are folded to one name here.\nexport type StoreScopeName = keyof typeof StoreScope;\n\n// Compared by value, never by enum identity: a piece bundle inlines its own\n// copy of StoreScope, and some pass the member name instead of its value.\nexport function normalizeStoreScope(scope?: unknown): StoreScopeName {\n return scope === StoreScope.PROJECT || scope === \"PROJECT\"\n ? \"PROJECT\"\n : \"FLOW\";\n}\n","// Our ActionContext → their ActionContext (doc 06 §2.8). Implements the top usage\n// tier (propsValue, auth, store, connections); the rest throws loudly, named.\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport { jsonSafe } from \"../worker/json-safe.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type { ConnectionsProvider } from \"./props.js\";\nimport type {\n BaseContext,\n ConnectionsManager,\n ExecutionType,\n FilesService,\n FlowsContext,\n InputPropertyMap,\n OutputContext,\n ReactorService,\n RunContext,\n ServerContext,\n StepContext,\n Store,\n TagsManager,\n} from \"@powerhousedao/pieces-framework\";\n\nexport { UnsupportedContextMemberError } from \"./stubs.js\";\n\n// The scope travels beside the key rather than inside it: which partition a\n// key belongs to is the host's decision, not a naming convention.\n\n// The host's half of the framework's Store, with its generics dropped: a\n// durable store round-trips through JSON, so nothing comes back as the T put in.\nexport interface KeyValueStore {\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown>;\n get(key: string, scope?: StoreScopeName): Promise<unknown>;\n delete(key: string, scope?: StoreScopeName): Promise<void>;\n}\n\n// In-memory connection registry: key → resolved connection value.\nexport class InMemoryConnectionsProvider implements ConnectionsProvider {\n private readonly values: Map<string, unknown>;\n\n constructor(values: Record<string, unknown> = {}) {\n this.values = new Map(Object.entries(values));\n }\n\n set(key: string, value: unknown): void {\n this.values.set(key, value);\n }\n\n get(key: string): Promise<unknown> {\n return Promise.resolve(this.values.get(key) ?? null);\n }\n}\n\nexport class InMemoryKeyValueStore implements KeyValueStore {\n private readonly entries: Map<string, unknown>;\n\n constructor(seed: Record<string, unknown> = {}) {\n this.entries = new Map(Object.entries(seed));\n }\n\n snapshot(): Record<string, unknown> {\n return Object.fromEntries(this.entries);\n }\n\n // Flattened like the durable store, so the heap fallback is not the one\n // place a Date survives a put.\n put(key: string, value: unknown, scope?: StoreScopeName): Promise<unknown> {\n const stored = jsonSafe(value);\n this.entries.set(this.scoped(key, scope), stored);\n return Promise.resolve(stored);\n }\n\n get(key: string, scope?: StoreScopeName): Promise<unknown> {\n return Promise.resolve(this.entries.get(this.scoped(key, scope)) ?? null);\n }\n\n delete(key: string, scope?: StoreScopeName): Promise<void> {\n this.entries.delete(this.scoped(key, scope));\n return Promise.resolve();\n }\n\n // One heap, so the scopes share it and are kept apart by name.\n private scoped(key: string, scope?: StoreScopeName): string {\n return scope === \"PROJECT\" ? `PROJECT:${key}` : key;\n }\n}\n\nexport interface ActionContextIdentity {\n runId?: string;\n projectId?: string;\n flowId?: string;\n flowVersionId?: string;\n stepName?: string;\n}\n\nexport interface ActionContextOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // ctx.files for actions. Mirrors the option triggers already accept; when\n // omitted the member keeps throwing, so a piece that needs files fails\n // loudly rather than silently dropping them.\n files?: ApFilesService;\n connections?: ConnectionsProvider;\n // ctx.output.update, the piece's own progress report. Omitted, the member\n // throws, so a piece that depends on it fails by name rather than silently.\n output?: { update(output: unknown): Promise<void> };\n // ctx.reactor. Served only to a piece the host loaded from an installed\n // reactor package; for every other piece the member throws by name.\n reactor?: ReactorService;\n executionType?: `${ExecutionType}`;\n identity?: ActionContextIdentity;\n onTouch?: (member: string) => void;\n}\n\n// Shape of the context we hand to `action.run()`: the framework's ActionContext\n// member for member. Those beyond the implemented tier throw, named.\nexport interface BuiltApActionContext {\n executionType: `${ExecutionType}`;\n auth: unknown;\n propsValue: Record<string, unknown>;\n store: Store;\n connections: ConnectionsManager;\n tags: TagsManager;\n server: ServerContext;\n files: FilesService;\n output: OutputContext;\n reactor: ReactorService;\n // Carried by the framework's own test double but absent from its types.\n agent: { tools: unknown[] };\n run: RunContext;\n project: BaseContext<undefined, InputPropertyMap>[\"project\"];\n flows: FlowsContext;\n step: StepContext;\n generateResumeUrl(params: {\n queryParams: Record<string, string>;\n sync?: boolean;\n }): string;\n}\n\nexport interface ActionContextHandle {\n context: BuiltApActionContext;\n // Top-level members the piece read; `UNDOCUMENTED:<name>` marks unknown reads.\n touched: ReadonlySet<string>;\n}\n\nexport function buildActionContext(\n options: ActionContextOptions,\n): ActionContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n\n const base: Record<string, unknown> = {\n executionType: options.executionType ?? \"BEGIN\",\n auth: options.auth,\n propsValue: options.propsValue,\n store: {\n put: (key: string, value: unknown, scope?: unknown) =>\n store.put(key, value, normalizeStoreScope(scope)),\n get: (key: string, scope?: unknown) =>\n store.get(key, normalizeStoreScope(scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(key, normalizeStoreScope(scope)),\n },\n connections: options.connections ?? throwingStub(\"connections\"),\n tags: throwingStub(\"tags\"),\n server: throwingStub(\"server\"),\n files: options.files ?? throwingStub(\"files\"),\n output: options.output ?? throwingStub(\"output\"),\n reactor: options.reactor ?? throwingStub(\"reactor\"),\n agent: throwingStub(\"agent\"),\n run: {\n id: identity.runId ?? \"run\",\n stop: throwingStub(\"run.stop\"),\n pause: throwingStub(\"run.pause\"),\n respond: throwingStub(\"run.respond\"),\n createWaitpoint: throwingStub(\"run.createWaitpoint\"),\n waitForWaitpoint: throwingStub(\"run.waitForWaitpoint\"),\n },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n flows: {\n list: throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"step\" },\n generateResumeUrl: throwingStub(\"generateResumeUrl\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return { context: context as unknown as BuiltApActionContext, touched };\n}\n","// One file-size ceiling for both directions. Inbound hydration (a FILE prop\n// that arrives as a URL, a data URI or an attachment ref) and outbound\n// ctx.files.write share it, because a piece that can emit a file the next step\n// cannot ingest is worse than a piece that refuses both.\nexport const DEFAULT_MAX_FILE_BYTES = 8 * 1024 * 1024;\n\n// What the environment asks for, or undefined when it asks for nothing usable.\n// Read per call: a host may set it after this module is loaded.\nexport function configuredMaxFileBytes(): number | undefined {\n const raw = process.env.PH_WORKFLOWS_PIECE_MAX_FILE_BYTES;\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : undefined;\n}\n\n// The worker child is forked without an environment, so its limit arrives on\n// the wire instead. Requests are serialized per worker: one value at a time.\nlet fromWire: number | undefined;\n\nexport function setMaxFileBytes(limit: number | undefined): void {\n fromWire = limit;\n}\n\nexport function maxFileBytes(): number {\n return fromWire ?? configuredMaxFileBytes() ?? DEFAULT_MAX_FILE_BYTES;\n}\n\nexport class FileTooLargeError extends Error {\n readonly size: number;\n readonly limit: number;\n\n constructor(size: number, limit: number = maxFileBytes()) {\n super(\n `File of ${size} bytes exceeds the ${limit} byte limit ` +\n `(raise PH_WORKFLOWS_PIECE_MAX_FILE_BYTES to allow more)`,\n );\n this.name = \"FileTooLargeError\";\n this.size = size;\n this.limit = limit;\n }\n}\n\nexport function assertWithinLimit(size: number): void {\n const limit = maxFileBytes();\n if (size > limit) throw new FileTooLargeError(size, limit);\n}\n","// Two FilesService implementations plus the staged-file contract that carries\n// bytes back to the host.\n//\n// `ctx.files.write()` is called *during* action.run(), inside the forked\n// worker, and the worker protocol has no worker-to-host request channel. So\n// this follows the pattern storeState already establishes — push in, return\n// whole — using the one thing a fork shares with its parent: the filesystem.\n// The worker writes bytes to a staging directory and returns a provisional\n// `apfile://<token>`; the host ingests each staged file after the step returns\n// and rewrites the tokens in the output before journalling it.\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n assertWithinLimit,\n FileTooLargeError,\n maxFileBytes,\n} from \"./limits.js\";\n\nexport { FileTooLargeError, maxFileBytes };\n\nexport const APFILE_SCHEME = \"apfile://\";\n\n// One file the piece wrote, as it crosses back on ResultResponse.files.\nexport interface StagedFile {\n // The provisional ref handed to the piece; the host rewrites it in place.\n token: string;\n path: string;\n fileName: string;\n size: number;\n contentType?: string;\n}\n\n// The framework's FilesService for both actions and triggers, narrowed to a\n// Buffer (the staging path cannot stream) with fileName optional.\nexport interface ApFilesService {\n write(file: { fileName?: string; data: Buffer }): Promise<string>;\n}\n\n// Default for both actions and triggers when the host injects nothing: inline\n// the bytes as a data URI so the payload stays self-contained. Bounded by the\n// shared cap, since a data URI lands in the run journal.\nexport class DataUriFilesService implements ApFilesService {\n write(file: { fileName?: string; data: Buffer }): Promise<string> {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n if (data.byteLength > maxFileBytes()) {\n return Promise.reject(new FileTooLargeError(data.byteLength));\n }\n return Promise.resolve(\n `data:application/octet-stream;base64,${data.toString(\"base64\")}`,\n );\n }\n}\n\nconst EXTENSION_TYPES: Record<string, string> = {\n pdf: \"application/pdf\",\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n tif: \"image/tiff\",\n tiff: \"image/tiff\",\n txt: \"text/plain\",\n json: \"application/json\",\n csv: \"text/csv\",\n};\n\nfunction contentTypeFor(fileName: string): string | undefined {\n const extension = fileName.split(\".\").pop()?.toLowerCase();\n return extension ? EXTENSION_TYPES[extension] : undefined;\n}\n\n// Worker-side service: writes into `<stagingDir>/<uuid>` and remembers what it\n// wrote so the worker can report it on the response.\nexport class StagedFilesService implements ApFilesService {\n private readonly files: StagedFile[] = [];\n\n constructor(private readonly stagingDir: string) {}\n\n staged(): StagedFile[] {\n return [...this.files];\n }\n\n async write(file: { fileName?: string; data: Buffer }): Promise<string> {\n const data = Buffer.isBuffer(file.data)\n ? file.data\n : Buffer.from(file.data);\n // Checked before the write: a piece must not be able to fill the disk by\n // handing over a file the host would refuse anyway.\n assertWithinLimit(data.byteLength);\n const token = randomUUID();\n const fileName =\n file.fileName && file.fileName !== \"\" ? file.fileName : token;\n const target = path.join(this.stagingDir, token);\n await mkdir(this.stagingDir, { recursive: true });\n await writeFile(target, data);\n this.files.push({\n token: `${APFILE_SCHEME}${token}`,\n path: target,\n fileName,\n size: data.byteLength,\n contentType: contentTypeFor(fileName),\n });\n return `${APFILE_SCHEME}${token}`;\n }\n}\n\n// Replaces every provisional token in a step output with the real ref the host\n// got back from its attachment store. Walks the whole value: a piece may nest\n// the ref anywhere, and a plain string replace over the serialized JSON would\n// corrupt any base64 that happens to contain the token.\nexport function rewriteFileRefs(\n value: unknown,\n refs: Map<string, string>,\n): unknown {\n if (refs.size === 0) return value;\n if (typeof value === \"string\") return refs.get(value) ?? value;\n if (Array.isArray(value)) {\n return value.map((entry) => rewriteFileRefs(entry, refs));\n }\n if (typeof value === \"object\" && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n out[key] = rewriteFileRefs(entry, refs);\n }\n return out;\n }\n return value;\n}\n","// Our TriggerHookContext → theirs (doc 06 §2.8): one builder covering the\n// strategy variants; identity/payload as data, capabilities injected or stubbed.\nimport { Cron } from \"croner\";\nimport { DEDUPE_KEY_PROPERTY, type ApTrigger } from \"../types.js\";\nimport {\n InMemoryKeyValueStore,\n type ActionContextIdentity,\n type KeyValueStore,\n} from \"./action.js\";\nimport type { ConnectionsProvider, FlowsProvider } from \"./props.js\";\nimport { normalizeStoreScope, type StoreScopeName } from \"./store-scope.js\";\nimport { throwingStub, withTouchTracking } from \"./stubs.js\";\nimport type { ApFilesService } from \"./files.js\";\nimport type {\n TriggerStrategy,\n InputPropertyMap,\n ServerContext,\n SetScheduleRequest,\n TestOrRunHookContext,\n} from \"@powerhousedao/pieces-framework\";\n\n// Both branches of the framework's SetScheduleRequest, as the piece asked.\nexport type RecordedSchedule = SetScheduleRequest;\n\ntype HookContextFor<S extends TriggerStrategy> = TestOrRunHookContext<\n undefined,\n InputPropertyMap,\n S\n>;\n\nexport type RecordedListener = Parameters<\n HookContextFor<TriggerStrategy.APP_WEBHOOK>[\"app\"][\"createListeners\"]\n>[0];\n\n// The floor for an interval schedule; a cron is validated the way upstream's\n// engine does, by handing the expression to a parser. Upstream sets this at a\n// minute, a fair default for a hosted multi-tenant scheduler and too coarse\n// here, where a polling trigger is the reactor's own loop against a service it\n// owns. See MIN_SCHEDULE_INTERVAL_MS in reactor/schedule.ts, the floor the\n// supervisor actually clamps to.\nexport const MIN_SCHEDULE_INTERVAL_MS = 1_000;\n\nexport class InvalidCronExpressionError extends Error {\n constructor(cronExpression: string) {\n super(`Invalid cron expression \"${cronExpression}\"`);\n this.name = \"InvalidCronExpressionError\";\n }\n}\n\nexport class InvalidScheduleIntervalError extends Error {\n constructor(intervalMs: unknown) {\n super(\n `Invalid schedule interval ${String(intervalMs)}: expected a whole number of milliseconds, at least ${MIN_SCHEDULE_INTERVAL_MS}`,\n );\n this.name = \"InvalidScheduleIntervalError\";\n }\n}\n\n// setSchedule's own validation, as the engine's trigger helper performs it: an\n// interval is a whole number at or above the floor, a cron has to parse.\nexport function validateSchedule(request: RecordedSchedule): RecordedSchedule {\n if (\"intervalMs\" in request) {\n const { intervalMs } = request;\n if (\n !Number.isInteger(intervalMs) ||\n intervalMs < MIN_SCHEDULE_INTERVAL_MS\n ) {\n throw new InvalidScheduleIntervalError(intervalMs);\n }\n return { intervalMs };\n }\n const timezone = request.timezone ?? \"UTC\";\n let parsed: Cron;\n try {\n parsed = new Cron(request.cronExpression, { timezone, legacyMode: false });\n } catch {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n if (!parsed.nextRun()) {\n throw new InvalidCronExpressionError(request.cronExpression);\n }\n return { cronExpression: request.cronExpression, timezone };\n}\n\nexport interface TriggerContextOptions {\n propsValue: Record<string, unknown>;\n auth?: unknown;\n store?: KeyValueStore;\n // \"test\" for test hooks so they never touch the live cursor; \"\" otherwise.\n // Ignored when hostPartitionedStore is set — the host separates them there.\n storePrefix?: string;\n // The store partitions on (scope, key) itself, so the key reaches it\n // verbatim instead of carrying the scope as a name prefix. See scopedKey.\n hostPartitionedStore?: boolean;\n identity?: ActionContextIdentity;\n // onEnable: an unchanged trigger re-enabling; pollingHelper keeps its cursor.\n isRepublish?: boolean;\n // WEBHOOK / APP_WEBHOOK: the incoming request; also handed to test runs.\n payload?: unknown;\n webhookUrl?: string;\n flows?: FlowsProvider;\n connections?: ConnectionsProvider;\n server?: ServerContext;\n // run/test hooks only per the AP contract; omitted members throw, named.\n files?: ApFilesService;\n onTouch?: (member: string) => void;\n}\n\n// One shape for every strategy: the framework splits TriggerHookContext by\n// TriggerStrategy, but a bundle's declared strategy is not known at build time.\nexport type BuiltApTriggerContext = HookContextFor<TriggerStrategy.POLLING> &\n HookContextFor<TriggerStrategy.WEBHOOK> &\n HookContextFor<TriggerStrategy.APP_WEBHOOK>;\n\nexport interface TriggerContextHandle {\n context: BuiltApTriggerContext;\n touched: ReadonlySet<string>;\n // setSchedule / app.createListeners calls, for the supervisor to arm.\n schedules: RecordedSchedule[];\n listeners: RecordedListener[];\n}\n\nexport function buildTriggerContext(\n options: TriggerContextOptions,\n): TriggerContextHandle {\n const { identity = {} } = options;\n const store = options.store ?? new InMemoryKeyValueStore();\n const touched = new Set<string>();\n const schedules: RecordedSchedule[] = [];\n const listeners: RecordedListener[] = [];\n\n // AP's engine store layout, for a store that is one flat map: FLOW scope\n // (the default) nests under the flow id; PROJECT scope uses the bare key.\n\n // Matching the enum's \"COLLECTION\" value alone missed a piece that passes\n // the name instead, which then silently got flow scope.\n const prefix = options.storePrefix ?? \"\";\n const flowId = identity.flowId ?? \"flow\";\n const scopedKey = (key: string, scope?: unknown) =>\n normalizeStoreScope(scope) === \"PROJECT\"\n ? `${prefix}${key}`\n : `${prefix}flow_${flowId}/${key}`;\n\n // A host-partitioned store owns the layout, so the scope travels beside the\n // key rather than inside it, exactly as buildActionContext passes it.\n\n // No \"test\" prefix on that path: a prefix aliases, so a live key named\n // \"testMode\" is a sample's \"Mode\" once both share one flat partition.\n\n // Separating a sample is then the host's job, by partition — which a prefix\n // could not do anyway, since nothing can enumerate a sample's keys to drop.\n const address = (\n key: string,\n scope?: unknown,\n ): [string, StoreScopeName | undefined] =>\n options.hostPartitionedStore\n ? [key, normalizeStoreScope(scope)]\n : [scopedKey(key, scope), undefined];\n\n const base: Record<string, unknown> = {\n auth: options.auth,\n propsValue: options.propsValue,\n isRepublish: options.isRepublish ?? false,\n store: {\n put: (key: string, value: unknown, scope?: unknown) => {\n const [at, partition] = address(key, scope);\n return store.put(at, value, partition);\n },\n get: (key: string, scope?: unknown) => store.get(...address(key, scope)),\n delete: (key: string, scope?: unknown) =>\n store.delete(...address(key, scope)),\n },\n flows: {\n list:\n options.flows?.list.bind(options.flows) ?? throwingStub(\"flows.list\"),\n current: {\n id: identity.flowId ?? \"flow\",\n version: { id: identity.flowVersionId ?? \"flow-version\" },\n },\n },\n step: { name: identity.stepName ?? \"trigger\" },\n project: {\n id: identity.projectId ?? \"project\",\n externalId: () => Promise.resolve(identity.projectId ?? \"project\"),\n },\n connections: options.connections ?? {\n get: throwingStub(\"connections.get\"),\n },\n server: options.server ?? throwingStub(\"server\"),\n webhookUrl: options.webhookUrl ?? \"http://localhost:0/webhook\",\n payload: options.payload,\n setSchedule: (schedule: RecordedSchedule) => {\n schedules.push(validateSchedule(schedule));\n },\n app: {\n createListeners: (listener: RecordedListener) => {\n listeners.push(listener);\n },\n },\n files: options.files ?? throwingStub(\"files\"),\n };\n\n const context = withTouchTracking(base, touched, options.onTouch);\n return {\n context: context as unknown as BuiltApTriggerContext,\n touched,\n schedules,\n listeners,\n };\n}\n\n// Dedup key per doc 08 §4.4: the payload's own _dedupe_key wins; the caller\n// falls back to its own synthesis when absent.\nexport function extractDedupeKey(payload: unknown): string | undefined {\n if (typeof payload !== \"object\" || payload === null) return undefined;\n const value = (payload as Record<string, unknown>)[DEDUPE_KEY_PROPERTY];\n return typeof value === \"string\" ? value : undefined;\n}\n\nexport class TriggerHookNotImplementedError extends Error {\n constructor(triggerName: string, hook: string) {\n super(`Trigger \"${triggerName}\" does not implement ${hook}()`);\n this.name = \"TriggerHookNotImplementedError\";\n }\n}\n\nexport type TriggerLifecycleHook =\n | \"onEnable\"\n | \"onDisable\"\n | \"run\"\n | \"test\"\n | \"onHandshake\"\n | \"onRenew\";\n\n// Invokes one lifecycle hook with the built context; result is returned untouched.\nexport async function runTriggerHook(\n trigger: ApTrigger,\n hook: TriggerLifecycleHook,\n handle: TriggerContextHandle,\n): Promise<unknown> {\n const fn = trigger[hook];\n if (typeof fn !== \"function\") {\n throw new TriggerHookNotImplementedError(trigger.name ?? \"unknown\", hook);\n }\n return await fn.call(trigger, handle.context);\n}\n","// Network egress policy, enforced inside the worker child. Pieces bundle their\n// own HTTP clients, so hooking one of them — or `fetch` — is bypassable.\n\n// Every TCP connection in Node ends at `net.Socket.prototype.connect`, whatever\n// the client, so that is the choke point installed here.\n\n// This hardens SSRF inside a cooperative process; it is not a boundary against\n// hostile code — see installEgressGuard.\nimport dgram from \"node:dgram\";\nimport dns from \"node:dns\";\nimport net, { isIP } from \"node:net\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { ssrfIpClassifier } from \"@powerhousedao/pieces-framework/host\";\nimport type { EgressPolicy } from \"./protocol.js\";\n\nexport const EGRESS_DENIED_CODE = \"EGRESS_DENIED\";\n\n// What a host applies when it expresses no preference: every public host is\n// reachable, private space and the metadata endpoint are not.\nexport const DEFAULT_EGRESS_POLICY: EgressPolicy = {};\n\n// Raised at connect time and delivered to the piece the way Node delivers a\n// failed DNS lookup — an error on the socket — so any client surfaces it.\nexport class EgressDeniedError extends Error {\n readonly code = EGRESS_DENIED_CODE;\n readonly host: string;\n readonly port: number | undefined;\n readonly address: string | undefined;\n\n constructor(\n reason: string,\n where: { host: string; port?: number; address?: string },\n ) {\n super(`Egress denied: ${reason}`);\n this.name = \"EgressDeniedError\";\n this.host = where.host;\n this.port = where.port;\n this.address = where.address;\n }\n}\n\n// The SSRF surface (loopback, RFC1918, link-local incl. the metadata endpoint,\n// multicast, and the IPv6 equivalents) is the framework's classifier table.\n\n// ipaddr.js reads a deprecated IPv4-compatible address (::a.b.c.d) as unicast,\n// so ::169.254.169.254 would walk past it; the whole block is refused here.\nconst IPV4_COMPATIBLE = new net.BlockList();\nIPV4_COMPATIBLE.addSubnet(\"::\", 96, \"ipv6\");\n\nfunction familyOf(address: string): \"ipv4\" | \"ipv6\" {\n return isIP(address) === 6 ? \"ipv6\" : \"ipv4\";\n}\n\n// The address without its zone, or undefined when it is not one at all.\nexport function parseAddress(value: string): string | undefined {\n const bare = value.split(\"%\")[0];\n return isIP(bare) === 0 ? undefined : bare;\n}\n\n// Compiled eagerly so a malformed entry fails the request rather than\n// degrading it to no enforcement.\nfunction addAllowedAddress(list: net.BlockList, spec: string): void {\n const slash = spec.indexOf(\"/\");\n const mask = slash === -1 ? \"\" : spec.slice(slash + 1);\n const address = parseAddress(slash === -1 ? spec : spec.slice(0, slash));\n if (!address) {\n throw new Error(`Egress policy entry \"${spec}\" is not an IP address`);\n }\n const family = familyOf(address);\n const width = family === \"ipv6\" ? 128 : 32;\n const prefix = mask === \"\" ? width : Number(mask);\n if (!Number.isInteger(prefix) || prefix < 1 || prefix > width) {\n throw new Error(`Egress policy entry \"${spec}\" has an invalid prefix`);\n }\n list.addSubnet(address, prefix, family);\n}\n\ntype NativeLookup = (\n hostname: string,\n options: dns.LookupOneOptions,\n callback: (error: Error | null, address: unknown, family?: number) => void,\n) => void;\n\n// getaddrinfo, taken before anything is patched: the guard resolves through\n// this so its own lookups never meet the refusal it installs below.\nconst nativeLookup = originalOf<NativeLookup>(dns, \"lookup\");\n\n// c-ares, which owns its sockets and never passes through dgram or connect.\n\n// A query is a channel out on its own — the data rides in the name — so the\n// answer is irrelevant and the whole surface is refused under a policy.\nconst RESOLVER_METHODS = [\n \"resolve\",\n \"resolve4\",\n \"resolve6\",\n \"resolveAny\",\n \"resolveCaa\",\n \"resolveCname\",\n \"resolveMx\",\n \"resolveNaptr\",\n \"resolveNs\",\n \"resolvePtr\",\n \"resolveSoa\",\n \"resolveSrv\",\n \"resolveTxt\",\n \"reverse\",\n];\n\nexport function isPrivateAddress(value: string): boolean {\n const address = parseAddress(value);\n // An address we cannot classify counts as private: fail closed.\n if (!address) return true;\n if (IPV4_COMPATIBLE.check(address, familyOf(address))) return true;\n return ssrfIpClassifier.isBlockedIp({ ip: address, allowList: [] });\n}\n\ninterface CompiledPolicy {\n hosts: string[] | undefined;\n addresses: net.BlockList | undefined;\n ports: number[] | undefined;\n allowPrivate: boolean;\n}\n\nfunction compile(policy: EgressPolicy): CompiledPolicy {\n const hosts = policy.allowHosts?.map((host) => host.trim().toLowerCase());\n const ports = policy.allowPorts?.map((port) => {\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new Error(`Egress policy port ${String(port)} is out of range`);\n }\n return port;\n });\n const specs = policy.allowAddresses ?? [];\n const addresses = new net.BlockList();\n for (const spec of specs) addAllowedAddress(addresses, spec);\n return {\n hosts: hosts && hosts.length > 0 ? hosts : undefined,\n addresses: specs.length > 0 ? addresses : undefined,\n ports: ports && ports.length > 0 ? ports : undefined,\n allowPrivate: policy.allowPrivateAddresses === true,\n };\n}\n\nfunction hostAllowed(policy: CompiledPolicy, host: string): boolean {\n if (!policy.hosts) return true;\n const name = host.toLowerCase();\n return policy.hosts.some((entry) =>\n entry.startsWith(\"*.\")\n ? name.length > entry.length - 1 && name.endsWith(entry.slice(1))\n : entry === name,\n );\n}\n\nfunction addressAllowed(policy: CompiledPolicy, address: string): boolean {\n const ip = parseAddress(address);\n if (!ip) return false;\n if (policy.addresses?.check(ip, familyOf(ip))) return true;\n return policy.allowPrivate || !isPrivateAddress(ip);\n}\n\n// The policy of the request in flight, and the one the work started under: both\n// apply, so a pooled client's callback chain cannot borrow a laxer context.\n\n// A piece's leftover timer keeps the policy it was created with rather than\n// whatever the next request brings.\nlet inFlight: CompiledPolicy | undefined;\nconst started = new AsyncLocalStorage<CompiledPolicy | undefined>();\n\nfunction policiesInForce(): CompiledPolicy[] {\n const inherited = started.getStore();\n const policies: CompiledPolicy[] = [];\n if (inFlight) policies.push(inFlight);\n if (inherited && inherited !== inFlight) policies.push(inherited);\n return policies;\n}\n\n// Runs one request under its policy. Compiling first means a malformed policy\n// fails the request rather than degrading it to no enforcement.\nexport async function runWithEgressPolicy<T>(\n policy: EgressPolicy | undefined,\n work: () => Promise<T>,\n): Promise<T> {\n const compiled = policy ? compile(policy) : undefined;\n installEgressGuard();\n inFlight = compiled;\n try {\n return await started.run(compiled, work);\n } finally {\n // The request is over; what it left running keeps the policy it inherited,\n // so it can never become less restricted than it started.\n if (inFlight === compiled) inFlight = undefined;\n }\n}\n\ninterface ConnectOptions {\n path?: string;\n port?: number | string;\n host?: string;\n lookup?: unknown;\n [key: string]: unknown;\n}\n\n// Node's own connect-argument shapes: (options) | (port[, host]) | (path), plus\n// the pre-normalized [options, callback] array net.createConnection hands over.\nfunction normalizeConnectArgs(args: unknown[]): {\n options: ConnectOptions;\n callback: unknown;\n} {\n if (Array.isArray(args[0])) {\n const [options, callback] = args[0] as [ConnectOptions, unknown];\n return { options: { ...options }, callback };\n }\n const first = args[0];\n let options: ConnectOptions = {};\n if (typeof first === \"object\" && first !== null) {\n options = { ...(first as ConnectOptions) };\n } else if (typeof first === \"string\" && Number.isNaN(Number(first))) {\n options.path = first;\n } else {\n options.port = first as number;\n if (typeof args[1] === \"string\") options.host = args[1];\n }\n const last = args[args.length - 1];\n return { options, callback: typeof last === \"function\" ? last : undefined };\n}\n\ntype LookupResult = { address: string; family: number }[];\n\ntype LookupCallback = (\n error: Error | null,\n address?: string | LookupResult,\n family?: number,\n) => void;\n\n// Classifies the address the socket is about to use, not the name the piece\n// asked for: a name check alone loses to DNS rebinding.\nfunction guardedLookup(\n policies: CompiledPolicy[],\n host: string,\n port: number | undefined,\n): (hostname: string, options: unknown, callback: LookupCallback) => void {\n return (hostname, options, callback) => {\n const asked = options as { all?: boolean };\n nativeLookup(\n hostname,\n options as dns.LookupOneOptions,\n (error: Error | null, result: unknown, family?: number) => {\n if (error) {\n callback(error);\n return;\n }\n try {\n const entries: LookupResult = asked.all\n ? (result as LookupResult)\n : [{ address: result as string, family: family ?? 0 }];\n const permitted = entries.filter((entry) =>\n policies.every((policy) => addressAllowed(policy, entry.address)),\n );\n if (permitted.length === 0) {\n const seen = entries.map((entry) => entry.address).join(\", \");\n callback(\n new EgressDeniedError(\n `host \"${host}\" resolves to ${seen || \"nothing\"}, which the policy does not permit`,\n { host, port, address: entries[0]?.address },\n ),\n );\n return;\n }\n if (asked.all) callback(null, permitted);\n else callback(null, permitted[0].address, permitted[0].family);\n } catch (failure) {\n // A defect in the guard denies the connection, never opens it.\n callback(\n failure instanceof Error ? failure : new Error(String(failure)),\n );\n }\n },\n );\n };\n}\n\nfunction denyReason(\n policies: CompiledPolicy[],\n options: ConnectOptions,\n): EgressDeniedError | undefined {\n if (typeof options.path === \"string\") {\n return new EgressDeniedError(\n `connections to local socket \"${options.path}\" are not permitted`,\n { host: options.path },\n );\n }\n const host = typeof options.host === \"string\" ? options.host : \"\";\n const port = options.port === undefined ? undefined : Number(options.port);\n for (const policy of policies) {\n if (policy.ports && (port === undefined || !policy.ports.includes(port))) {\n return new EgressDeniedError(\n `port ${String(port)} on host \"${host}\" is not permitted`,\n { host, port },\n );\n }\n if (!hostAllowed(policy, host)) {\n return new EgressDeniedError(`host \"${host}\" is not on the allowlist`, {\n host,\n port,\n });\n }\n if (isIP(host) && !addressAllowed(policy, host)) {\n return new EgressDeniedError(`address ${host} is not permitted`, {\n host,\n port,\n address: host,\n });\n }\n }\n return undefined;\n}\n\n// Reports a denial the way Node reports an asynchronous socket failure, so a\n// piece catches it from its client rather than from a synchronous throw.\nfunction failLater(\n emitter: { emit: (event: string, error: Error) => boolean },\n error: EgressDeniedError,\n callback: unknown,\n): void {\n process.nextTick(() => {\n if (typeof callback === \"function\") (callback as (e: Error) => void)(error);\n else emitter.emit(\"error\", error);\n });\n}\n\n// Takes a method off its descriptor rather than as a method reference: what is\n// wanted is the original implementation, re-applied with an explicit `this`.\nfunction originalOf<T>(target: object, name: string): T {\n return Object.getOwnPropertyDescriptor(target, name)?.value as T;\n}\n\nfunction resolverDenial(method: string, args: unknown[]): EgressDeniedError {\n const host = typeof args[0] === \"string\" ? args[0] : \"\";\n return new EgressDeniedError(\n `DNS ${method}(\"${host}\") is not permitted; use a hostname in a request instead`,\n { host },\n );\n}\n\n// Refuses every c-ares entry point on one object, in the shape its callers\n// expect: a rejected promise here, a callback error there.\nfunction refuseResolvers(target: object, promised: boolean): void {\n for (const method of RESOLVER_METHODS) {\n const original = originalOf<(this: unknown, ...args: unknown[]) => unknown>(\n target,\n method,\n );\n if (typeof original !== \"function\") continue;\n function refused(this: unknown, ...args: unknown[]): unknown {\n if (policiesInForce().length === 0) return original.apply(this, args);\n const denied = resolverDenial(method, args);\n if (promised) return Promise.reject(denied);\n const callback = args[args.length - 1];\n // No callback is a programming error Node would throw on anyway.\n if (typeof callback !== \"function\") throw denied;\n process.nextTick(() => (callback as (error: Error) => void)(denied));\n return undefined;\n }\n seal(target, method, refused);\n }\n}\n\n// Sealed so a piece holding the pristine implementation cannot put it back, and\n// so a later assignment cannot quietly unhook the guard.\nfunction seal(target: object, name: string, value: unknown): void {\n Object.defineProperty(target, name, {\n value,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n}\n\nlet installed = false;\n\n// Installed when the worker child starts, before any piece code can run, and a\n// no-op while no policy is in force.\n\n// Not a boundary against hostile code: a child process or a worker thread gets\n// its own copy of these modules. Isolation is a network namespace, not this.\nexport function installEgressGuard(): void {\n if (installed) return;\n installed = true;\n\n const connect = originalOf<\n (this: net.Socket, ...args: unknown[]) => net.Socket\n >(net.Socket.prototype, \"connect\");\n\n function patchedConnect(this: net.Socket, ...args: unknown[]): net.Socket {\n const policies = policiesInForce();\n if (policies.length === 0) return connect.apply(this, args);\n const { options, callback } = normalizeConnectArgs(args);\n // Node defaults a missing host to localhost; write it back so the checks\n // and the guarded lookup below both see what will be dialled.\n if (typeof options.path !== \"string\" && !options.host) {\n options.host = \"localhost\";\n }\n const denied = denyReason(policies, options);\n if (denied) {\n process.nextTick(() => this.destroy(denied));\n return this;\n }\n if (typeof options.host === \"string\" && !isIP(options.host)) {\n options.lookup = guardedLookup(\n policies,\n options.host,\n options.port === undefined ? undefined : Number(options.port),\n );\n }\n return connect.call(this, options, callback);\n }\n seal(net.Socket.prototype, \"connect\", patchedConnect);\n\n // The dgram surface carries no destination a policy can usefully allow — a\n // piece's work is HTTP — so it is refused whole, as is c-ares further down.\n const send = originalOf<(this: dgram.Socket, ...args: unknown[]) => void>(\n dgram.Socket.prototype,\n \"send\",\n );\n function patchedSend(this: dgram.Socket, ...args: unknown[]): void {\n if (policiesInForce().length === 0) {\n send.apply(this, args);\n return;\n }\n const host = args.find(\n (arg, index) => index > 0 && typeof arg === \"string\",\n ) as string | undefined;\n const last = args[args.length - 1];\n failLater(\n this,\n new EgressDeniedError(\n `UDP to \"${host ?? \"the requested address\"}\" is not permitted`,\n { host: host ?? \"\" },\n ),\n typeof last === \"function\" ? last : undefined,\n );\n }\n seal(dgram.Socket.prototype, \"send\", patchedSend);\n\n // Inbound is refused for the same reason: a delivery reaches a workflow\n // through the host's webhook endpoint, never a port the piece opened.\n const bind = originalOf<\n (this: dgram.Socket, ...args: unknown[]) => dgram.Socket\n >(dgram.Socket.prototype, \"bind\");\n function patchedBind(this: dgram.Socket, ...args: unknown[]): dgram.Socket {\n if (policiesInForce().length === 0) return bind.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"binding a UDP socket is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(dgram.Socket.prototype, \"bind\", patchedBind);\n\n const listen = originalOf<\n (this: net.Server, ...args: unknown[]) => net.Server\n >(net.Server.prototype, \"listen\");\n function patchedListen(this: net.Server, ...args: unknown[]): net.Server {\n if (policiesInForce().length === 0) return listen.apply(this, args);\n failLater(\n this,\n new EgressDeniedError(\"listening for connections is not permitted\", {\n host: \"\",\n }),\n undefined,\n );\n return this;\n }\n seal(net.Server.prototype, \"listen\", patchedListen);\n\n // The four objects a piece can reach c-ares through; dns.lookup is\n // getaddrinfo and stays open, guarded per connect instead.\n refuseResolvers(dns, false);\n refuseResolvers(dns.Resolver.prototype, false);\n refuseResolvers(dns.promises, true);\n refuseResolvers(dns.promises.Resolver.prototype, true);\n}\n\n// True for a denial raised in the child, including one a piece's client\n// re-wrapped: axios copies `code`, undici keeps the original as `cause`.\nexport function isEgressDenied(error: unknown): boolean {\n const seen = new Set<unknown>();\n let candidate: unknown = error;\n // Wrappers nest, and some of them produce a cycle; the walk is bounded by\n // the seen set and by a depth no honest chain reaches.\n for (let depth = 0; depth < 16; depth++) {\n if (candidate instanceof EgressDeniedError) return true;\n if (typeof candidate !== \"object\" || candidate === null) return false;\n if (seen.has(candidate)) return false;\n seen.add(candidate);\n const fields = candidate as {\n name?: unknown;\n code?: unknown;\n message?: unknown;\n cause?: unknown;\n properties?: { code?: unknown };\n serialized?: { name?: unknown; properties?: { code?: unknown } };\n };\n const codes = [\n fields.code,\n fields.properties?.code,\n fields.serialized?.properties?.code,\n ];\n if (codes.includes(EGRESS_DENIED_CODE)) return true;\n if (fields.name === \"EgressDeniedError\") return true;\n if (fields.serialized?.name === \"EgressDeniedError\") return true;\n if (\n typeof fields.message === \"string\" &&\n fields.message.includes(\"Egress denied:\")\n ) {\n return true;\n }\n candidate = fields.cause;\n }\n return false;\n}\n","// Credential redaction for anything that gets journaled or shown to a user.\n// Two independent passes, because each catches what the other misses.\n\n// Key-based catches a credential the run never knew about: a piece's own\n// hardcoded key, a token it fetched mid-step.\n\n// Value-based catches a secret the run did resolve, wherever a piece spliced\n// it — into a message, a URL, a header it composed itself.\n\nexport const REDACTED_PREFIX = \"[redacted:\";\nexport const SECRET_MARKER = \"[redacted:secret]\";\nexport const CIRCULAR_MARKER = \"[circular]\";\nexport const TRUNCATED_MARKER = \"[truncated]\";\n\n// Bounds for the hostile-error path only. Ordinary step output is data a user\n// asked for, so it is redacted whole rather than truncated.\nconst ERROR_MAX_DEPTH = 8;\nconst ERROR_MAX_NODES = 1000;\n\n// Deep enough never to be reached by real data, shallow enough that the\n// recursive walk cannot overflow the stack on a self-nesting object.\nconst STACK_GUARD_DEPTH = 200;\n\n// Exact names, matched after stripping separators and case: \"X-Api-Key\",\n// \"x_api_key\" and \"apiKey\" are one name.\nconst SENSITIVE_NAMES = new Set([\n \"auth\",\n \"authorization\",\n \"proxyauthorization\",\n \"wwwauthenticate\",\n \"authtoken\",\n \"xauthtoken\",\n \"apikey\",\n \"xapikey\",\n \"apisecret\",\n \"bearer\",\n \"cookie\",\n \"setcookie\",\n \"credential\",\n \"credentials\",\n \"password\",\n \"passwd\",\n \"passphrase\",\n \"pwd\",\n \"privatekey\",\n \"secret\",\n \"secrettext\",\n \"sessionid\",\n \"signature\",\n \"token\",\n]);\n\n// A name ending in one of these is sensitive whatever prefixes it, which is\n// what catches githubToken, client_secret and the rest of the long tail.\nconst SENSITIVE_SUFFIXES = [\n \"apikey\",\n \"credentials\",\n \"password\",\n \"privatekey\",\n \"secret\",\n \"token\",\n];\n\n// Header and field names worth redacting inside a free-form string, where\n// there is no key to walk.\n\n// Deliberately a fixed list: a loose pattern over prose eats more of the\n// message than it saves.\n\n// Signature is the one alternative that carries its own affixes, because a\n// webhook MAC header wraps the word: x-hub-signature-256.\nconst TEXT_FIELD = new RegExp(\n String.raw`\\b(authorization|proxy-authorization|api[-_]?key|x-api-key|access[-_]?token|refresh[-_]?token|client[-_]?secret|set-cookie|cookie|password|secret|token|(?:[a-z0-9]+[-_])*signature(?:[-_][a-z0-9]+)*)\\b([\"']?)(\\s*[:=]\\s*)([\"']?)((?:(?:Bearer|Basic|Token)\\s+)?[^\\s\",;&)}]+)\\4`,\n \"gi\",\n);\n\nconst AUTH_SCHEME = /\\b(Bearer|Basic|Token)\\s+([A-Za-z0-9._~+/=-]{8,})/g;\n\nconst QUERY_PARAM = /([?&])([A-Za-z0-9_.%[\\]-]+)=([^&\\s\"'<>]+)/g;\n\n// The password half of a URL's userinfo, which no header or query pattern\n// reaches: https://user:s3cret@host/api.\nconst URL_USERINFO = /([a-z][a-z0-9+.-]*:\\/\\/)([^/\\s:@]+):([^/\\s@]+)@/gi;\n\nexport function normalizeName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nexport function isSensitiveName(name: string): boolean {\n const normalized = normalizeName(name);\n if (!normalized) return false;\n if (SENSITIVE_NAMES.has(normalized)) return true;\n // Anywhere in the name, because a webhook MAC header carries its algorithm\n // after it: x-hub-signature-256.\n if (normalized.includes(\"signature\")) return true;\n return SENSITIVE_SUFFIXES.some(\n (suffix) =>\n normalized.length > suffix.length && normalized.endsWith(suffix),\n );\n}\n\nfunction marker(name: string): string {\n return `[redacted:${name.toLowerCase()}]`;\n}\n\nfunction shannonEntropy(text: string): number {\n const counts = new Map<string, number>();\n for (const char of text) counts.set(char, (counts.get(char) ?? 0) + 1);\n let entropy = 0;\n for (const count of counts.values()) {\n const p = count / text.length;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// The bar a *guessed* secret must clear before its value is matched anywhere.\n\n// A short or repetitive guess (\"admin\", \"8080\", \"aaaaaaaa\") would hit unrelated\n// text and leave an error nobody can read; the key-based pass still covers it.\nconst MIN_VALUE_LENGTH = 8;\nconst MIN_DISTINCT_CHARS = 5;\nconst MIN_ENTROPY_BITS = 2;\n\n// A value the host hands over is a declaration, not a guess, so \"hunter2\" is\n// redacted. Only a value too short to be a credential is refused.\nconst MIN_DECLARED_LENGTH = 4;\n\nexport function isRedactableValue(value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n if (value.length < MIN_VALUE_LENGTH) return false;\n if (new Set(value).size < MIN_DISTINCT_CHARS) return false;\n return shannonEntropy(value) >= MIN_ENTROPY_BITS;\n}\n\nexport function isDeclaredValue(value: unknown): value is string {\n return typeof value === \"string\" && value.length >= MIN_DECLARED_LENGTH;\n}\n\n// The AppConnectionValue discriminator, and anything shaped like an endpoint.\n\n// Both are configuration rather than credentials, and a URL is usually the\n// most useful thing left in a failed request's error.\nconst STRUCTURAL_NAMES = new Set([\"type\", \"authtype\"]);\nconst URL_LIKE = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\n// Every credential-shaped string leaf of a resolved connection. The fallback\n// for a host resolver that cannot say which of its values are secret.\nexport function collectSecretValues(\n value: unknown,\n into: Set<string> = new Set(),\n depth = 0,\n): Set<string> {\n if (depth > ERROR_MAX_DEPTH) return into;\n if (isRedactableValue(value)) {\n if (!URL_LIKE.test(value)) into.add(value);\n return into;\n }\n if (Array.isArray(value)) {\n for (const entry of value) collectSecretValues(entry, into, depth + 1);\n return into;\n }\n if (typeof value === \"object\" && value !== null) {\n for (const [key, entry] of Object.entries(value)) {\n if (STRUCTURAL_NAMES.has(normalizeName(key))) continue;\n collectSecretValues(entry, into, depth + 1);\n }\n }\n return into;\n}\n\nexport interface RedactOptions {\n // Concrete secret values resolved for this step; each occurrence is replaced.\n values?: Iterable<string>;\n maxDepth?: number;\n maxNodes?: number;\n}\n\n// A host-side handle from a thrown error to the secrets its step ran with, so\n// a catch far from the connection can still redact by value.\nconst thrownSecrets = new WeakMap<object, string[]>();\n\nexport function rememberSecrets<T>(error: T, values: string[]): T {\n if (typeof error === \"object\" && error !== null && values.length > 0) {\n thrownSecrets.set(error, values);\n }\n return error;\n}\n\nexport function secretsFor(error: unknown): string[] {\n if (typeof error !== \"object\" || error === null) return [];\n return thrownSecrets.get(error) ?? [];\n}\n\ninterface Pass {\n values: string[];\n maxDepth: number;\n maxNodes: number;\n nodes: number;\n}\n\n// Longest first, so a secret that contains another is replaced whole rather\n// than leaving its tail behind.\nfunction preparePass(options: RedactOptions | undefined): Pass {\n const values = [...(options?.values ?? [])]\n .filter(isDeclaredValue)\n .sort((a, b) => b.length - a.length);\n return {\n values,\n maxDepth: options?.maxDepth ?? STACK_GUARD_DEPTH,\n maxNodes: options?.maxNodes ?? Number.POSITIVE_INFINITY,\n nodes: 0,\n };\n}\n\nfunction safeDecode(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name;\n }\n}\n\nfunction replaceValues(text: string, values: string[]): string {\n let result = text;\n for (const value of values) {\n if (result.includes(value)) {\n result = result.split(value).join(SECRET_MARKER);\n }\n const encoded = encodeURIComponent(value);\n if (encoded !== value && result.includes(encoded)) {\n result = result.split(encoded).join(SECRET_MARKER);\n }\n }\n return result;\n}\n\nfunction redactText(text: string, pass: Pass): string {\n let result = replaceValues(text, pass.values);\n result = result.replace(\n URL_USERINFO,\n (_match, scheme: string, user: string) =>\n `${scheme}${user}:${marker(\"password\")}@`,\n );\n result = result.replace(QUERY_PARAM, (match, sep: string, name: string) =>\n isSensitiveName(safeDecode(name)) ? `${sep}${name}=${marker(name)}` : match,\n );\n result = result.replace(\n AUTH_SCHEME,\n (_match, scheme: string) => `${scheme} ${marker(scheme)}`,\n );\n\n // Skipping a value that is already a marker keeps this pass from re-matching\n // what the query pass just wrote and swallowing the rest of the string.\n return result.replace(\n TEXT_FIELD,\n (\n match,\n name: string,\n nameQuote: string,\n sep: string,\n quote: string,\n value: string,\n ) =>\n value.startsWith(REDACTED_PREFIX)\n ? match\n : `${name}${nameQuote}${sep}${quote}${marker(name)}${quote}`,\n );\n}\n\nfunction walk(\n value: unknown,\n pass: Pass,\n depth: number,\n seen: Set<object>,\n): unknown {\n if (typeof value === \"string\") return redactText(value, pass);\n if (typeof value !== \"object\" || value === null) return value;\n if (seen.has(value)) return CIRCULAR_MARKER;\n if (depth >= pass.maxDepth) return TRUNCATED_MARKER;\n if (pass.nodes >= pass.maxNodes) return TRUNCATED_MARKER;\n pass.nodes += 1;\n\n // Tracked per path, not globally: the same object appearing twice in a tree\n // is not a cycle, and calling it one would drop data a user needs.\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((entry) => walk(entry, pass, depth + 1, seen));\n }\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n result[key] = isSensitiveName(key)\n ? marker(key)\n : walk(entry, pass, depth + 1, seen);\n }\n return result;\n } finally {\n seen.delete(value);\n }\n}\n\n// Redacts credentials from an arbitrary value: sensitive keys by name, known\n// secret values wherever they appear, sensitive URL query parameters.\n\n// Cycles are collapsed; nothing else is dropped, because this also runs over\n// step output a user asked to see.\nexport function redact(value: unknown, options?: RedactOptions): unknown {\n return walk(value, preparePass(options), 0, new Set());\n}\n\n// The same pass for an error object, which is attacker-shaped: depth and node\n// count are capped so a hostile error cannot make redaction expensive.\nexport function redactError(value: unknown, options?: RedactOptions): unknown {\n return redact(value, {\n maxDepth: ERROR_MAX_DEPTH,\n maxNodes: ERROR_MAX_NODES,\n ...options,\n });\n}\n\n// True when a value carries a marker this module wrote. Rerun uses it to\n// refuse a journaled output it cannot faithfully replay.\nexport function containsRedactedMarker(value: unknown, depth = 0): boolean {\n if (typeof value === \"string\") return value.includes(REDACTED_PREFIX);\n if (typeof value !== \"object\" || value === null) return false;\n if (depth >= STACK_GUARD_DEPTH) return false;\n return Object.values(value).some((entry) =>\n containsRedactedMarker(entry, depth + 1),\n );\n}\n\n// The string-only form, for a message that is already flat text.\nexport function redactMessage(text: string, options?: RedactOptions): string {\n return redactText(text, preparePass(options));\n}\n"],"mappings":";;;;;;;;;;;AAgHA,SAAgB,WAAW,OAA0C;AAGnE,SADE,O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as PieceDescriptor, O as loadPieceFromDir, S as localFirstResolver, T as extractDedupeKey, _ as PieceWorker, a as AttachmentPort, b as PackagePiece, f as BlockExecution, g as IPieceWorker, h as PieceWorkerPool, i as ActivepiecesBlockExecutor, k as ensurePieceBundle, l as StaticConnectionResolver, m as WorkflowRunResult, o as CompositeBlockExecutor, r as runWorkflow, s as ReactorPort, t as PieceRegistry, u as InMemorySecretProvider, w as RecordedSchedule, x as PieceResolver, y as LocalPiece } from "./piece-registry-
|
|
1
|
+
import { A as fetchPieceBundle, D as buildDescriptor, E as PieceDescriptor, O as loadPieceFromDir, S as localFirstResolver, T as extractDedupeKey, _ as PieceWorker, a as AttachmentPort, b as PackagePiece, f as BlockExecution, g as IPieceWorker, h as PieceWorkerPool, i as ActivepiecesBlockExecutor, k as ensurePieceBundle, l as StaticConnectionResolver, m as WorkflowRunResult, o as CompositeBlockExecutor, r as runWorkflow, s as ReactorPort, t as PieceRegistry, u as InMemorySecretProvider, w as RecordedSchedule, x as PieceResolver, y as LocalPiece } from "./piece-registry-BH39cD-k.js";
|
|
2
2
|
export { ActivepiecesBlockExecutor, type AttachmentPort, type BlockExecution, CompositeBlockExecutor, type IPieceWorker, InMemorySecretProvider, type LocalPiece, type PackagePiece, type PieceDescriptor, PieceRegistry, type PieceResolver, PieceWorker, PieceWorkerPool, type ReactorPort, type RecordedSchedule, StaticConnectionResolver, type WorkflowRunResult, buildDescriptor, ensurePieceBundle, extractDedupeKey, fetchPieceBundle, loadPieceFromDir, localFirstResolver, runWorkflow };
|
package/dist/testing.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { f as extractDedupeKey } from "./redact-
|
|
2
|
-
import {
|
|
3
|
-
import { i as loadPieceFromDir, t as buildDescriptor } from "./descriptor-
|
|
1
|
+
import { f as extractDedupeKey } from "./redact-ChAU8USo.js";
|
|
2
|
+
import { D as ensurePieceBundle, O as fetchPieceBundle, S as PieceWorker, T as localFirstResolver, a as CompositeBlockExecutor, g as InMemorySecretProvider, i as ActivepiecesBlockExecutor, p as StaticConnectionResolver, r as runWorkflow, t as PieceRegistry, x as PieceWorkerPool } from "./piece-registry-lsGsY9fT.js";
|
|
3
|
+
import { i as loadPieceFromDir, t as buildDescriptor } from "./descriptor-Doax7KPd.js";
|
|
4
4
|
export { ActivepiecesBlockExecutor, CompositeBlockExecutor, InMemorySecretProvider, PieceRegistry, PieceWorker, PieceWorkerPool, StaticConnectionResolver, buildDescriptor, ensurePieceBundle, extractDedupeKey, fetchPieceBundle, loadPieceFromDir, localFirstResolver, runWorkflow };
|
package/dist/worker-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { A as
|
|
2
|
-
import { i as loadPieceFromDir, n as describeProperties, r as loadPiece, t as buildDescriptor } from "./descriptor-
|
|
1
|
+
import { A as REACTOR_FIND, B as getActions, C as InMemoryKeyValueStore, D as OUTPUT_UPDATE, E as LOG_WRITE, F as STORE_GET, I as STORE_PUT, L as UnsupportedContextMemberError, M as REACTOR_MODEL, N as REACTOR_MODELS, O as REACTOR_CREATE, P as STORE_DELETE, R as throwingStub, S as InMemoryConnectionsProvider, T as jsonSafe, V as getTriggers, a as redactMessage, b as maxFileBytes, d as buildTriggerContext, h as StagedFilesService, i as redactError, j as REACTOR_GET, k as REACTOR_EXECUTE, l as installEgressGuard, m as DataUriFilesService, p as runTriggerHook, u as runWithEgressPolicy, v as assertWithinLimit, w as buildActionContext, x as setMaxFileBytes, z as withTouchTracking } from "./redact-ChAU8USo.js";
|
|
2
|
+
import { i as loadPieceFromDir, n as describeProperties, r as loadPiece, t as buildDescriptor } from "./descriptor-Doax7KPd.js";
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
4
|
import { format } from "node:util";
|
|
5
5
|
import { arrayZipperProcessor, formatPieceError, processors } from "@powerhousedao/pieces-framework/host";
|
|
@@ -596,7 +596,10 @@ function dispatch(message) {
|
|
|
596
596
|
}
|
|
597
597
|
process.on("message", (message) => {
|
|
598
598
|
if (!isWorkerMessage(message)) return;
|
|
599
|
-
Promise.resolve().then(() =>
|
|
599
|
+
Promise.resolve().then(() => {
|
|
600
|
+
setMaxFileBytes(message.request.maxFileBytes);
|
|
601
|
+
return runWithEgressPolicy(message.request.egress, () => dispatch(message));
|
|
602
|
+
}).catch((error) => ({
|
|
600
603
|
id: message.id,
|
|
601
604
|
type: "error",
|
|
602
605
|
error: serializeError(error, redactValuesOf(message)),
|
package/dist/worker-entry.js.map
CHANGED
|
@@ -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 connection check. The framework has no\n// checkConnection hook: auth.validate({auth, server}) is the whole contract.\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 validate().\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 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","// 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 {\n normalizePropsValue,\n type NormalizeOptions,\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 { getActions, getTriggers, type ApProperty } from \"../types.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 };\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 // 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\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 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 normalizePropsValue(action.props, 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 // 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 const handle = buildTriggerContext({\n propsValue: await normalizePropsValue(trigger.props, request.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\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const app = piece as {\n checkConnection?: (context: unknown) => unknown;\n };\n if (typeof app.checkConnection !== \"function\") {\n const outcome: CheckConnectionOutcome = { declared: false };\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n }\n const { context, touched } = buildCheckConnectionContext({\n auth: request.auth,\n });\n const result = await app.checkConnection(context);\n const outcome: CheckConnectionOutcome = {\n declared: true,\n result: jsonSafe(result),\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 runWithEgressPolicy(message.request.egress, () => dispatch(message)),\n );\n handler\n .catch(\n (error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(message)),\n tlsPoisoned: consumeTlsFlag(),\n }),\n )\n .then((response) => process.send?.(response))\n .catch(() => process.exit(1));\n});\n"],"mappings":";;;;;;AASA,MAAM,+BAA+B;AASrC,MAAM,0BAAU,IAAI,KAAsB;AAC1C,IAAI,SAAS;AACb,IAAI,YAAY;AAEhB,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,QAAgB,QAAgB;AAC1C,QAAM,cAAc,OAAO,YAAY,SAAS;AAChD,OAAK,OAAO;;;AAIhB,IAAa,uBAAb,cAA0C,MAAM;CA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,MAAM;EAGN,QAAQ,SAAS,WAAW;EAC5B,SAAS,EAAE;EACX,aAAa,gBAAgB;EAC9B;;AAGH,SAAS,gBAAgB,OAA+C;AACtE,KAAI,OAAO,UAAU,YAAY,UAAU,KAAM,QAAO;CACxD,MAAM,OAAQ,MAA6B;AAC3C,QACE,SAAS,SACT,SAAS,qBACT,SAAS,kBACT,SAAS,sBACT,SAAS;;AAIb,SAAS,SAAS,SAAwD;AACxE,SAAQ,QAAQ,MAAhB;EACE,KAAK,MACH,QAAO,UAAU,QAAQ;EAC3B,KAAK,kBACH,QAAO,qBAAqB,QAAQ;EACtC,KAAK,eACH,QAAO,kBAAkB,QAAQ;EACnC,KAAK,mBACH,QAAO,sBAAsB,QAAQ;EACvC,KAAK,WACH,QAAO,eAAe,QAAQ;;;AAIpC,QAAQ,GAAG,YAAY,YAAqB;AAC1C,KAAI,CAAC,gBAAgB,QAAQ,CAAE;AAGf,SAAQ,SAAS,CAAC,WAChC,oBAAoB,QAAQ,QAAQ,cAAc,SAAS,QAAQ,CAAC,CACrE,CAEE,OACE,WAAoC;EACnC,IAAI,QAAQ;EACZ,MAAM;EACN,OAAO,eAAe,OAAO,eAAe,QAAQ,CAAC;EACrD,aAAa,gBAAgB;EAC9B,EACF,CACA,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 connection check. The framework has no\n// checkConnection hook: auth.validate({auth, server}) is the whole contract.\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 validate().\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 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","// 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 type NormalizeOptions,\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 { getActions, getTriggers, type ApProperty } from \"../types.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 };\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 // 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\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 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 normalizePropsValue(action.props, 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 // 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 const handle = buildTriggerContext({\n propsValue: await normalizePropsValue(trigger.props, request.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\nasync function handleCheckConnection(\n message: CheckConnectionMessage,\n): Promise<WorkerResponse> {\n const { request } = message;\n const { piece } = await loadCached(request);\n const app = piece as {\n checkConnection?: (context: unknown) => unknown;\n };\n if (typeof app.checkConnection !== \"function\") {\n const outcome: CheckConnectionOutcome = { declared: false };\n return {\n id: message.id,\n type: \"result\",\n output: outcome,\n touched: [],\n tlsPoisoned: consumeTlsFlag(),\n };\n }\n const { context, touched } = buildCheckConnectionContext({\n auth: request.auth,\n });\n const result = await app.checkConnection(context);\n const outcome: CheckConnectionOutcome = {\n declared: true,\n result: jsonSafe(result),\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(\n (error: unknown): WorkerResponse => ({\n id: message.id,\n type: \"error\",\n error: serializeError(error, redactValuesOf(message)),\n tlsPoisoned: consumeTlsFlag(),\n }),\n )\n .then((response) => process.send?.(response))\n .catch(() => process.exit(1));\n});\n"],"mappings":";;;;;;AASA,MAAM,+BAA+B;AASrC,MAAM,0BAAU,IAAI,KAAsB;AAC1C,IAAI,SAAS;AACb,IAAI,YAAY;AAEhB,IAAa,gBAAb,cAAmC,MAAM;CACvC,YAAY,QAAgB,QAAgB;AAC1C,QAAM,cAAc,OAAO,YAAY,SAAS;AAChD,OAAK,OAAO;;;AAIhB,IAAa,uBAAb,cAA0C,MAAM;CAC9C,YAAY,QAAgB,WAAmB;AAC7C,QAAM,cAAc,OAAO,yBAAyB,UAAU,IAAI;AAClE,OAAK,OAAO;;;AAIhB,SAAS,mBAAmB,OAA2C;AACrE,QACE,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS;;AAM3C,SAAS,kBAAwB;AAC/B,KAAI,UAAW;AACf,aAAY;AACZ,SAAQ,GAAG,YAAY,YAAqB;AAC1C,MAAI,CAAC,mBAAmB,QAAQ,CAAE;EAClC,MAAM,QAAQ,QAAQ,IAAI,QAAQ,GAAG;AACrC,MAAI,CAAC,MAAO;AACZ,UAAQ,OAAO,QAAQ,GAAG;AAC1B,eAAa,MAAM,MAAM;AACzB,MAAI,QAAQ,UAAU,KAAA,GAAW;AAC/B,SAAM,OAAO,IAAI,cAAc,MAAM,QAAQ,QAAQ,MAAM,CAAC;AAC5D;;AAEF,QAAM,QAAQ,QAAQ,MAAM;GAC5B;;AAGJ,SAAgB,SACd,QACA,SACA,YAAoB,8B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AAQ,QAAQ,aAAa;AAC7C,SAAO,oBAAoB,QAAQ,QAAQ,cAAc,SAAS,QAAQ,CAAC;GAC3E,CAEC,OACE,WAAoC;EACnC,IAAI,QAAQ;EACZ,MAAM;EACN,OAAO,eAAe,OAAO,eAAe,QAAQ,CAAC;EACrD,aAAa,gBAAgB;EAC9B,EACF,CACA,MAAM,aAAa,QAAQ,OAAO,SAAS,CAAC,CAC5C,YAAY,QAAQ,KAAK,EAAE,CAAC;EAC/B"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerhousedao/reactor-workflow",
|
|
3
|
-
"version": "6.2.3-dev.
|
|
3
|
+
"version": "6.2.3-dev.21",
|
|
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.
|
|
33
|
-
"@powerhousedao/reactor": "6.2.3-dev.
|
|
34
|
-
"@powerhousedao/shared": "6.2.3-dev.
|
|
35
|
-
"@powerhousedao/workflow": "6.2.3-dev.
|
|
32
|
+
"@powerhousedao/pieces-framework": "6.2.3-dev.21",
|
|
33
|
+
"@powerhousedao/reactor": "6.2.3-dev.21",
|
|
34
|
+
"@powerhousedao/shared": "6.2.3-dev.21",
|
|
35
|
+
"@powerhousedao/workflow": "6.2.3-dev.21",
|
|
36
36
|
"croner": "10.0.1",
|
|
37
|
-
"document-model": "6.2.3-dev.
|
|
37
|
+
"document-model": "6.2.3-dev.21",
|
|
38
38
|
"graphql": "^16"
|
|
39
39
|
},
|
|
40
40
|
"devDependencies": {
|