@uipath/maestro-builder-sdk 6.117.4 → 6.118.1

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.
@@ -0,0 +1,560 @@
1
+ /**
2
+ * The Extract document node's IDP processor (builder-sdk#1984): the identity a
3
+ * node runs through, the solution resource file that stores the processor, and
4
+ * the `bindings_v2.json` row that declares it.
5
+ *
6
+ * Short version: the node does not run a deployed model. Its extraction settings
7
+ * (the taxonomy in `inputs.schemaDocument` and `inputs.modelConfig`) are copied
8
+ * into an `idpProcessor` solution resource, and the node names that resource by
9
+ * `inputs.processorKey`. `uip maestro flow nodes create` mints the key and writes
10
+ * the resource file; `uip solution pack` rewrites the file from the node and
11
+ * refuses a node with no key. This module is the SDK's copy of those rules, so
12
+ * compile can leave a node in the state `nodes create` leaves it.
13
+ *
14
+ * For instance, a node `extract` labelled "Extract invoice" in a solution gets
15
+ *
16
+ * ```json
17
+ * "inputs": { "processorKey": "<uuid>", "processorName": "Extract invoice", … }
18
+ * ```
19
+ *
20
+ * and the solution gets
21
+ * `resources/solution_folder/idpProcessor/extraction/Extract_invoice.json`.
22
+ *
23
+ * Every function here is a copy, kept byte-for-byte in behaviour, of the CLI's
24
+ * code or of `@uipath/flow-schema/idp-packaging`, which the CLI and Studio Web
25
+ * both run, with ONE deliberate exception: {@link updateIdpProcessorResource}
26
+ * clears the optional spec keys the node no longer sets
27
+ * (`MANAGED_OPTIONAL_SPEC_KEYS`), where the CLI's merge keeps them. Keep that
28
+ * on an upstream sync. The SDK cannot import either (FB016), so
29
+ * `tests/idp-processor-contract.test.ts` runs the real `idp-packaging` against
30
+ * these copies. The sources, by function:
31
+ *
32
+ * - {@link buildIdpProcessorSpec} and its helpers: flow-schema
33
+ * `idp-packaging/idp-processor-spec.ts`, `build-extraction-json.ts`,
34
+ * `build-extraction-config.ts`, `build-api-extraction-config.ts`,
35
+ * `build-output-schema.ts`, `field-schema.ts`, `extraction-schema.ts`,
36
+ * `normalize-extraction-schema.ts`;
37
+ * - {@link deriveIdpProcessorName}: `idp-processor-naming.ts`;
38
+ * - {@link idpProcessorBindingRows}: `processor-bindings.ts` and the
39
+ * `idpProcessor` branch of `packaging/packaging.ts` (`getBindingResources`);
40
+ * - {@link wrapIdpProcessorSpec}, {@link updateIdpProcessorResource},
41
+ * {@link idpProcessorResourcePath}: uipath-cli
42
+ * `packager-tool-flow/src/idp-processor/resource-file.ts`;
43
+ * - {@link buildDefaultSchemaDocument}: uipath-cli
44
+ * `flow-tool/src/services/extract-schema/default-schema-document.ts`.
45
+ *
46
+ * Pure: no file access (the flow core is portable, FB015). `idp-processor-files.ts`
47
+ * reads and writes the resource files for `compile`.
48
+ */
49
+ import { ownEntry } from '../../../core/own-entry.js';
50
+ /** The node type this module serves, as the family registers it. */
51
+ export const DYNAMIC_EXTRACT_TYPE = 'uipath.ixp.extract-document-builder';
52
+ /** Node inputs that name the processor (flow-schema `idp-processor-spec.ts`). */
53
+ export const PROCESSOR_KEY_INPUT = 'processorKey';
54
+ export const PROCESSOR_NAME_INPUT = 'processorName';
55
+ export const PROCESSOR_READONLY_INPUT = 'processorReadOnly';
56
+ export const PROCESSOR_FOLDER_PATH_INPUT = 'processorFolderPath';
57
+ /** The processor name a node with no label gets (the CLI's `DEFAULT_IDP_PROCESSOR_NAME`). */
58
+ export const DEFAULT_IDP_PROCESSOR_NAME = 'IdpProcessor';
59
+ const IDP_PROCESSOR_RESOURCE_KIND = 'idpProcessor';
60
+ const IDP_PROCESSOR_RESOURCE_TYPE = 'Extraction';
61
+ const SOLUTION_FOLDER = 'solution_folder';
62
+ const IDP_PROCESSOR_RESOURCE_API_VERSION = 'ecs.uipath.com/v2';
63
+ const IDP_PROCESSOR_RESOURCE_DOC_VERSION = '1.0.0';
64
+ const IDP_PROCESSOR_DESCRIPTION_MAX_LENGTH = 1024;
65
+ function isPlainObject(value) {
66
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
67
+ }
68
+ /** flow-schema `utils.asRecord`: a plain object, else undefined. */
69
+ function asRecord(value) {
70
+ return isPlainObject(value) ? value : undefined;
71
+ }
72
+ /** flow-schema `node-inputs.ts`'s own `asRecord`: any object, arrays included. */
73
+ function asObject(value) {
74
+ return typeof value === 'object' && value !== null ? value : undefined;
75
+ }
76
+ /** Every node of a `.flow`, subflow bodies included (flow-schema `collectWorkflowNodes`). */
77
+ export function collectWorkflowNodes(workflow) {
78
+ const nodes = [];
79
+ if (Array.isArray(workflow?.nodes))
80
+ nodes.push(...workflow.nodes);
81
+ if (workflow?.subflows && typeof workflow.subflows === 'object') {
82
+ for (const entry of Object.values(workflow.subflows)) {
83
+ if (Array.isArray(entry?.nodes))
84
+ nodes.push(...entry.nodes);
85
+ }
86
+ }
87
+ return nodes;
88
+ }
89
+ export function isDynamicExtractNode(node) {
90
+ return node?.type === DYNAMIC_EXTRACT_TYPE;
91
+ }
92
+ export function readIdpProcessorKey(inputs) {
93
+ const key = asObject(inputs)?.[PROCESSOR_KEY_INPUT];
94
+ return typeof key === 'string' && key.length > 0 ? key : undefined;
95
+ }
96
+ export function readIdpProcessorName(inputs) {
97
+ const name = asObject(inputs)?.[PROCESSOR_NAME_INPUT];
98
+ return typeof name === 'string' && name.trim().length > 0 ? name : undefined;
99
+ }
100
+ export function readIdpProcessorFolderPath(inputs) {
101
+ const path = asObject(inputs)?.[PROCESSOR_FOLDER_PATH_INPUT];
102
+ return typeof path === 'string' && path.trim().length > 0 ? path : undefined;
103
+ }
104
+ export function isIdpProcessorReadOnly(inputs) {
105
+ return asObject(inputs)?.[PROCESSOR_READONLY_INPUT] === true;
106
+ }
107
+ /** The processor this node writes to: none for a read-only mirror (flow-schema `readAuthoringProcessorKey`). */
108
+ export function readAuthoringProcessorKey(node) {
109
+ if (!isDynamicExtractNode(node))
110
+ return undefined;
111
+ if (isIdpProcessorReadOnly(node.inputs))
112
+ return undefined;
113
+ return readIdpProcessorKey(node.inputs);
114
+ }
115
+ /** A processor published to the tenant: the key comes with the folder it lives in, and no solution resource exists. */
116
+ export function isPublishedIdpProcessorLink(inputs) {
117
+ return readIdpProcessorKey(inputs) !== undefined && readIdpProcessorFolderPath(inputs) !== undefined;
118
+ }
119
+ /** The node's `display.label` (else a top-level `label`), the name a new processor takes. */
120
+ export function readNodeLabel(node) {
121
+ const direct = node?.label;
122
+ if (typeof direct === 'string' && direct.trim().length > 0)
123
+ return direct;
124
+ const label = asObject(node?.display)?.label;
125
+ return typeof label === 'string' && label.trim().length > 0 ? label : undefined;
126
+ }
127
+ /** `display.subLabel`, which the processor's read-only description mirrors; `''` when absent. */
128
+ function readNodeDescription(node) {
129
+ const description = asObject(node?.display)?.subLabel;
130
+ return typeof description === 'string' ? description : '';
131
+ }
132
+ const ATTRIBUTION_TO_API_STRATEGY = { word_ids: 'WordId', table_heuristic: 'TableHeuristic' };
133
+ const EXECUTION_MODE_TO_API_STRATEGY = {
134
+ standard: 'SingleExtract',
135
+ advanced_harness: 'DynamicExtract',
136
+ agentic: 'Agentic',
137
+ };
138
+ const MODEL_VERSION_TO_LLM_GATEWAY_ID = {
139
+ gpt_4o_2024_05_13: 'gpt-4o-2024-08-06',
140
+ gpt_5_1_2025_11_13: 'gpt-5.1-2025-11-13',
141
+ gpt_5_4_2026_03_05: 'gpt-5.4-2026-03-05',
142
+ gemini_2_5_flash: 'gemini-2.5-flash',
143
+ gemini_2_5_pro: 'gemini-2.5-pro',
144
+ gemini_3_1_pro_preview: 'gemini-3.1-pro-preview',
145
+ gemini_3_1_flash_lite_preview: 'gemini-3.1-flash-lite',
146
+ };
147
+ const LANGUAGE_SUPPORT_TO_API = { auto: 'Auto', latin: 'UiPath', extended: 'UiPathExtended' };
148
+ const LEGACY_PREPROCESSING = {
149
+ none: { languageSupport: 'latin', layoutParsing: 'none' },
150
+ table_model: { languageSupport: 'latin', layoutParsing: 'tables_forms' },
151
+ table_model_mini: { languageSupport: 'latin', layoutParsing: 'tables_forms' },
152
+ azure_table_formatting: { languageSupport: 'latin', layoutParsing: 'full' },
153
+ azure_markdown: { languageSupport: 'extended', layoutParsing: 'full' },
154
+ };
155
+ function toApiExtractionStrategy(executionMode) {
156
+ return (executionMode && ownEntry(EXECUTION_MODE_TO_API_STRATEGY, executionMode)) || 'SingleExtract';
157
+ }
158
+ function toGatewayModelId(version) {
159
+ return ownEntry(MODEL_VERSION_TO_LLM_GATEWAY_ID, version) ?? version;
160
+ }
161
+ function tryLlmGatewayModelId(version) {
162
+ if (!version)
163
+ return undefined;
164
+ const mapped = ownEntry(MODEL_VERSION_TO_LLM_GATEWAY_ID, version);
165
+ if (mapped)
166
+ return mapped;
167
+ return version.toLowerCase().startsWith('helix') ? undefined : version;
168
+ }
169
+ function resolveApiAttributionStrategy(attribution, executionMode) {
170
+ const member = attribution ? ownEntry(ATTRIBUTION_TO_API_STRATEGY, attribution) : undefined;
171
+ if (member === 'TableHeuristic' && toApiExtractionStrategy(executionMode) !== 'SingleExtract')
172
+ return 'WordId';
173
+ return member;
174
+ }
175
+ function readPreprocessing(mc) {
176
+ if (mc.language_support === undefined && mc.layout_parsing === undefined) {
177
+ const projected = mc.input_config === undefined ? undefined : ownEntry(LEGACY_PREPROCESSING, mc.input_config);
178
+ return projected ?? { languageSupport: 'latin', layoutParsing: 'none' };
179
+ }
180
+ return { languageSupport: mc.language_support ?? 'latin', layoutParsing: mc.layout_parsing ?? 'none' };
181
+ }
182
+ const trimmedOrNull = (value) => {
183
+ const trimmed = typeof value === 'string' ? value.trim() : '';
184
+ return trimmed === '' ? null : trimmed;
185
+ };
186
+ /** The `config` block derived from `inputs.modelConfig` (flow-schema `buildExtractionConfig`), minus the prompt it composes, which no spec field reads. */
187
+ function buildExtractionConfig(modelConfig) {
188
+ const mc = modelConfig ?? {};
189
+ const { languageSupport, layoutParsing } = readPreprocessing(mc);
190
+ const layoutEngine = layoutParsing === 'none' ? null : trimmedOrNull(mc.layout_engine);
191
+ const layoutModel = trimmedOrNull(mc.layout_model_version);
192
+ const attribution = mc.attribution_method ?? 'word_ids';
193
+ const executionMode = mc.execution_mode ?? 'standard';
194
+ const attributionModel = trimmedOrNull(mc.attribution_model_version);
195
+ return {
196
+ model: mc.model_version ? { family: mc.model_version.split(/[-_]/)[0], version: mc.model_version } : null,
197
+ execution_mode: executionMode,
198
+ attribution,
199
+ language_support: languageSupport,
200
+ layout_engine: layoutEngine,
201
+ layout_model: layoutParsing === 'full' && layoutEngine !== null && layoutModel !== null ? toGatewayModelId(layoutModel) : null,
202
+ attribution_model: attributionModel !== null && resolveApiAttributionStrategy(attribution, executionMode) === 'WordId'
203
+ ? toGatewayModelId(attributionModel)
204
+ : null,
205
+ overrides: trimmedOrNull(mc.experimentalSettings),
206
+ };
207
+ }
208
+ /** Schema Editor's public document: `{ config, prompt, outputSchema }`. */
209
+ function isExtractionSchema(value) {
210
+ const schema = asRecord(value);
211
+ return asRecord(schema?.config) !== undefined && typeof schema?.prompt === 'string' && asRecord(schema?.outputSchema) !== undefined;
212
+ }
213
+ // A pre-v3 monetary field holds an `{ amount, currency }` object; v3 is one string.
214
+ const MONETARY_OBJECT_KEYWORDS = ['properties', 'required', 'additionalProperties'];
215
+ function normalizeNode(node) {
216
+ if (Array.isArray(node))
217
+ return node.map(normalizeNode);
218
+ if (!isPlainObject(node))
219
+ return node;
220
+ if (node.format === 'monetary' && (Array.isArray(node.type) ? node.type : [node.type]).some((t) => t === 'object')) {
221
+ const kept = Object.fromEntries(Object.entries(node).filter(([key]) => !MONETARY_OBJECT_KEYWORDS.includes(key) && key !== 'type'));
222
+ return { ...kept, type: ['string', 'null'], format: 'monetary' };
223
+ }
224
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, normalizeNode(value)]));
225
+ }
226
+ /** The node's `schemaDocument` as packaging reads it (flow-schema `readExtractionSchema`). */
227
+ function readExtractionSchema(inputs) {
228
+ const document = asRecord(inputs)?.schemaDocument;
229
+ if (isExtractionSchema(document)) {
230
+ const normalized = normalizeNode(document);
231
+ return JSON.stringify(normalized) === JSON.stringify(document) ? document : normalized;
232
+ }
233
+ return asRecord(document);
234
+ }
235
+ function buildFieldValueSchema(kind, choices) {
236
+ switch (kind) {
237
+ case 'Exact Text': return { type: ['string', 'null'], format: 'verbatim' };
238
+ case 'Inferred Text': return { type: ['string', 'null'] };
239
+ case 'Date': return { type: ['string', 'null'], format: 'timestamp' };
240
+ case 'Number': return { type: ['string', 'null'], format: 'decimal' };
241
+ case 'Boolean': return { type: ['boolean', 'null'] };
242
+ case 'Monetary Quantity': return { type: ['string', 'null'], format: 'monetary' };
243
+ case 'Choice': {
244
+ const usable = (choices ?? []).filter((choice) => choice.name.length > 0);
245
+ if (usable.length === 0)
246
+ return { type: ['string', 'null'] };
247
+ const synonyms = Object.fromEntries(usable.flatMap((choice) => {
248
+ const aliases = (choice.values ?? '').split(',').map((a) => a.trim()).filter((a) => a.length > 0);
249
+ return aliases.length === 0 ? [] : [[choice.name, aliases]];
250
+ }));
251
+ return { type: ['string', 'null'], enum: usable.map((c) => c.name), ...(Object.keys(synonyms).length === 0 ? {} : { synonyms }) };
252
+ }
253
+ default: return { type: ['string', 'null'] };
254
+ }
255
+ }
256
+ const groupName = (group) => (group.ownName ?? group.name ?? '').trim();
257
+ function groupOutputName(group, byId) {
258
+ const path = [group];
259
+ const seen = new Set(group.id ? [group.id] : []);
260
+ let parentId = group.parentId;
261
+ while (parentId) {
262
+ if (seen.has(parentId))
263
+ return groupName(group);
264
+ seen.add(parentId);
265
+ const parent = byId.get(parentId);
266
+ if (!parent)
267
+ break;
268
+ path.unshift(parent);
269
+ parentId = parent.parentId;
270
+ }
271
+ const names = path.map(groupName);
272
+ if (!names[names.length - 1])
273
+ return '';
274
+ return names.filter(Boolean).join(' > ');
275
+ }
276
+ function buildLegacyOutputSchema(doc) {
277
+ const taxonomy = asObject(doc?.taxonomy);
278
+ const groups = taxonomy?.fieldGroups ?? [];
279
+ if (groups.length === 0)
280
+ return { type: 'object', additionalProperties: false, required: [], properties: {} };
281
+ const typeIndex = new Map();
282
+ for (const ft of doc?.fieldTypes ?? [])
283
+ if (ft.id)
284
+ typeIndex.set(ft.id, ft);
285
+ const definitions = new Map();
286
+ const keyByTypeId = new Map();
287
+ const register = (ft) => {
288
+ const id = (ft.id ?? '').trim();
289
+ const name = (ft.name ?? '').trim();
290
+ if (!id || !name)
291
+ return undefined;
292
+ const existing = keyByTypeId.get(id);
293
+ if (existing)
294
+ return existing;
295
+ let key = name;
296
+ for (let suffix = 2; definitions.has(key); suffix++)
297
+ key = `${name} (${suffix})`;
298
+ const value = buildFieldValueSchema(ft.kind, ft.choices);
299
+ const instructions = (ft.instructions ?? '').trim();
300
+ definitions.set(key, instructions ? { ...value, description: instructions } : value);
301
+ keyByTypeId.set(id, key);
302
+ return key;
303
+ };
304
+ const pointer = (v) => encodeURIComponent(v.replaceAll('~', '~0').replaceAll('/', '~1'));
305
+ const byId = new Map(groups.flatMap((g) => (g.id ? [[g.id, g]] : [])));
306
+ const properties = {};
307
+ const required = [];
308
+ for (const group of groups) {
309
+ const name = groupOutputName(group, byId);
310
+ if (!name || name in properties)
311
+ continue;
312
+ const fieldProps = {};
313
+ const fieldReq = [];
314
+ for (const field of group.fields ?? []) {
315
+ const fname = (field.name ?? '').trim();
316
+ if (!fname || fname in fieldProps)
317
+ continue;
318
+ const ft = field.fieldTypeId ? typeIndex.get(field.fieldTypeId) : undefined;
319
+ const description = (field.instructions ?? '').trim() || undefined;
320
+ const defKey = ft ? register(ft) : undefined;
321
+ if (defKey) {
322
+ fieldProps[fname] = { $ref: `#/$defs/${pointer(defKey)}`, ...(description ? { description } : {}) };
323
+ }
324
+ else {
325
+ const value = buildFieldValueSchema(ft?.kind ?? field.kind, ft?.choices);
326
+ fieldProps[fname] = description ? { ...value, description } : value;
327
+ }
328
+ fieldReq.push(fname);
329
+ }
330
+ const instructions = (group.instructions ?? '').trim();
331
+ properties[name] = {
332
+ type: 'array',
333
+ ...(instructions ? { description: instructions } : {}),
334
+ items: { type: 'object', additionalProperties: false, required: fieldReq, properties: fieldProps },
335
+ };
336
+ required.push(name);
337
+ }
338
+ return {
339
+ type: 'object', additionalProperties: false, required, properties,
340
+ ...(definitions.size > 0 ? { $defs: Object.fromEntries(definitions) } : {}),
341
+ };
342
+ }
343
+ function clampDescription(description) {
344
+ if (description.length <= IDP_PROCESSOR_DESCRIPTION_MAX_LENGTH)
345
+ return description;
346
+ const cut = description.slice(0, IDP_PROCESSOR_DESCRIPTION_MAX_LENGTH);
347
+ const last = cut.codePointAt(cut.length - 1) ?? 0;
348
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
349
+ }
350
+ /**
351
+ * The spec a node's processor holds (flow-schema `buildIdpProcessorSpec` over
352
+ * `collectIdpProcessorUpdates`' inputs): the taxonomy JSON-encoded, and the
353
+ * model settings in the backend's vocabulary. For instance the seeded node
354
+ * gives `{ description: '', prompt: '', outputSchema: '{"type":"object",…}',
355
+ * extractionStrategy: 'SingleExtract', modelOverride: 'gemini-2.5-flash', … }`.
356
+ */
357
+ export function buildIdpProcessorSpec(node) {
358
+ const schema = readExtractionSchema(node.inputs);
359
+ const modelConfig = asObject(asObject(node.inputs)?.modelConfig);
360
+ const config = modelConfig === undefined
361
+ ? (isExtractionSchema(schema) ? schema.config : buildExtractionConfig(undefined))
362
+ : buildExtractionConfig(modelConfig);
363
+ const prompt = isExtractionSchema(schema) ? schema.prompt : (asObject(schema?.taxonomy)?.overallInstructions ?? '');
364
+ const outputSchema = isExtractionSchema(schema) ? schema.outputSchema : buildLegacyOutputSchema(schema);
365
+ const modelOverride = tryLlmGatewayModelId(config.model?.version);
366
+ const attributionStrategy = resolveApiAttributionStrategy(config.attribution, config.execution_mode);
367
+ const attributionModelOverride = attributionStrategy === 'WordId' ? config.attribution_model?.trim() || undefined : undefined;
368
+ const languageSupport = config.language_support ? ownEntry(LANGUAGE_SUPPORT_TO_API, config.language_support) : undefined;
369
+ const layoutEngine = config.layout_engine?.trim() || undefined;
370
+ const layoutModel = layoutEngine ? config.layout_model?.trim() || undefined : undefined;
371
+ const overrides = config.overrides?.trim() || undefined;
372
+ // Key order is the upstream spread order, so the file's bytes match.
373
+ const preprocessing = {
374
+ ...(languageSupport ? { languageSupport } : {}),
375
+ ...(layoutEngine ? { layoutEngine } : {}),
376
+ ...(layoutModel ? { layoutModel } : {}),
377
+ ...(overrides ? { overrides } : {}),
378
+ };
379
+ return {
380
+ description: clampDescription(readNodeDescription(node)),
381
+ prompt,
382
+ outputSchema: JSON.stringify(outputSchema),
383
+ extractionStrategy: toApiExtractionStrategy(config.execution_mode),
384
+ ...(modelOverride ? { modelOverride } : {}),
385
+ ...(attributionStrategy ? { attributionStrategy } : {}),
386
+ attributionModelOverride: attributionModelOverride ?? '',
387
+ ...preprocessing,
388
+ layoutEngine: layoutEngine ?? '',
389
+ layoutModel: layoutModel ?? '',
390
+ };
391
+ }
392
+ /**
393
+ * A processor's name from the node's label, suffixed `_1`, `_2`, … when the
394
+ * solution already has it (case-insensitive); undefined for a blank label.
395
+ * For instance `deriveIdpProcessorName('Extract', ['extract'])` is `'Extract_1'`.
396
+ */
397
+ export function deriveIdpProcessorName(label, takenNames) {
398
+ const base = label?.trim();
399
+ if (!base)
400
+ return undefined;
401
+ const taken = new Set();
402
+ for (const name of takenNames)
403
+ taken.add(name.toLowerCase());
404
+ if (!taken.has(base.toLowerCase()))
405
+ return base;
406
+ for (let index = 1;; index++) {
407
+ const candidate = `${base}_${index}`;
408
+ if (!taken.has(candidate.toLowerCase()))
409
+ return candidate;
410
+ }
411
+ }
412
+ // ─── The resource file ───────────────────────────────────────────────────────
413
+ const lowerFirst = (value) => (value.length === 0 ? value : value.charAt(0).toLowerCase() + value.slice(1));
414
+ /** Solution-relative path a NEW processor's file is created at, e.g. `resources/solution_folder/idpProcessor/extraction/Extract_invoice.json`. */
415
+ export function idpProcessorResourcePath(name) {
416
+ return `resources/${SOLUTION_FOLDER}/${lowerFirst(IDP_PROCESSOR_RESOURCE_KIND)}/${lowerFirst(IDP_PROCESSOR_RESOURCE_TYPE)}/${name.replace(/[^a-zA-Z0-9._-]/g, '_')}.json`;
417
+ }
418
+ /** Whether a parsed resource file is an IDP processor's (its `kind`, case-insensitively). */
419
+ export function isIdpProcessorResource(file) {
420
+ const kind = asObject(asObject(file)?.resource)?.kind;
421
+ return typeof kind === 'string' && kind.toLowerCase() === IDP_PROCESSOR_RESOURCE_KIND.toLowerCase();
422
+ }
423
+ /** A brand-new resource file for a processor. */
424
+ export function wrapIdpProcessorSpec(input) {
425
+ return {
426
+ docVersion: IDP_PROCESSOR_RESOURCE_DOC_VERSION,
427
+ resource: {
428
+ name: input.name,
429
+ kind: IDP_PROCESSOR_RESOURCE_KIND,
430
+ type: lowerFirst(IDP_PROCESSOR_RESOURCE_TYPE),
431
+ apiVersion: IDP_PROCESSOR_RESOURCE_API_VERSION,
432
+ isOverridable: true,
433
+ dependencies: [],
434
+ runtimeDependencies: [],
435
+ folders: [{ fullyQualifiedName: SOLUTION_FOLDER }],
436
+ spec: { name: input.name, ...input.spec },
437
+ locks: [],
438
+ key: input.key,
439
+ files: [],
440
+ },
441
+ };
442
+ }
443
+ /**
444
+ * The optional spec keys {@link buildIdpProcessorSpec} omits when the node has
445
+ * no value for them. The node is their only author, so one it no longer sets
446
+ * is cleared rather than kept from an earlier compile: for instance a removed
447
+ * `modelConfig.experimentalSettings` drops `overrides`. (The CLI's pack merges
448
+ * without clearing, so a stale value would survive there; nothing re-adds a
449
+ * cleared one.)
450
+ */
451
+ const MANAGED_OPTIONAL_SPEC_KEYS = ['modelOverride', 'attributionStrategy', 'languageSupport', 'overrides'];
452
+ /**
453
+ * An existing resource file with a fresh spec merged in key by key: its key,
454
+ * name and any spec key the node does not manage stay; a managed optional key
455
+ * the fresh spec omits is cleared.
456
+ */
457
+ export function updateIdpProcessorResource(file, spec) {
458
+ const resource = asObject(file.resource) ?? {};
459
+ const previous = { ...(asObject(resource.spec) ?? {}) };
460
+ for (const key of MANAGED_OPTIONAL_SPEC_KEYS)
461
+ if (!(key in spec))
462
+ delete previous[key];
463
+ return { ...file, resource: { ...resource, spec: { ...previous, ...spec } } };
464
+ }
465
+ /**
466
+ * The `idpProcessor` row of each distinct processor the flow's Extract document
467
+ * nodes name, as pack derives it: `processorKey` with the key, `name` with the
468
+ * resource's name (`namesByKey`, else the node's `processorName`, else its
469
+ * label), `folderPath` with a published processor's folder. An attribute with no
470
+ * value carries no `defaultValue`, as pack writes it.
471
+ */
472
+ export function idpProcessorBindingRows(workflow, namesByKey = new Map()) {
473
+ const rows = [];
474
+ const seen = new Set();
475
+ for (const node of collectWorkflowNodes(workflow)) {
476
+ if (!isDynamicExtractNode(node))
477
+ continue;
478
+ const key = readIdpProcessorKey(node.inputs);
479
+ if (!key || seen.has(key))
480
+ continue;
481
+ seen.add(key);
482
+ const name = namesByKey.get(key) ?? readIdpProcessorName(node.inputs) ?? readNodeLabel(node) ?? '';
483
+ const folderPath = readIdpProcessorFolderPath(node.inputs) ?? '';
484
+ const attribute = (value, displayName) => ({ ...(value ? { defaultValue: value } : {}), isExpression: false, displayName });
485
+ const label = readNodeLabel(node);
486
+ rows.push({
487
+ resource: IDP_PROCESSOR_RESOURCE_KIND,
488
+ key,
489
+ id: `${IDP_PROCESSOR_RESOURCE_KIND}${key}`,
490
+ value: {
491
+ processorKey: attribute(key, 'Processor key'),
492
+ name: attribute(name, 'Processor name'),
493
+ folderPath: attribute(folderPath, 'Folder path'),
494
+ },
495
+ metadata: {
496
+ ...(label !== undefined ? { ActivityName: label } : {}),
497
+ BindingsVersion: '2.2',
498
+ DisplayLabel: PROCESSOR_KEY_INPUT,
499
+ SolutionsSupport: 'true',
500
+ },
501
+ });
502
+ }
503
+ return rows;
504
+ }
505
+ /**
506
+ * `bindings_v2.json` rows with the processor rows replaced by `rows`: a row
507
+ * for a key no node names any more goes, as pack drops it, unless some flow
508
+ * could not be read (`keepUnderived`), when the old rows stay. Every other
509
+ * row is kept as it is.
510
+ */
511
+ export function withIdpProcessorRows(resources, rows, options = {}) {
512
+ const derived = new Map();
513
+ for (const row of rows)
514
+ if (!derived.has(row.key))
515
+ derived.set(row.key, row);
516
+ const kept = resources.filter((r) => r.resource !== IDP_PROCESSOR_RESOURCE_KIND
517
+ || (options.keepUnderived === true && !derived.has(String(r.key))));
518
+ return [...kept, ...derived.values()];
519
+ }
520
+ // ─── The seeded taxonomy ─────────────────────────────────────────────────────
521
+ /** The field-type catalogue a new node starts with (the CLI's `DEFAULT_FIELD_TYPE_DEFINITIONS`). */
522
+ const DEFAULT_FIELD_TYPE_DEFINITIONS = {
523
+ 'ft-exact-text': { title: 'Exact Text', type: ['string', 'null'], format: 'verbatim' },
524
+ 'ft-inferred-text': { title: 'Inferred Text', type: ['string', 'null'] },
525
+ 'ft-date': { title: 'Date', type: ['string', 'null'], format: 'date' },
526
+ 'ft-number': { title: 'Number', type: ['string', 'null'], format: 'decimal' },
527
+ 'ft-monetary-quantity': { title: 'Monetary Quantity', type: ['string', 'null'], format: 'monetary' },
528
+ 'ft-boolean': { title: 'Boolean', type: ['boolean', 'null'] },
529
+ };
530
+ /** The `config` block the Schema Editor insists on, from the node's model settings (the CLI's `buildScaffoldConfig`). */
531
+ export function buildScaffoldConfig(modelConfig) {
532
+ const settings = asObject(modelConfig) ?? {};
533
+ const text = (v) => (typeof v === 'string' ? v : undefined);
534
+ const modelVersion = text(settings.model_version);
535
+ return {
536
+ extraction_method: 'external_llm',
537
+ model: modelVersion === undefined || modelVersion.length === 0 ? null : { family: modelVersion.split(/[-_]/)[0], version: modelVersion },
538
+ execution_mode: text(settings.execution_mode) ?? 'standard',
539
+ 'pre-processing': text(settings.input_config) ?? 'none',
540
+ attribution: text(settings.attribution_method) ?? 'word_ids',
541
+ model_config: { temperature: null, top_p: null, seed: null, frequency_penalty: null, prompt_override: null },
542
+ };
543
+ }
544
+ /**
545
+ * The schema document `nodes create` seeds a node with: no field groups, and
546
+ * the default field types to reference. Fresh per call.
547
+ */
548
+ export function buildDefaultSchemaDocument(modelConfig) {
549
+ return {
550
+ config: buildScaffoldConfig(modelConfig),
551
+ prompt: '',
552
+ outputSchema: {
553
+ type: 'object',
554
+ additionalProperties: false,
555
+ required: [],
556
+ properties: {},
557
+ $defs: JSON.parse(JSON.stringify(DEFAULT_FIELD_TYPE_DEFINITIONS)),
558
+ },
559
+ };
560
+ }