@plugmatica/plugin-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +136 -2
- package/dist/advanced.d.ts +315 -0
- package/dist/advanced.js +3 -0
- package/dist/advanced.js.map +1 -0
- package/dist/chunk-ACHELRPS.js +182 -0
- package/dist/chunk-ACHELRPS.js.map +1 -0
- package/dist/chunk-AFVR6B2A.js +256 -0
- package/dist/chunk-AFVR6B2A.js.map +1 -0
- package/dist/chunk-YY4H56JF.js +84 -0
- package/dist/chunk-YY4H56JF.js.map +1 -0
- package/dist/extension-index.d.ts +178 -0
- package/dist/extension-index.js +3 -0
- package/dist/extension-index.js.map +1 -0
- package/dist/host.d.ts +859 -0
- package/dist/host.js +2280 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +1465 -0
- package/dist/index.js +749 -0
- package/dist/index.js.map +1 -0
- package/dist/types-83DpQEKd.d.ts +599 -0
- package/package.json +107 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/entities.ts","../src/routes.ts","../src/workflowNodes.ts","../src/workflowNodeFacet.ts","../src/defineWorkflowNode.ts","../src/workflowNodeFields.ts"],"names":["segment","value","segments"],"mappings":";;;;;;;;;AAy8BA,IAAM,0BAAA,GAA6B,IAAI,IAAA,GAAO,IAAA;AAevC,SAAS,WAAA,CACd,KACA,MAAA,EACsB;AACtB,EAAA,MAAM,IAAA,GAAO,CAAA,WAAA,EAAc,OAAA,CAAQ,MAAM,CAAC,CAAA,CAAA;AAC1C,EAAA,MAAM,WAAA,GAAc,GAAG,IAAI,CAAA,SAAA,CAAA;AAC3B,EAAA,MAAM,WAAA,GAAc,GAAG,IAAI,CAAA,SAAA,CAAA;AAE3B,EAAA,OAAO;AAAA,IACL,WAAW,CAAC,KAAA,KAAU,oBAAA,CAAqB,GAAA,EAAK,MAAM,KAAK,CAAA;AAAA,IAC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AAgB,CAAA;AACvC,IAAA,MAAM,UAAA,GAAa,CAAC,WAAA,KAAgB,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,OAAA,IAChE,qBAAA,CAAsB,OAAA,GAAU,OAAA,EAAS,KAAA,GAAQ,iBAAiB,CAAA,CAAA;AACpE,IAAA,MAAA,CAAO,IAAA,CAAK,OAAO,MAAA,CAAO,EAAE,MAAM,QAAA,EAAU,IAAA,EAAM,UAAA,EAAY,CAAC,CAAA;AAAA,EACjE;AACA,EAAA,OAAO,MAAA,CAAO,OAAO,MAAM,CAAA;AAC7B","file":"index.js","sourcesContent":["import type { PluginApiClient, PluginApiRequestOptions } from \"./types\";\n\n/**\n * Field kinds supported by Plugmatica object-resource entity schemas.\n */\nexport type PluginEntityFieldKind =\n | \"id\"\n | \"string\"\n | \"integer\"\n | \"number\"\n | \"boolean\"\n | \"date\"\n | \"date_time\"\n | \"json\"\n | \"blob_ref\"\n | \"entity_ref\";\n\n/**\n * Sensitivity levels attached to object-resource fields.\n */\nexport type PluginEntityFieldSensitivity = \"normal\" | \"sensitive\" | \"secret\";\n\n/**\n * One effective entity field after owner and augmentation schemas have been merged.\n */\nexport type EffectiveEntityField = {\n /**\n * Stable field/remote/contribution name.\n */\n name: string;\n /**\n * Plugin that owns the effective field definition.\n */\n ownerPlugin: string;\n /**\n * Whether the field originates from the base entity or an augmentation.\n */\n ownerKind: \"entity\" | \"augmentation\";\n /**\n * Entity or augmentation key that owns the field.\n */\n ownerKey: string;\n /**\n * Effective field descriptor and access metadata.\n */\n descriptor: {\n name: string;\n kind: PluginEntityFieldKind;\n nullable: boolean;\n id: boolean;\n indexed: boolean;\n /** Target entity metadata for entity_ref fields. */\n entityRef?: { plugin: string; entity: string } | null;\n access: {\n sensitivity: PluginEntityFieldSensitivity;\n readCapability?: string | null;\n writeCapability?: string | null;\n };\n };\n};\n\n/**\n * One augmentation included in an effective entity schema.\n */\nexport type EffectiveEntityAugmentation = {\n /**\n * Plugin identifier or plugin identity associated with this value.\n */\n plugin: string;\n /**\n * Stable entity augmentation or contribution key.\n */\n key: string;\n /**\n * Schema version associated with this entity value/definition.\n */\n schemaVersion: number;\n /**\n * Augmentation depth from the base entity.\n */\n depth: number;\n /**\n * Generated/normalized target identifying what this extension or augmentation applies to.\n */\n target:\n | { kind: \"entity\"; plugin: string; entity: string }\n | { kind: \"augmentation\"; plugin: string; augmentation: string };\n};\n\n/**\n * Effective object-resource schema returned by the runtime for an entity.\n */\nexport type EffectiveEntitySchema = {\n /**\n * Plugin identifier or plugin identity associated with this value.\n */\n plugin: string;\n /**\n * Entity resource name.\n */\n entity: string;\n /**\n * Schema version associated with this entity value/definition.\n */\n schemaVersion: number;\n /**\n * Revision fingerprint for the effective merged entity shape.\n */\n shapeRevision: string;\n /**\n * Fields included in the effective entity schema/export.\n */\n fields: EffectiveEntityField[];\n /**\n * Augmentations included in the effective entity schema.\n */\n augmentations: EffectiveEntityAugmentation[];\n};\n\n/**\n * Entity value plus optimistic-concurrency and schema metadata.\n */\nexport type EntityEnvelope<T> = {\n /**\n * Entity or provider value represented by this result.\n */\n value: T;\n /**\n * Optimistic-concurrency revision of the entity.\n */\n revision: number;\n /**\n * Schema version associated with this entity value/definition.\n */\n schemaVersion: number;\n};\n\n/**\n * Paginated entity-list response returned by object-resource APIs.\n */\nexport type EntityListResponse<T> = {\n /**\n * Items returned by this paginated/preview result.\n */\n items: EntityEnvelope<T>[];\n /**\n * Cursor for the next page, or `null` when there is no next page.\n */\n nextCursor: string | null;\n};\n\n/**\n * Pagination options for listing object-resource entities.\n */\nexport type EntityListOptions = {\n /**\n * Maximum number of items/rows to return.\n */\n limit?: number;\n /**\n * Cursor identifying the next entity-list page.\n */\n cursor?: string | number | null;\n};\n\n/**\n * Optimistic-concurrency update request for one entity.\n */\nexport type EntityUpdate<T> = {\n /**\n * Entity revision that must still be current for the write to succeed.\n */\n expectedRevision: number;\n /**\n * Partial entity fields to update.\n */\n patch: Partial<T>;\n};\n\n/**\n * Filter expression applied by object-resource list/export operations.\n */\nexport type EntityFilterOperator =\n \"eq\" | \"in\" | \"contains\" | \"startsWith\" | \"endsWith\" | \"gt\" | \"lt\";\n\nexport type EntityFilter = {\n /**\n * Entity field referenced by this filter/error.\n */\n field: string;\n /**\n * Indexed filter operator. Omitted values preserve equality semantics.\n */\n operator?: EntityFilterOperator;\n /**\n * Indexed filter value. `in` requires a non-empty array. Legacy equality\n * arrays retain any-of semantics; separate filters are ANDed.\n */\n value: unknown;\n};\n\n/**\n * Public bulk modes available to plugin/frontend code.\n *\n * `restore` is intentionally absent. Trusted restore is a host/platform-admin\n * capability and must not be exposed through the plugin SDK.\n */\nexport type EntityBulkMode = \"full\" | \"validated\";\n\n/**\n * One create row submitted to the immediate bulk-write API.\n */\nexport type EntityBulkCreateRow<T> = {\n /**\n * Optional caller-supplied row identifier echoed in results/errors.\n */\n clientRowId?: string;\n /**\n * Entity or provider value represented by this result.\n */\n value: Partial<T>;\n};\n\n/**\n * One update row submitted to the immediate bulk-write API.\n */\nexport type EntityBulkUpdateRow<T> = {\n /**\n * Optional caller-supplied row identifier echoed in results/errors.\n */\n clientRowId?: string;\n /**\n * Persistent entity identifier.\n */\n pid: string;\n /**\n * Entity revision that must still be current for the write to succeed.\n */\n expectedRevision: number;\n /**\n * Partial entity fields to update.\n */\n patch: Partial<T>;\n};\n\n/**\n * Immediate bounded bulk-write request for create or update operations.\n */\nexport type EntityBulkWriteRequest<T> =\n | {\n mode: \"validated\";\n writeMode: \"create\";\n rows: EntityBulkCreateRow<T>[];\n }\n | {\n mode: \"full\";\n writeMode: \"create\";\n rows: EntityBulkCreateRow<T>[];\n }\n | {\n mode: \"full\";\n writeMode: \"update\";\n rows: EntityBulkUpdateRow<T>[];\n };\n\n/**\n * Successful row result returned by an immediate bulk write.\n */\nexport type EntityBulkRowResult = {\n /**\n * Zero-based input row index.\n */\n index: number;\n /**\n * Optional caller-supplied row identifier echoed in results/errors.\n */\n clientRowId?: string | null;\n /**\n * Persistent entity identifier.\n */\n pid: string;\n /**\n * Optimistic-concurrency revision of the entity.\n */\n revision: number;\n /**\n * Schema version associated with this entity value/definition.\n */\n schemaVersion: number;\n};\n\n/**\n * Validation or write error associated with one bulk/import row.\n */\nexport type EntityBulkRowError = {\n /**\n * Zero-based input row index.\n */\n index: number;\n /**\n * Optional caller-supplied row identifier echoed in results/errors.\n */\n clientRowId?: string | null;\n /**\n * Entity field referenced by this filter/error.\n */\n field?: string | null;\n /**\n * Stable machine-readable code.\n */\n code: string;\n /**\n * Human-readable diagnostic/error message.\n */\n message: string;\n /**\n * Optional structured diagnostic details.\n */\n details?: unknown;\n};\n\n/**\n * Aggregate and per-row result returned by an immediate bulk write.\n */\nexport type EntityBulkWriteResponse = {\n /**\n * Selected execution/import/session mode.\n */\n mode: EntityBulkMode;\n /**\n * Whether rows create new entities or update existing entities.\n */\n writeMode: \"create\" | \"update\";\n /**\n * Number of rows received by the bulk operation.\n */\n received: number;\n /**\n * Number of rows written successfully.\n */\n succeeded: number;\n /**\n * Number of rows that failed validation or writing.\n */\n failed: number;\n /**\n * Rows included in the bulk request/result.\n */\n rows: EntityBulkRowResult[];\n /**\n * Validation/write errors associated with this result.\n */\n errors: EntityBulkRowError[];\n};\n\n/**\n * File formats accepted by staged entity imports.\n */\nexport type EntityImportFormat = \"csv\" | \"ndjson\";\n\n/**\n * Lifecycle states reported for a staged entity import.\n */\nexport type EntityImportStatus =\n | \"created\"\n | \"uploading\"\n | \"uploaded\"\n | \"validating\"\n | \"ready\"\n | \"committing\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\";\n\n/**\n * CSV parsing options for a staged entity import.\n */\nexport type EntityImportCsvOptions = {\n /**\n * Has header associated with this entity import csv options.\n */\n hasHeader?: boolean;\n /**\n * CSV field delimiter.\n */\n delimiter?: string;\n /**\n * CSV quote character.\n */\n quote?: string;\n /**\n * Null values associated with this entity import csv options.\n */\n nullValues?: string[];\n};\n\n/**\n * Request used to create a staged entity-import job.\n */\nexport type EntityImportCreateRequest =\n | {\n mode: \"validated\";\n writeMode: \"create\";\n format: EntityImportFormat;\n fileName?: string;\n fieldMap?: Record<string, string>;\n csv?: EntityImportCsvOptions;\n chunkRows?: number;\n }\n | {\n mode: \"full\";\n writeMode: \"create\" | \"update\";\n format: EntityImportFormat;\n fileName?: string;\n fieldMap?: Record<string, string>;\n csv?: EntityImportCsvOptions;\n chunkRows?: number;\n };\n\n/**\n * Current state and counters for a staged entity-import job.\n */\nexport type EntityImportJob = {\n /**\n * Persistent entity identifier.\n */\n pid: string;\n /**\n * Plugin identifier or plugin identity associated with this value.\n */\n plugin: string;\n /**\n * Entity resource name.\n */\n entity: string;\n /**\n * Selected execution/import/session mode.\n */\n mode: EntityBulkMode;\n /**\n * Whether rows create new entities or update existing entities.\n */\n writeMode: \"create\" | \"update\";\n /**\n * Import/export file format.\n */\n format: EntityImportFormat;\n /**\n * Resolution/job/runtime status.\n */\n status: EntityImportStatus;\n /**\n * Suggested/source file name.\n */\n fileName: string | null;\n /**\n * Total size of the import source in bytes.\n */\n sourceBytes: number;\n /**\n * Number of source bytes uploaded so far.\n */\n uploadedBytes: number;\n /**\n * Total parsed/exportable row count when known.\n */\n totalRows: number;\n /**\n * Number of import rows processed so far.\n */\n processedRows: number;\n /**\n * Number of import rows that passed validation.\n */\n validRows: number;\n /**\n * Number of import rows that failed validation.\n */\n invalidRows: number;\n /**\n * Number of entities created by the import.\n */\n createdRows: number;\n /**\n * Number of entities updated by the import.\n */\n updatedRows: number;\n /**\n * Number of rows that failed during import.\n */\n failedRows: number;\n /**\n * Job-level failure message, or `null` when no job failure is recorded.\n */\n errorMessage: string | null;\n /**\n * ISO timestamp when the job was created.\n */\n createdAt: string;\n /**\n * ISO timestamp when the job was last updated.\n */\n updatedAt: string;\n /**\n * ISO timestamp when the job reached a terminal state, or `null` while active.\n */\n completedAt: string | null;\n};\n\n/**\n * One parsed row returned by an import preview.\n */\nexport type EntityImportPreviewRow<T> = {\n /**\n * Source row number represented by this preview entry.\n */\n row: number;\n /**\n * Entity or provider value represented by this result.\n */\n value: Partial<T> | null;\n /**\n * Validation/write errors associated with this result.\n */\n errors: EntityBulkRowError[];\n};\n\n/**\n * Paginated preview of parsed rows from a staged entity import.\n */\nexport type EntityImportPreview<T> = {\n /**\n * Items returned by this paginated/preview result.\n */\n items: EntityImportPreviewRow<T>[];\n /**\n * Offset for the next preview page, or `null` when complete.\n */\n nextOffset: number | null;\n};\n\n/**\n * Byte-level progress reported while uploading an import source.\n */\nexport type EntityImportUploadProgress = {\n /**\n * Number of source bytes uploaded so far.\n */\n uploadedBytes: number;\n /**\n * Total upload size in bytes.\n */\n totalBytes: number;\n /**\n * Upload completion fraction from 0 to 1.\n */\n fraction: number;\n};\n\n/**\n * Options controlling chunked upload of an import source.\n */\nexport type EntityImportUploadOptions = {\n /**\n * Maximum bytes sent in each browser upload request.\n */\n chunkBytes?: number;\n /**\n * Suggested/source file name.\n */\n fileName?: string;\n /**\n * Abort signal cancelled when the owning runtime scope becomes stale.\n */\n signal?: AbortSignal;\n /**\n * Callback invoked after each successfully uploaded chunk.\n *\n * @param progress Updated upload progress after one chunk completes.\n */\n onProgress?: (progress: EntityImportUploadProgress) => void;\n};\n\n/**\n * Pagination options for an import preview.\n */\nexport type EntityImportPreviewOptions = {\n /**\n * Zero-based preview row offset.\n */\n offset?: number;\n /**\n * Maximum number of items/rows to return.\n */\n limit?: number;\n};\n\n/**\n * File formats supported by staged entity exports.\n */\nexport type EntityExportFormat = \"csv\" | \"ndjson\";\n\n/**\n * Lifecycle states reported for a staged entity export.\n */\nexport type EntityExportStatus =\n \"queued\" | \"exporting\" | \"completed\" | \"failed\" | \"cancelled\";\n\n/**\n * Request used to create a staged entity-export job.\n */\nexport type EntityExportCreateRequest = {\n /**\n * Import/export file format.\n */\n format: EntityExportFormat;\n /**\n * Entity filters applied to the export.\n */\n filters?: EntityFilter[];\n /**\n * Fields included in the effective entity schema/export.\n */\n fields?: string[];\n /**\n * Whether Plugmatica metadata columns are included in the export.\n */\n includeMetadata?: boolean;\n /**\n * Suggested/source file name.\n */\n fileName?: string;\n /**\n * Rows processed per server-side chunk.\n */\n chunkRows?: number;\n};\n\n/**\n * Current state and counters for a staged entity-export job.\n */\nexport type EntityExportJob = {\n /**\n * Persistent entity identifier.\n */\n pid: string;\n /**\n * Plugin identifier or plugin identity associated with this value.\n */\n plugin: string;\n /**\n * Entity resource name.\n */\n entity: string;\n /**\n * Import/export file format.\n */\n format: EntityExportFormat;\n /**\n * Resolution/job/runtime status.\n */\n status: EntityExportStatus;\n /**\n * Suggested/source file name.\n */\n fileName: string | null;\n /**\n * Total parsed/exportable row count when known.\n */\n totalRows: number | null;\n /**\n * Number of entity rows written to the export so far.\n */\n exportedRows: number;\n /**\n * Current size of the generated export in bytes.\n */\n outputBytes: number;\n /**\n * Job-level failure message, or `null` when no job failure is recorded.\n */\n errorMessage: string | null;\n /**\n * ISO timestamp when the job was created.\n */\n createdAt: string;\n /**\n * ISO timestamp when the job was last updated.\n */\n updatedAt: string;\n /**\n * ISO timestamp when the job reached a terminal state, or `null` while active.\n */\n completedAt: string | null;\n};\n\n/**\n * Runtime-owned reference to another Plugmatica entity.\n *\n * Plugin code normally obtains these through an entity reference field rather\n * than naming the target plugin/entity directly.\n */\nexport type EntityReference = {\n plugin: string;\n entity: string;\n pid: string;\n};\n\n/** Human-readable projection returned for an EntityRef field. */\nexport type EntityReferenceOption = {\n reference: EntityReference;\n label: string;\n};\n\n/** Search options for an EntityRef field declared by the current plugin. */\nexport type EntityReferenceSearchOptions = {\n text?: string;\n limit?: number;\n cursor?: string | null;\n};\n\n/** Batch response for resolving existing EntityRef PIDs. */\nexport type EntityReferenceResolveResponse = {\n items: EntityReferenceOption[];\n};\n\n/** One bounded search page for an EntityRef field. */\nexport type EntityReferenceSearchResponse = {\n items: EntityReferenceOption[];\n nextCursor: string | null;\n /** Runtime-derived primary display field, when one is available. */\n displayField: string | null;\n /** Runtime-derived indexed string fields used for generic reference search. */\n searchFields: string[];\n};\n\n/**\n * Read-only resolver for one EntityRef field owned by the current plugin.\n *\n * The browser supplies only the owning entity and field. The runtime resolves\n * the target plugin/entity from the effective entity schema, preserving plugin\n * isolation and avoiding direct knowledge of another plugin.\n */\nexport type OwnerEntityReferenceClient = {\n search(\n options?: EntityReferenceSearchOptions,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityReferenceSearchResponse>;\n resolve(\n pid: string,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityReferenceOption>;\n resolveMany(\n pids: readonly string[],\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityReferenceOption[]>;\n};\n\n/**\n * Object-resource client for an entity owned by the current plugin.\n */\nexport type OwnerEntityClient<T extends Record<string, unknown>> = {\n /**\n * Follow one EntityRef field declared by this owned entity. The target is\n * resolved by the runtime from entity metadata; callers do not name another\n * plugin or target entity.\n */\n reference(field: string): OwnerEntityReferenceClient;\n /**\n * Load the effective merged schema for this entity.\n *\n * @param requestOptions Optional transport request settings.\n * @returns Effective schema after owner/dependency contributions and runtime policy are applied.\n */\n schema(\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EffectiveEntitySchema>;\n /**\n * List entities owned by the current plugin.\n *\n * @param options Entity pagination/filter options.\n * @param requestOptions Optional transport request settings.\n * @returns Page of entity envelopes plus pagination metadata.\n */\n list(\n options?: EntityListOptions,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityListResponse<T>>;\n /**\n * Load one owned entity by persistent identifier.\n *\n * @param pid Persistent entity identifier.\n * @param requestOptions Optional transport request settings.\n * @returns Entity envelope containing the value, persistent identifier and revision.\n */\n get(\n pid: string,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityEnvelope<T>>;\n /**\n * Create one entity value.\n *\n * @param value Input value to normalize/convert.\n * @returns Created entity envelope including its assigned identifier and revision.\n */\n create(value: Partial<T>): Promise<EntityEnvelope<T>>;\n /**\n * Update one entity using optimistic concurrency.\n *\n * @param pid Persistent entity identifier.\n * @param update Patch and expected revision for the entity update.\n * @returns Updated entity envelope at the new revision.\n */\n update(pid: string, update: EntityUpdate<T>): Promise<EntityEnvelope<T>>;\n /**\n * Delete one entity using optimistic concurrency.\n *\n * @param pid Persistent entity identifier.\n * @param expectedRevision Current entity revision required for optimistic concurrency.\n * @returns Confirmation containing the deleted persistent identifier.\n */\n delete(\n pid: string,\n expectedRevision: number,\n ): Promise<{ deleted: true; pid: string }>;\n\n /** Immediate bounded bulk write. Large files should use staged imports. */\n /**\n * @param request Request payload/options for this operation.\n * @returns Per-row bulk-write outcome and aggregate counts.\n */\n bulkWrite(\n request: EntityBulkWriteRequest<T>,\n ): Promise<EntityBulkWriteResponse>;\n\n /**\n * Create a staged import job.\n *\n * @param request Request payload/options for this operation.\n * @returns Newly created staged import job.\n */\n createImport(request: EntityImportCreateRequest): Promise<EntityImportJob>;\n /**\n * Upload the source content for a staged import job.\n *\n * @param pid Persistent entity identifier.\n * @param source Blob/File containing the staged import source.\n * @param options Chunking, file-name, cancellation and progress settings.\n * @returns Import job state after the source upload completes.\n */\n uploadImport(\n pid: string,\n source: Blob,\n options?: EntityImportUploadOptions,\n ): Promise<EntityImportJob>;\n /**\n * Load the current state of a staged import job.\n *\n * @param pid Persistent entity identifier.\n * @returns Current staged import job state.\n */\n getImport(pid: string): Promise<EntityImportJob>;\n /**\n * Preview parsed/validated rows from a staged import.\n *\n * @param pid Persistent entity identifier.\n * @param options Preview pagination settings.\n * @returns Preview rows, validation information and preview pagination metadata.\n */\n previewImport(\n pid: string,\n options?: EntityImportPreviewOptions,\n ): Promise<EntityImportPreview<T>>;\n /**\n * Run server-side validation for a staged import.\n *\n * @param pid Persistent entity identifier.\n * @returns Import job after server-side validation has run.\n */\n validateImport(pid: string): Promise<EntityImportJob>;\n /**\n * Commit a validated staged import.\n *\n * @param pid Persistent entity identifier.\n * @returns Import job after the commit request has been accepted/applied.\n */\n commitImport(pid: string): Promise<EntityImportJob>;\n /**\n * Cancel a staged import that has not completed.\n *\n * @param pid Persistent entity identifier.\n * @returns Import job after cancellation is requested.\n */\n cancelImport(pid: string): Promise<EntityImportJob>;\n /**\n * Download the row-error artifact for a staged import.\n *\n * @param pid Persistent entity identifier.\n * @returns Blob containing the generated import row-error artifact.\n */\n downloadImportErrors(pid: string): Promise<Blob>;\n\n /**\n * Create a staged entity export job.\n *\n * @param request Request payload/options for this operation.\n * @returns Newly created staged export job.\n */\n createExport(request: EntityExportCreateRequest): Promise<EntityExportJob>;\n /**\n * Load the current state of a staged export job.\n *\n * @param pid Persistent entity identifier.\n * @returns Current staged export job state.\n */\n getExport(pid: string): Promise<EntityExportJob>;\n /**\n * Cancel a staged export that has not completed.\n *\n * @param pid Persistent entity identifier.\n * @returns Export job after cancellation is requested.\n */\n cancelExport(pid: string): Promise<EntityExportJob>;\n /**\n * Download the completed export artifact.\n *\n * @param pid Persistent entity identifier.\n * @returns Blob containing the completed export artifact.\n */\n downloadExport(pid: string): Promise<Blob>;\n};\n\n/**\n * Read-only object-resource client for an entity exposed by a declared plugin dependency.\n */\nexport type DependencyEntityClient<T extends Record<string, unknown>> = {\n /**\n * Load the effective merged schema exposed by the dependency entity.\n *\n * @param requestOptions Optional transport request settings.\n * @returns Effective schema after owner/dependency contributions and runtime policy are applied.\n */\n schema(\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EffectiveEntitySchema>;\n /**\n * List entities exposed by the declared dependency.\n *\n * @param options Entity pagination/filter options.\n * @param requestOptions Optional transport request settings.\n * @returns Page of entity envelopes plus pagination metadata.\n */\n list(\n options?: EntityListOptions,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityListResponse<T>>;\n /**\n * Load one dependency entity by persistent identifier.\n *\n * @param pid Persistent entity identifier.\n * @param requestOptions Optional transport request settings.\n * @returns Entity envelope containing the value, persistent identifier and revision.\n */\n get(\n pid: string,\n requestOptions?: PluginApiRequestOptions,\n ): Promise<EntityEnvelope<T>>;\n};\n\nconst DEFAULT_UPLOAD_CHUNK_BYTES = 8 * 1024 * 1024;\n\n/**\n * Create an object-resource client for an entity owned by the current plugin.\n *\n * @param api Plugin-scoped API client.\n * @param entity Entity resource name.\n * @returns Entity client scoped to the current plugin owner route.\n * @example\n * ```ts\n * const api = usePluginApi();\n * const customers = ownerEntity<Customer>(api, \"customer\");\n * const page = await customers.list({ limit: 50 });\n * ```\n */\nexport function ownerEntity<T extends Record<string, unknown>>(\n api: PluginApiClient,\n entity: string,\n): OwnerEntityClient<T> {\n const base = `/_entities/${segment(entity)}`;\n const importsBase = `${base}/_imports`;\n const exportsBase = `${base}/_exports`;\n\n return {\n reference: (field) => ownerEntityReference(api, base, field),\n schema: (requestOptions) =>\n api.get<EffectiveEntitySchema>(`${base}/_schema`, requestOptions),\n list: (options, requestOptions) =>\n api.get<EntityListResponse<T>>(\n `${base}${pageQuery(options)}`,\n requestOptions,\n ),\n get: (pid, requestOptions) =>\n api.get<EntityEnvelope<T>>(`${base}/${segment(pid)}`, requestOptions),\n create: (value) => api.post<EntityEnvelope<T>>(base, { value }),\n update: (pid, update) =>\n api.patch<EntityEnvelope<T>>(`${base}/${segment(pid)}`, update),\n delete: (pid, expectedRevision) => {\n const query = new URLSearchParams({\n expectedRevision: String(expectedRevision),\n });\n return api.delete<{ deleted: true; pid: string }>(\n `${base}/${segment(pid)}?${query.toString()}`,\n );\n },\n\n bulkWrite: (request) =>\n api.post<EntityBulkWriteResponse>(`${base}/_bulk`, request),\n\n createImport: (request) => api.post<EntityImportJob>(importsBase, request),\n\n uploadImport: (pid, source, options) =>\n uploadImportSource(\n api,\n `${importsBase}/${segment(pid)}/content`,\n source,\n options,\n ),\n\n getImport: (pid) =>\n api.get<EntityImportJob>(`${importsBase}/${segment(pid)}`),\n\n previewImport: (pid, options) =>\n api.get<EntityImportPreview<T>>(\n `${importsBase}/${segment(pid)}/preview${previewQuery(options)}`,\n ),\n\n validateImport: (pid) =>\n api.post<EntityImportJob>(`${importsBase}/${segment(pid)}/validate`),\n\n commitImport: (pid) =>\n api.post<EntityImportJob>(`${importsBase}/${segment(pid)}/commit`),\n\n cancelImport: (pid) =>\n api.post<EntityImportJob>(`${importsBase}/${segment(pid)}/cancel`),\n\n downloadImportErrors: (pid) =>\n api.getBlob(`${importsBase}/${segment(pid)}/errors`),\n\n createExport: (request) => api.post<EntityExportJob>(exportsBase, request),\n\n getExport: (pid) =>\n api.get<EntityExportJob>(`${exportsBase}/${segment(pid)}`),\n\n cancelExport: (pid) =>\n api.post<EntityExportJob>(`${exportsBase}/${segment(pid)}/cancel`),\n\n downloadExport: (pid) =>\n api.getBlob(`${exportsBase}/${segment(pid)}/content`),\n };\n}\n\n/**\n * Create a read-only object-resource client for an entity exposed by a declared plugin dependency.\n *\n * @param api Plugin-scoped API client.\n * @param plugin Dependency plugin identifier.\n * @param entity Entity resource name.\n * @returns Read-only entity client scoped to the declared dependency route.\n * @example\n * ```ts\n * const api = usePluginApi();\n * const customers = dependencyEntity<Customer>(\n * api,\n * \"plugmatica.customer\",\n * \"customer\",\n * );\n * const customer = await customers.get(customerPid);\n * ```\n */\nexport function dependencyEntity<T extends Record<string, unknown>>(\n api: PluginApiClient,\n plugin: string,\n entity: string,\n): DependencyEntityClient<T> {\n const base = `/_dependencies/${segment(plugin)}/entities/${segment(entity)}`;\n return {\n schema: (requestOptions) =>\n api.get<EffectiveEntitySchema>(`${base}/_schema`, requestOptions),\n list: (options, requestOptions) =>\n api.get<EntityListResponse<T>>(\n `${base}${pageQuery(options)}`,\n requestOptions,\n ),\n get: (pid, requestOptions) =>\n api.get<EntityEnvelope<T>>(`${base}/${segment(pid)}`, requestOptions),\n };\n}\n\nfunction ownerEntityReference(\n api: PluginApiClient,\n ownerBase: string,\n field: string,\n): OwnerEntityReferenceClient {\n const base = `${ownerBase}/_references/${segment(field)}`;\n return {\n search: (options, requestOptions) =>\n api.get<EntityReferenceSearchResponse>(\n `${base}${referenceSearchQuery(options)}`,\n requestOptions,\n ),\n resolve: (pid, requestOptions) =>\n api.get<EntityReferenceOption>(`${base}/${segment(pid)}`, requestOptions),\n resolveMany: (pids, requestOptions) =>\n api\n .post<EntityReferenceResolveResponse>(\n `${base}/_resolve`,\n { pids: [...pids] },\n requestOptions,\n )\n .then((response) => response.items),\n };\n}\n\nfunction referenceSearchQuery(options?: EntityReferenceSearchOptions): string {\n if (!options) return \"\";\n const query = new URLSearchParams();\n const text = options.text?.trim();\n if (text) query.set(\"q\", text);\n if (options.limit != null) query.set(\"limit\", String(options.limit));\n if (options.cursor) query.set(\"cursor\", options.cursor);\n const encoded = query.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nasync function uploadImportSource(\n api: PluginApiClient,\n path: string,\n source: Blob,\n options?: EntityImportUploadOptions,\n): Promise<EntityImportJob> {\n if (source.size <= 0) {\n throw new Error(\"Import source cannot be empty.\");\n }\n\n const chunkBytes = options?.chunkBytes ?? DEFAULT_UPLOAD_CHUNK_BYTES;\n if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) {\n throw new Error(\"Import upload chunkBytes must be a positive integer.\");\n }\n\n const sourceName = options?.fileName ?? blobName(source);\n let offset = 0;\n let job: EntityImportJob | null = null;\n\n while (offset < source.size) {\n if (options?.signal?.aborted) {\n throw abortError();\n }\n\n const endExclusive = Math.min(offset + chunkBytes, source.size);\n const chunk = source.slice(offset, endExclusive, source.type);\n const headers = new Headers();\n headers.set(\n \"Content-Range\",\n `bytes ${offset}-${endExclusive - 1}/${source.size}`,\n );\n headers.set(\"Content-Type\", source.type || \"application/octet-stream\");\n if (sourceName) {\n headers.set(\"X-Upload-Filename\", encodeURIComponent(sourceName));\n }\n\n const requestOptions: PluginApiRequestOptions = {\n headers,\n signal: options?.signal,\n };\n\n job = await api.put<EntityImportJob>(path, chunk, requestOptions);\n offset = endExclusive;\n\n options?.onProgress?.({\n uploadedBytes: offset,\n totalBytes: source.size,\n fraction: offset / source.size,\n });\n }\n\n if (!job) {\n throw new Error(\"Import upload completed without a job response.\");\n }\n\n return job;\n}\n\nfunction blobName(source: Blob): string | undefined {\n if (typeof File !== \"undefined\" && source instanceof File) {\n return source.name;\n }\n return undefined;\n}\n\nfunction abortError(): Error {\n if (typeof DOMException !== \"undefined\") {\n return new DOMException(\"Import upload aborted.\", \"AbortError\");\n }\n return new Error(\"Import upload aborted.\");\n}\n\nfunction pageQuery(options?: EntityListOptions): string {\n const query = new URLSearchParams();\n if (options?.limit != null) {\n query.set(\"limit\", String(options.limit));\n }\n if (options?.cursor != null && String(options.cursor).trim()) {\n query.set(\"cursor\", String(options.cursor));\n }\n const encoded = query.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nfunction previewQuery(options?: EntityImportPreviewOptions): string {\n const query = new URLSearchParams();\n if (options?.offset != null) {\n query.set(\"offset\", String(options.offset));\n }\n if (options?.limit != null) {\n query.set(\"limit\", String(options.limit));\n }\n const encoded = query.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nfunction segment(value: string): string {\n const trimmed = value.trim();\n if (!trimmed) {\n throw new Error(\"Plugin entity path segment cannot be empty.\");\n }\n return encodeURIComponent(trimmed);\n}\n","import * as React from \"react\";\n\nimport { usePluginNavigation } from \"./runtime\";\n\n/**\n * Route-parameter object inferred from a Plugmatica route pattern.\n */\nexport type PluginRouteParams<TPattern extends string> = {\n [TName in RequiredRouteParamNames<TPattern>]: string;\n} & {\n [TName in OptionalRouteParamNames<TPattern>]?: string;\n};\n\ntype RouteParamTokens<TPattern extends string> =\n TPattern extends `${string}:${infer Param}/${infer Rest}`\n ? Param | RouteParamTokens<`/${Rest}`>\n : TPattern extends `${string}:${infer Param}`\n ? Param\n : never;\n\ntype RequiredRouteParamNames<TPattern extends string> =\n RouteParamTokens<TPattern> extends infer TParam extends string\n ? TParam extends `${string}?`\n ? never\n : CleanParam<TParam>\n : never;\n\ntype OptionalRouteParamNames<TPattern extends string> =\n RouteParamTokens<TPattern> extends infer TParam extends string\n ? TParam extends `${infer Name}?`\n ? Name\n : never\n : never;\n\ntype CleanParam<TParam extends string> = TParam extends `${infer Name}?`\n ? Name\n : TParam extends `${infer Name}*`\n ? Name\n : TParam;\n\n/**\n * Match a router-agnostic plugin route pattern against a path.\n *\n * Supported segments are static text, `:param`, optional trailing `:param?`\n * and trailing catch-all `:param*`. Query/hash are ignored and parameters are\n * decoded exactly once. Trailing slashes are normalised.\n *\n * @param pattern Plugmatica route pattern to match.\n * @param path Path to match; query and hash components are ignored.\n * @returns Decoded route parameters when the pattern matches; otherwise `null`.\n * @example\n * ```ts\n * const match = matchPluginRoute(\"/customers/:pid\", \"/customers/cus_123\");\n * // { pid: \"cus_123\" }\n * ```\n */\nexport function matchPluginRoute<const TPattern extends string>(\n pattern: TPattern,\n path: string,\n): PluginRouteParams<TPattern> | null {\n const patternSegments = segments(normalizePluginPattern(pattern));\n const pathSegments = segments(normalizePluginPath(path));\n const params: Record<string, string> = {};\n\n let pathIndex = 0;\n for (\n let patternIndex = 0;\n patternIndex < patternSegments.length;\n patternIndex += 1\n ) {\n const segment = patternSegments[patternIndex]!;\n\n if (!segment.startsWith(\":\")) {\n const value = pathSegments[pathIndex];\n if (value == null || decodeSegment(value) !== segment) return null;\n pathIndex += 1;\n continue;\n }\n\n const raw = segment.slice(1);\n const catchAll = raw.endsWith(\"*\");\n const optional = raw.endsWith(\"?\");\n const name = raw.replace(/[?*]$/, \"\");\n if (!name)\n throw new Error(`Invalid Plugmatica route pattern '${pattern}'.`);\n\n if (catchAll) {\n if (patternIndex !== patternSegments.length - 1) {\n throw new Error(\n `Catch-all route parameter ':${raw}' must be the final segment.`,\n );\n }\n setRouteParam(\n params,\n name,\n pathSegments.slice(pathIndex).map(decodeSegment).join(\"/\"),\n );\n pathIndex = pathSegments.length;\n break;\n }\n\n const value = pathSegments[pathIndex];\n if (value == null) {\n if (optional && patternIndex === patternSegments.length - 1) continue;\n return null;\n }\n\n setRouteParam(params, name, decodeSegment(value));\n pathIndex += 1;\n }\n\n if (pathIndex !== pathSegments.length) return null;\n return params as PluginRouteParams<TPattern>;\n}\n\n/** Current host route, with subscription when the host exposes navigation events. */\n/**\n * @returns Host-supplied path, including query and hash when provided.\n */\nexport function usePluginCurrentPath(): string {\n const navigation = usePluginNavigation();\n const subscribe = React.useCallback(\n (listener: () => void) => navigation.subscribe?.(listener) ?? noopSubscribe(),\n [navigation],\n );\n const snapshot = React.useCallback(() => navigation.currentPath(), [navigation]);\n return React.useSyncExternalStore(subscribe, snapshot, snapshot);\n}\n\n/**\n * Match a Plugmatica route pattern against the current host path.\n *\n * @param pattern Plugmatica route pattern to match.\n * @returns Decoded route parameters for the current path, or `null`.\n */\nexport function usePluginRouteMatch<const TPattern extends string>(\n pattern: TPattern,\n): PluginRouteParams<TPattern> | null {\n return matchPluginRoute(pattern, usePluginCurrentPath());\n}\n\n/** Remove query/hash, ensure a leading slash and collapse a trailing slash. */\n/**\n * @param value Input value to normalize/convert.\n * @returns Normalized leading-slash path without query/hash/trailing slash noise.\n */\nexport function normalizePluginPath(value: string): string {\n const withoutHash = value.split(\"#\", 1)[0] ?? \"\";\n const withoutQuery = withoutHash.split(\"?\", 1)[0] ?? \"\";\n const withLeadingSlash = withoutQuery.startsWith(\"/\")\n ? withoutQuery\n : `/${withoutQuery}`;\n const collapsed = withLeadingSlash.replace(/\\/{2,}/g, \"/\");\n return collapsed.length > 1 ? collapsed.replace(/\\/+$/, \"\") : \"/\";\n}\n\nfunction normalizePluginPattern(value: string): string {\n const trimmed = value.trim();\n const withLeadingSlash = trimmed.startsWith(\"/\") ? trimmed : `/${trimmed}`;\n const collapsed = withLeadingSlash.replace(/\\/{2,}/g, \"/\");\n return collapsed.length > 1 ? collapsed.replace(/\\/+$/, \"\") : \"/\";\n}\n\nfunction segments(value: string): string[] {\n return value === \"/\" ? [] : value.slice(1).split(\"/\");\n}\n\nfunction setRouteParam(\n params: Record<string, string>,\n name: string,\n value: string,\n): void {\n // Assigning to {}[\"__proto__\"] invokes Object.prototype's setter instead\n // of creating a route field. Preserve the existing plain-object API while\n // ensuring even unusual (but valid) route parameter names are addressable.\n if (name === \"__proto__\") {\n Object.defineProperty(params, name, {\n value,\n enumerable: true,\n configurable: true,\n writable: true,\n });\n } else {\n params[name] = value;\n }\n}\n\nfunction decodeSegment(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch (error) {\n throw new Error(\n `Invalid percent-encoding in plugin route segment '${value}'.`,\n {\n cause: error,\n },\n );\n }\n}\n\nfunction noopSubscribe(): () => void {\n return () => undefined;\n}\n","import type {\n ConnectionProfile,\n WorkflowGraphNode,\n WorkflowNodeAuthoringDescriptor,\n WorkflowNodeCatalogContribution,\n WorkflowNodeCatalogEntries,\n} from \"@plugmatica/core-sdk\";\nimport type { ReactNode } from \"react\";\nimport type { WorkflowNodeFields, WorkflowNodePresentationField } from \"./workflowNodeFields\";\nimport { extensionTarget } from \"./definitions\";\n\n/** Public capability, not an import from the Workflows plugin implementation. */\nexport const WORKFLOW_NODE_UI_CONTRACT = \"plugmatica.workflow.node.host\" as const;\nexport const WORKFLOW_NODE_UI_SURFACE = \"workflow.node\" as const;\n\n/**\n * Targets for optional Workflow authoring facets. The compiler discovers\n * both defineExtension() tokens and defineWorkflowNode() static declarations.\n */\nexport const workflowNodeUiTargets = {\n catalog: extensionTarget.ui({\n surface: \"custom\",\n key: WORKFLOW_NODE_UI_SURFACE,\n point: \"catalog\",\n required: false,\n contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: \"^1.1.0\" },\n }),\n editor: extensionTarget.ui({\n surface: \"custom\",\n key: WORKFLOW_NODE_UI_SURFACE,\n point: \"editor\",\n required: false,\n contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: \"^1.0.0\" },\n }),\n presentation: extensionTarget.ui({\n surface: \"custom\",\n key: WORKFLOW_NODE_UI_SURFACE,\n point: \"presentation\",\n required: false,\n contract: { id: WORKFLOW_NODE_UI_CONTRACT, version: \"^1.0.0\" },\n }),\n} as const;\n\n/** Host-mediated editor contract; all field writes pass through the Workflow host. */\nexport type WorkflowNodeEditorContext = Readonly<{\n node: WorkflowGraphNode;\n descriptor: WorkflowNodeAuthoringDescriptor;\n connections: readonly ConnectionProfile[];\n readOnly: boolean;\n /** @deprecated DX1 escape hatch; prefer fields for validated, atomic writes. */\n setConfig(config: Record<string, unknown>): void;\n fields: WorkflowNodeFields;\n /** Translation scoped to the contributing plugin, not the Workflow host. */\n translate?: (key: string) => string;\n}>;\n\nexport type WorkflowNodeEditorContribution = Readonly<{\n key: string;\n nodeType: string;\n order?: number;\n render(context: WorkflowNodeEditorContext): ReactNode;\n}>;\n\nexport type WorkflowNodePresentationContext = Readonly<{\n nodeId: string;\n nodeType: string;\n config: unknown;\n summary?: string;\n readOnly: boolean;\n /** Safe input readiness only: never contains values, formulas, BlobRefs or resource identities. */\n fields?: readonly WorkflowNodePresentationField[];\n /** Translation scoped to the contributing plugin, not the Workflow host. */\n translate?: (key: string) => string;\n}>;\n\nexport type WorkflowNodePresentationContribution = Readonly<{\n key: string;\n nodeType: string;\n order?: number;\n render(context: WorkflowNodePresentationContext): ReactNode;\n}>;\n\nexport type { WorkflowNodeCatalogContribution, WorkflowNodeCatalogEntries };\n","/**\n * Match a Workflow UI facet using the extension runtime's authoritative point.\n * The host sends node identity in the payload but the selected extension point\n * belongs to ExtensionRenderContext, not to the arbitrary payload object.\n *\n * Keep this independent of React so authoring contract checks can run without\n * a built shell or Module Federation remote.\n */\nexport type WorkflowNodeFacetPayload = Readonly<{\n nodeType?: string;\n nodeTypes?: readonly string[];\n}>;\n\nexport type WorkflowNodeFacetAvailability = Readonly<{\n catalog: boolean;\n editor: boolean;\n presentation: boolean;\n}>;\n\nexport function workflowNodeFacetAccepts(\n point: string,\n payload: WorkflowNodeFacetPayload | undefined,\n nodeType: string,\n available: WorkflowNodeFacetAvailability,\n): boolean {\n if (point === \"catalog\") {\n return available.catalog && Array.isArray(payload?.nodeTypes)\n && payload.nodeTypes.includes(nodeType);\n }\n if (payload?.nodeType !== nodeType) return false;\n if (point === \"editor\") return available.editor;\n if (point === \"presentation\") return available.presentation;\n return false;\n}\n","import {\n createElement,\n lazy,\n Suspense,\n type ComponentType,\n type ReactNode,\n} from \"react\";\nimport type { StructuredUiExtensionModule } from \"./types\";\nimport { workflowNodeFacetAccepts, type WorkflowNodeFacetPayload } from \"./workflowNodeFacet\";\nimport type {\n WorkflowNodeEditorContext,\n WorkflowNodeEditorContribution,\n WorkflowNodePresentationContext,\n WorkflowNodePresentationContribution,\n WorkflowNodeCatalogEntries,\n} from \"./workflowNodes\";\n\n/** One independently packaged, backend-owned Workflow action's optional UI facets. */\nexport type WorkflowNodeCatalogDefinition = Readonly<{\n titleKey: string;\n descriptionKey?: string;\n categoryKey?: string;\n icon?: string;\n keywords?: readonly string[];\n}>;\n\n/** Lazy components are split by Vite; palette catalog resolution never imports their chunks. */\nexport type WorkflowNodeComponentLoader<TProps> = () => Promise<{\n default: ComponentType<TProps>;\n}>;\n\nexport type WorkflowNodeDefinition = Readonly<{\n /** Must match an action in THIS plugin's compiled backend descriptor. */\n nodeType: `${string}:action:${string}`;\n /** Stable Module Federation expose for this file, e.g. ./nodes/DownloadFile. */\n module: `./${string}`;\n catalog?: WorkflowNodeCatalogDefinition;\n /** Inline component (eager) or loadEditor (code split); supply only one. */\n editor?: ComponentType<WorkflowNodeEditorContext>;\n loadEditor?: WorkflowNodeComponentLoader<WorkflowNodeEditorContext>;\n presentation?: ComponentType<WorkflowNodePresentationContext>;\n loadPresentation?: WorkflowNodeComponentLoader<WorkflowNodePresentationContext>;\n /** Explicit backend-owned editable leaf paths; checked during package assembly. */\n editableFields?: readonly string[];\n /** Optional assertion checked against the compiled backend action contract. */\n contractVersion?: number;\n order?: number;\n}>;\n\ntype WorkflowPayload = WorkflowNodeFacetPayload;\n\ntype WorkflowValue =\n | WorkflowNodeCatalogEntries\n | WorkflowNodeEditorContribution\n | WorkflowNodePresentationContribution;\n\n/**\n * Define one Workflow action's optional frontend facets without a private\n * Workflows-plugin import, global registry or executable schema duplication.\n *\n * The SDK produces an ordinary structured extension module. plugin-build\n * expands the statically declared facets into catalog/editor/presentation\n * contributions sharing this module expose. The extension runtime supplies\n * `point` through the contribution context (not through the payload).\n *\n * A single author-owned file is enough. Prefer loadEditor/loadPresentation\n * when the palette should not load rich React controls.\n *\n * @example\n * ```tsx\n * export default defineWorkflowNode({\n * nodeType: \"plugmatica.sftp:action:list-directory\",\n * module: \"./nodes/ListDirectory\",\n * catalog: { titleKey: \"workflow.list.title\", icon: \"FolderOpen\" },\n * editableFields: [\"path\"],\n * loadEditor: () => import(\"./ListDirectoryEditor\"),\n * });\n * ```\n */\nexport function defineWorkflowNode<const T extends WorkflowNodeDefinition>(\n definition: T,\n): StructuredUiExtensionModule<WorkflowValue, WorkflowPayload> {\n if (definition.editor && definition.loadEditor) {\n throw new Error(\n `Workflow node '${definition.nodeType}' cannot declare both editor and loadEditor.`,\n );\n }\n if (definition.presentation && definition.loadPresentation) {\n throw new Error(\n `Workflow node '${definition.nodeType}' cannot declare both presentation and loadPresentation.`,\n );\n }\n const editor = view(definition.editor, definition.loadEditor);\n const presentation = view(\n definition.presentation,\n definition.loadPresentation,\n );\n const key = definition.nodeType;\n const availability = {\n catalog: Boolean(definition.catalog),\n editor: Boolean(editor),\n presentation: Boolean(presentation),\n };\n const accepts = (point: string, payload: WorkflowPayload | undefined): boolean =>\n workflowNodeFacetAccepts(point, payload, key, availability);\n return {\n visible: ({ point, payload }) => accepts(point, payload),\n contribute: ({ point, payload, t }) => {\n if (!accepts(point, payload)) {\n throw new Error(\n `Workflow node '${key}' cannot contribute to '${point}'.`,\n );\n }\n switch (point) {\n case \"catalog\": {\n const catalog = definition.catalog!;\n return {\n key: `${key}.catalog`,\n nodeType: key,\n title: t(catalog.titleKey),\n ...(catalog.descriptionKey\n ? { description: t(catalog.descriptionKey) }\n : {}),\n ...(catalog.categoryKey\n ? { category: t(catalog.categoryKey) }\n : {}),\n ...(catalog.icon ? { icon: catalog.icon } : {}),\n ...(catalog.keywords ? { keywords: [...catalog.keywords] } : {}),\n };\n }\n case \"editor\":\n return {\n key: `${key}.editor`,\n nodeType: key,\n order: definition.order ?? 1000,\n render: (context: WorkflowNodeEditorContext) =>\n editor!({ ...context, translate: (messageKey) => t(messageKey) }),\n };\n case \"presentation\":\n return {\n key: `${key}.presentation`,\n nodeType: key,\n order: definition.order ?? 1000,\n render: (context: WorkflowNodePresentationContext) =>\n presentation!({\n ...context,\n translate: (messageKey) => t(messageKey),\n }),\n };\n default:\n throw new Error(\n `Workflow node '${key}' requires a supported host point.`,\n );\n }\n },\n };\n}\n\nfunction view<TProps extends object>(\n component?: ComponentType<TProps>,\n loader?: WorkflowNodeComponentLoader<TProps>,\n): ((props: TProps) => ReactNode) | undefined {\n if (component) return (props) => createElement(component, props);\n if (!loader) return undefined;\n\n const Lazy = lazy(loader);\n return (props) =>\n createElement(Suspense, { fallback: null }, createElement(Lazy, props));\n}\n","import type {\n WorkflowGraph,\n WorkflowGraphNode,\n WorkflowNodeAuthoringDescriptor,\n WorkflowNodeDescriptor,\n WorkflowValidationIssue,\n} from \"@plugmatica/core-sdk\";\n\n/** Public, serializable field/source projection supplied by the Workflow host. */\nexport type WorkflowFieldSchema = Readonly<{\n type?: string | readonly string[];\n title?: string;\n description?: string;\n default?: unknown;\n enum?: readonly unknown[];\n properties?: Record<string, WorkflowFieldSchema>;\n required?: readonly string[];\n [key: string]: unknown;\n}>;\n\nexport type WorkflowFieldSource = Readonly<{\n expression: string;\n nodeId: string;\n nodeLabel: string;\n fieldPath: string;\n fieldLabel: string;\n type?: string | readonly string[];\n description?: string;\n /** Public schema semantic, when the upstream output declares one. */\n semantic?: string;\n /** A semantic match to this target, computed by the host-owned facade. */\n recommended?: boolean;\n sourceKind: \"trigger\" | \"step\" | \"variable\" | \"config\" | \"error\";\n availability: \"always\" | \"conditional\";\n presence?: \"required\" | \"optional\";\n compatibility: \"exact\" | \"numeric_widening\" | \"unknown\" | \"incompatible\";\n}>;\n\nexport type WorkflowFieldValueMode = \"unset\" | \"fixed\" | \"source\" | \"formula\";\n/** Advisory state of an explicit source selection, never execution authorization. */\nexport type WorkflowFieldReferenceStatus =\n | \"available\" | \"conditional\" | \"optional\" | \"unverified\";\nexport type WorkflowNodeFieldState = Readonly<{\n path: string;\n label: string;\n schema: WorkflowFieldSchema;\n required: boolean;\n channel: \"input\" | \"config\";\n supportsFixed: boolean;\n supportsExpression: boolean;\n mode: WorkflowFieldValueMode;\n /** Configured means a non-empty fixed value or a non-empty mapping, not successful validation. */\n configured: boolean;\n /** A direct upstream reference may become unverified after graph rewiring.\n * Free-form expressions are not treated as broken just because the host\n * cannot catalogue every expression they contain. */\n referenceStatus?: WorkflowFieldReferenceStatus;\n value?: unknown;\n expression: string;\n sources: readonly WorkflowFieldSource[];\n issues: readonly WorkflowValidationIssue[];\n}>;\n\n/** Host-localized labels: a third-party plugin needs no Workflows translation keys. */\nexport type WorkflowFieldLabels = Readonly<{\n choose: string;\n recommended: string;\n fixed: string;\n formula: string;\n clear: string;\n search: string;\n required: string;\n optional: string;\n conditional: string;\n unverified: string;\n empty: string;\n trueLabel: string;\n falseLabel: string;\n}>;\n\nexport interface WorkflowNodeFields {\n readonly nodeId: string;\n readonly readOnly: boolean;\n readonly labels: WorkflowFieldLabels;\n /** Only authorable leaf paths are exposed; resources and sensitive fields are never listed. */\n list(): readonly WorkflowNodeFieldState[];\n /** Returns undefined rather than exposing unknown, resource or sensitive paths. */\n get(path: string): WorkflowNodeFieldState | undefined;\n /** One host-owned graph patch; switches off an existing mapping. */\n setLiteral(path: string, value: unknown): void;\n /** One host-owned graph patch; switches off a configured literal. */\n setMapping(path: string, expression: string): void;\n /** Remove both representations in one patch. */\n clear(path: string): void;\n /** Associates host validation/focus navigation with a contributed field. */\n registerAnchor(path: string, element: HTMLDivElement | null): void;\n}\n\nexport const DEFAULT_WORKFLOW_FIELD_LABELS: WorkflowFieldLabels = {\n choose: \"Choose a value\", recommended: \"Recommended matching data\", fixed: \"Fixed value\", formula: \"Formula / expression\",\n clear: \"Clear value\", search: \"Search available values\", required: \"Required\",\n optional: \"May be unavailable\", conditional: \"Available on some paths\",\n unverified: \"This saved source is not available to this step. Check the upstream node and its connection, then choose an available value.\",\n empty: \"No compatible values\", trueLabel: \"True\", falseLabel: \"False\",\n};\n\nexport type WorkflowNodeFieldHostOptions = Readonly<{\n node: WorkflowGraphNode;\n descriptor: WorkflowNodeAuthoringDescriptor;\n /** These MUST be effective, resource-pruned host projections, never plugin-supplied schemas. */\n inputSchema?: Record<string, unknown> | null;\n configSchema?: Record<string, unknown> | null;\n sources: readonly WorkflowFieldSource[];\n issues: readonly WorkflowValidationIssue[];\n readOnly: boolean;\n labels?: WorkflowFieldLabels;\n sourceCompatibility?: (targetType?: string | readonly string[], sourceType?: string | readonly string[]) => WorkflowFieldSource[\"compatibility\"];\n /** Current active node supplied by the host; stale editor callbacks are ignored. */\n currentNode(): WorkflowGraphNode | null;\n /** False once the host switches nodes, versions, or unmounts the editor. */\n isActive(): boolean;\n onChange(patch: Partial<WorkflowGraphNode>): void;\n onRegisterAnchor?: (fieldPath: string, element: HTMLDivElement | null) => void;\n}>;\n\nconst UNSAFE_SEGMENTS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst MAX_PATH_DEPTH = 12;\nconst MAX_LITERAL_BYTES = 64 * 1024;\n\nfunction immutableJson<T>(value: T): T {\n if (value === undefined || value === null || typeof value !== \"object\") return value;\n const clone = structuredClone(value);\n const visit = (item: unknown): void => {\n if (item === null || typeof item !== \"object\" || Object.isFrozen(item)) return;\n Object.freeze(item);\n for (const child of Object.values(item)) visit(child);\n };\n visit(clone);\n return clone;\n}\nfunction record(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\nfunction segments(path: string): string[] | null {\n if (typeof path !== \"string\" || path.length > 512) return null;\n const items = path.split(\".\");\n return items.length > 0 && items.length <= MAX_PATH_DEPTH &&\n items.every((item) => item.length > 0 && item.length <= 128 &&\n !UNSAFE_SEGMENTS.has(item) && !item.includes(\"[\") && !item.includes(\"]\"))\n ? items : null;\n}\nfunction forbidden(schema: Record<string, unknown>): boolean {\n return schema.readOnly === true || schema.writeOnly === true ||\n schema[\"x-sensitive\"] === true || schema[\"x-plugmatica-sensitive\"] === true ||\n schema[\"x-plugmatica-secret\"] === true || schema[\"x-plugmatica-hidden\"] === true ||\n schema[\"x-plugmatica-ui\"] === \"hidden\" ||\n (schema[\"x-plugmatica-generated\"] !== undefined && schema[\"x-plugmatica-generated\"] !== false) ||\n Object.hasOwn(schema, \"const\");\n}\nfunction fieldAt(schema: unknown, parts: readonly string[]): WorkflowFieldSchema | undefined {\n let current = record(schema) ? schema : null;\n if (!current || forbidden(current)) return undefined;\n for (const part of parts) {\n const properties: Record<string, unknown> | null = record(current.properties) ? current.properties : null;\n if (!properties || !Object.hasOwn(properties, part)) return undefined;\n const child: unknown = properties[part];\n if (!record(child) || forbidden(child)) return undefined;\n current = child;\n }\n return current as WorkflowFieldSchema;\n}\nfunction pathIsResource(path: string, descriptor: WorkflowNodeDescriptor): boolean {\n return (descriptor.resourceBindings ?? []).some((binding) =>\n path === binding.configPath || path.startsWith(`${binding.configPath}.`) ||\n binding.configPath.startsWith(`${path}.`));\n}\nfunction valueAt(root: unknown, parts: readonly string[]): unknown {\n let current: unknown = root;\n for (const part of parts) {\n if (!record(current) || !Object.hasOwn(current, part)) return undefined;\n current = current[part];\n }\n return current;\n}\n/** Structural sharing: never mutate the graph, node, config, mappings, or a sibling. */\nfunction updatedValue(root: unknown, parts: readonly string[], nextValue: unknown, remove: boolean): Record<string, unknown> {\n const before = record(root) ? root : {};\n const result = { ...before };\n const part = parts[0];\n if (parts.length === 1) {\n if (remove) delete result[part]; else result[part] = nextValue;\n } else {\n const child = updatedValue(before[part], parts.slice(1), nextValue, remove);\n if (remove && !Object.keys(child).length) delete result[part];\n else result[part] = child;\n }\n return result;\n}\nfunction literalExpression(expression: string): { value: unknown } | null {\n try {\n const parsed: unknown = JSON.parse(expression);\n if (parsed === null || typeof parsed === \"string\" ||\n typeof parsed === \"boolean\" || (typeof parsed === \"number\" && Number.isFinite(parsed))) {\n return { value: parsed };\n }\n } catch { /* Formula or incomplete expression. */ }\n return null;\n}\nfunction supportsFixed(schema: WorkflowFieldSchema, canUseConfig: boolean): boolean {\n if (canUseConfig) return true;\n const types = Array.isArray(schema.type) ? schema.type : [schema.type];\n return types.every((type) => type === undefined || [\"string\", \"number\", \"integer\", \"boolean\", \"null\"].includes(type));\n}\nfunction typeSupportsValue(schema: WorkflowFieldSchema, value: unknown): boolean {\n const types = Array.isArray(schema.type) ? schema.type : schema.type ? [schema.type] : [];\n if (!types.length) return true;\n return types.some((type) => type === \"null\" && value === null ||\n type === \"string\" && typeof value === \"string\" ||\n type === \"boolean\" && typeof value === \"boolean\" ||\n type === \"number\" && typeof value === \"number\" && Number.isFinite(value) ||\n type === \"integer\" && typeof value === \"number\" && Number.isSafeInteger(value) ||\n type === \"object\" && record(value) || type === \"array\" && Array.isArray(value));\n}\nfunction sameValue(a: unknown, b: unknown): boolean {\n return a === b || JSON.stringify(a) === JSON.stringify(b);\n}\n/** A required empty string must not look configured just because it has a fixed mode. */\nexport function workflowFieldHasValue(value: unknown): boolean {\n if (value === undefined || value === null) return false;\n if (typeof value === \"string\") return value.trim().length > 0;\n if (Array.isArray(value)) return value.length > 0;\n return true;\n}\n\nfunction normalizedSemantic(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length > 256) return undefined;\n const trimmed = value.trim().toLowerCase();\n return trimmed || undefined;\n}\n\n/**\n * Semantic matching is generic and opt-in. Two explicitly different identities\n * cannot be substituted, even if both JSON properties happen to be strings.\n * Untagged sources remain selectable for explicit formulas or imported values,\n * but are not promoted as recommended matches.\n */\nfunction sourceSemanticRank(target: unknown, source: unknown): 0 | 1 | 2 {\n const requested = normalizedSemantic(target);\n const offered = normalizedSemantic(source);\n if (!requested || !offered) return 1;\n return requested === offered ? 0 : 2;\n}\n/** A bare Workflow data path, not a function call or expression fragment.\n * An uncatalogued direct path is advisory-only: the backend remains the\n * authority for whether a dynamic JSON path is executable. */\nfunction isDirectWorkflowDataPath(expression: string): boolean {\n return /^\\$\\.(?:trigger|nodes|steps|variables|config)(?:\\.[A-Za-z0-9_-]+)*$/.test(expression);\n}\n\nfunction visiblePaths(schema: unknown, prefix = \"\", depth = 0): string[] {\n if (depth >= MAX_PATH_DEPTH || !record(schema) || forbidden(schema)) return [];\n const properties = record(schema.properties) ? schema.properties : null;\n if (!properties) return [];\n const result: string[] = [];\n for (const [key, field] of Object.entries(properties)) {\n const path = prefix ? `${prefix}.${key}` : key;\n if (!segments(path) || !record(field) || forbidden(field)) continue;\n const descendants = visiblePaths(field, path, depth + 1);\n if (descendants.length) result.push(...descendants);\n else if (!record(field.properties) || !Object.keys(field.properties).length) result.push(path);\n }\n return result;\n}\n\n/**\n * Constructs a typed, constrained editor facade. The host owns the callback and\n * projections. This helper never evaluates workflow expressions, creates secrets,\n * chooses Connections, or writes to the graph merely because it was rendered.\n */\nexport function createWorkflowNodeFields(options: WorkflowNodeFieldHostOptions): WorkflowNodeFields {\n const { node, descriptor, inputSchema, configSchema, sources, issues, readOnly, onChange } = options;\n const inputDefaults = configSchema?.[\"x-plugmatica-input-defaults\"] === true;\n const paths = new Map<string, { channel: \"input\" | \"config\"; schema: WorkflowFieldSchema; required: boolean }>();\n for (const [channel, schema] of [[\"config\", configSchema], [\"input\", inputSchema]] as const) {\n const source = record(schema) ? schema : null;\n for (const path of visiblePaths(source)) {\n if (pathIsResource(path, descriptor)) continue;\n const parts = segments(path);\n const field = parts && fieldAt(source, parts);\n if (!field) continue;\n let required = true;\n let parent: Record<string, unknown> = source!;\n for (const part of parts!) {\n required &&= Array.isArray(parent.required) && parent.required.includes(part);\n parent = record(parent.properties) && record(parent.properties[part]) ? parent.properties[part] as Record<string, unknown> : {};\n }\n paths.set(path, { channel, schema: immutableJson(field), required });\n }\n }\n // Input fields take priority over config fields with the same path, so their\n // fixed/mapped modes remain consistent with the backend input binding contract.\n function definition(path: string) {\n return segments(path) ? paths.get(path) : undefined;\n }\n function snapshot(path: string): WorkflowNodeFieldState | undefined {\n const def = definition(path);\n if (!def) return undefined;\n const parts = segments(path)!;\n const current = options.currentNode();\n // A component may render the last snapshot briefly while the host switches.\n const activeNode = current?.id === node.id && current?.type === node.type ? current : node;\n const mappings = activeNode.inputMappings ?? {};\n const expression = def.channel === \"input\" ? mappings[path]?.expression ?? \"\" : \"\";\n const configured = valueAt(activeNode.config, parts);\n const literal = literalExpression(expression);\n const requestedSemantic = def.schema[\"x-plugmatica-semantic\"];\n const allowedSources = def.channel === \"input\" ? sources.map((candidate) => {\n const semanticRank = sourceSemanticRank(requestedSemantic, candidate.semantic);\n return {\n ...candidate,\n // Conditional branches and optional array/field members are visible,\n // but must never be advertised as a guaranteed one-click match.\n recommended: semanticRank === 0 && candidate.availability === \"always\" && candidate.presence !== \"optional\",\n // Never suggest an explicitly different semantic just because both\n // fields share a broad JSON type such as \"string\".\n compatibility: semanticRank === 2 ? \"incompatible\" as const :\n options.sourceCompatibility?.(def.schema.type, candidate.type) ?? candidate.compatibility,\n };\n }).filter((candidate) => candidate.compatibility !== \"incompatible\")\n .sort((a, b) => Number(b.recommended) - Number(a.recommended)) : [];\n const selectedSource = allowedSources.find((candidate) => candidate.expression === expression.trim());\n const selected = selectedSource !== undefined;\n const useConfigLiteral = def.channel === \"config\" || inputDefaults;\n const mode: WorkflowFieldValueMode = expression.trim()\n ? selected ? \"source\" : literal ? \"fixed\" : \"formula\"\n : useConfigLiteral && configured !== undefined ? \"fixed\" : \"unset\";\n const value = mode === \"fixed\" ? immutableJson(expression.trim() ? literal?.value : configured) : undefined;\n const referenceStatus: WorkflowFieldReferenceStatus | undefined = selectedSource\n ? selectedSource.availability === \"conditional\" ? \"conditional\"\n : selectedSource.presence === \"optional\" ? \"optional\" : \"available\"\n : mode === \"formula\" && isDirectWorkflowDataPath(expression.trim())\n ? \"unverified\" : undefined;\n const fieldIssues = issues.filter((issue) => issue.field === `config.${path}` ||\n issue.field === `inputMappings.${path}`).map((issue) => immutableJson(issue));\n return {\n path, schema: def.schema,\n label: typeof def.schema.title === \"string\" && def.schema.title.trim() ? def.schema.title.trim() : path,\n required: def.required, channel: def.channel,\n supportsFixed: supportsFixed(def.schema, useConfigLiteral),\n supportsExpression: def.channel === \"input\",\n mode, configured: mode === \"fixed\" ? workflowFieldHasValue(value)\n : mode !== \"unset\" && referenceStatus !== \"unverified\",\n referenceStatus, value, expression, sources: allowedSources.map((source) => immutableJson(source)), issues: fieldIssues,\n };\n }\n function commit(path: string, mode: \"literal\" | \"mapping\" | \"clear\", value?: unknown): void {\n const def = definition(path);\n if (!def) throw new Error(`Workflow field '${path}' is not an editable input or configuration path`);\n if (readOnly || !options.isActive()) return;\n const current = options.currentNode();\n if (!current || current.id !== node.id || current.type !== node.type) return;\n const parts = segments(path)!;\n const configured = valueAt(current.config, parts);\n const mappings = current.inputMappings ?? {};\n const oldExpression = mappings[path]?.expression;\n const nextMappings = { ...mappings };\n let configChanged = false;\n let mappingsChanged = false;\n let nextConfig: Record<string, unknown> | undefined;\n if (mode === \"literal\") {\n if (!supportsFixed(def.schema, def.channel === \"config\" || inputDefaults)) {\n throw new Error(`Workflow field '${path}' does not allow fixed values`);\n }\n if (!typeSupportsValue(def.schema, value)) throw new Error(`Invalid value type for Workflow field '${path}'`);\n let encoded: string;\n try {\n encoded = JSON.stringify(value);\n if (typeof encoded !== \"string\" || encoded.length > MAX_LITERAL_BYTES) throw new Error(\"invalid\");\n } catch { throw new Error(`Workflow field '${path}' requires a bounded JSON value`); }\n if (def.channel === \"config\" || inputDefaults) {\n if (!sameValue(configured, value)) {\n nextConfig = updatedValue(current.config, parts, JSON.parse(encoded) as unknown, false);\n configChanged = true;\n }\n } else {\n if (configured !== undefined) {\n nextConfig = updatedValue(current.config, parts, undefined, true);\n configChanged = true;\n }\n if (oldExpression !== encoded) { nextMappings[path] = { expression: encoded }; mappingsChanged = true; }\n }\n if ((def.channel === \"config\" || inputDefaults) && oldExpression !== undefined) {\n delete nextMappings[path]; mappingsChanged = true;\n }\n } else {\n if (mode === \"mapping\") {\n if (def.channel !== \"input\") throw new Error(`Workflow config field '${path}' cannot be mapped`);\n if (typeof value !== \"string\" || value.length > 32_768) throw new Error(\"Invalid Workflow expression\");\n const expression = value.trim();\n if (expression) {\n const source = sources.find((candidate) => candidate.expression === expression);\n if (source && (sourceSemanticRank(def.schema[\"x-plugmatica-semantic\"], source.semantic) === 2 ||\n (options.sourceCompatibility?.(def.schema.type, source.type) ?? source.compatibility) === \"incompatible\")) {\n throw new Error(`Incompatible Workflow mapping source for '${path}'`);\n }\n if (oldExpression !== value) { nextMappings[path] = { expression: value }; mappingsChanged = true; }\n } else if (oldExpression !== undefined) { delete nextMappings[path]; mappingsChanged = true; }\n } else if (oldExpression !== undefined) { delete nextMappings[path]; mappingsChanged = true; }\n if (configured !== undefined && (mode === \"clear\" || def.channel === \"input\")) {\n nextConfig = updatedValue(current.config, parts, undefined, true);\n configChanged = true;\n }\n }\n if (!configChanged && !mappingsChanged) return;\n onChange({ ...(configChanged ? { config: nextConfig } : {}), ...(mappingsChanged ? { inputMappings: nextMappings } : {}) });\n }\n return {\n nodeId: node.id, readOnly, labels: options.labels ?? DEFAULT_WORKFLOW_FIELD_LABELS,\n list: () => [...paths.keys()].map(snapshot).filter((item): item is WorkflowNodeFieldState => item !== undefined),\n get: snapshot,\n setLiteral: (path, value) => commit(path, \"literal\", value),\n setMapping: (path, expression) => commit(path, \"mapping\", expression),\n clear: (path) => commit(path, \"clear\"),\n registerAnchor(path, element) {\n const def = definition(path);\n if (!def) return;\n if (def.channel === \"input\") {\n options.onRegisterAnchor?.(`inputMappings.${path}`, element);\n if (inputDefaults) options.onRegisterAnchor?.(`config.${path}`, element);\n } else {\n options.onRegisterAnchor?.(`config.${path}`, element);\n }\n },\n };\n}\n\n/** Pure read helper for plugin React components (updates flow through host context renders). */\nexport function useWorkflowNodeField(fields: WorkflowNodeFields, path: string) {\n return fields.get(path);\n}\n\n/**\n * Read-only, privacy-limited canvas projection. It is intentionally not a field\n * controller: no values, expressions, Connection identifiers, or credentials\n * cross this surface. In particular, a mapped BlobRef is never disclosed.\n */\nexport type WorkflowNodePresentationField = Readonly<{\n path: string;\n required: boolean;\n mode: \"unset\" | \"fixed\" | \"mapped\";\n /** No literal, expression, or managed-resource value is disclosed by this status. */\n configured: boolean;\n}>;\n\nconst MAX_PRESENTATION_FIELDS = 24;\n\n/**\n * Upstream reachability for privacy-safe canvas readiness. A node that is\n * present in the graph but no longer connected is not a usable data source.\n * This is advisory only; runtime validation still decides expression semantics.\n */\nexport function workflowUpstreamNodeIds(\n graph: Pick<WorkflowGraph, \"edges\" | \"nodes\">,\n nodeId: string,\n): ReadonlySet<string> {\n const parents = new Map<string, string[]>();\n const validIds = new Set(graph.nodes.map((node) => node.id));\n for (const edge of graph.edges) {\n if (!validIds.has(edge.source) || !validIds.has(edge.target)) continue;\n if (!parents.has(edge.target)) parents.set(edge.target, []);\n parents.get(edge.target)!.push(edge.source);\n }\n const result = new Set<string>();\n const queue = [...(parents.get(nodeId) ?? [])];\n for (let index = 0; index < queue.length; index += 1) {\n const candidate = queue[index];\n if (candidate === nodeId || result.has(candidate)) continue;\n result.add(candidate);\n queue.push(...(parents.get(candidate) ?? []));\n }\n return result;\n}\n\nfunction directWorkflowNodeSource(expression: string): string | undefined {\n return /^\\$\\.nodes\\.([A-Za-z0-9_-]+)\\.(?:output|error)(?:\\.[A-Za-z0-9_-]+)*$/\n .exec(expression)?.[1];\n}\n\nexport function projectWorkflowNodePresentationFields(\n node: WorkflowGraphNode,\n descriptor: WorkflowNodeDescriptor,\n /** Optional graph-derived predecessor IDs. Never exposed in the projection. */\n upstreamNodeIds?: ReadonlySet<string>,\n): readonly WorkflowNodePresentationField[] {\n const schema = record(descriptor.inputSchema) ? descriptor.inputSchema : null;\n if (!schema) return [];\n const inputDefaults = descriptor.configSchema?.[\"x-plugmatica-input-defaults\"] === true;\n const mappings = node.inputMappings ?? {};\n const fields: WorkflowNodePresentationField[] = [];\n for (const path of visiblePaths(schema)) {\n if (fields.length >= MAX_PRESENTATION_FIELDS) break;\n if (pathIsResource(path, descriptor)) continue;\n const parts = segments(path);\n const field = parts ? fieldAt(schema, parts) : undefined;\n if (!parts || !field) continue;\n let required = true;\n let current: Record<string, unknown> = schema;\n for (const part of parts) {\n required &&= Array.isArray(current.required) && current.required.includes(part);\n current = record(current.properties) && record(current.properties[part])\n ? current.properties[part] as Record<string, unknown> : {};\n }\n const expression = mappings[path]?.expression;\n const trimmed = typeof expression === \"string\" ? expression.trim() : \"\";\n const literal = trimmed ? literalExpression(trimmed) : null;\n const configuredLiteral = valueAt(node.config, parts);\n const mode: WorkflowNodePresentationField[\"mode\"] = trimmed\n ? literal ? \"fixed\" : \"mapped\"\n : inputDefaults && configuredLiteral !== undefined ? \"fixed\" : \"unset\";\n const referencedNodeId = trimmed ? directWorkflowNodeSource(trimmed) : undefined;\n const unreachable = upstreamNodeIds !== undefined && referencedNodeId !== undefined &&\n !upstreamNodeIds.has(referencedNodeId);\n const configured = !unreachable && (mode === \"mapped\" || mode === \"fixed\" &&\n workflowFieldHasValue(trimmed ? literal?.value : configuredLiteral));\n fields.push(Object.freeze({ path, required, mode, configured }));\n }\n return Object.freeze(fields);\n}\n"]}
|