@elementumai/edk 0.8.0-preview.11 → 0.8.2-alpha.5

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.
Files changed (180) hide show
  1. package/README.md +510 -324
  2. package/dist-sdk/src/catalog/ai-provider-models.d.ts +30 -0
  3. package/dist-sdk/src/catalog/ai-provider-models.js +63 -0
  4. package/dist-sdk/src/catalog/factories.d.ts +56 -3
  5. package/dist-sdk/src/catalog/factories.js +83 -4
  6. package/dist-sdk/src/catalog/from-authoring.js +19 -2
  7. package/dist-sdk/src/catalog/index.d.ts +3 -2
  8. package/dist-sdk/src/catalog/index.js +3 -2
  9. package/dist-sdk/src/catalog/org.d.ts +1 -1
  10. package/dist-sdk/src/catalog/org.js +134 -50
  11. package/dist-sdk/src/catalog/render.d.ts +13 -1
  12. package/dist-sdk/src/catalog/render.js +21 -4
  13. package/dist-sdk/src/catalog/token.js +18 -0
  14. package/dist-sdk/src/catalog/types.d.ts +75 -3
  15. package/dist-sdk/src/catalog/types.js +3 -0
  16. package/dist-sdk/src/core/system-fields.d.ts +2 -0
  17. package/dist-sdk/src/core/system-fields.js +2 -0
  18. package/dist-sdk/src/core/types/ai-provider.d.ts +10 -23
  19. package/dist-sdk/src/core/types/ai-provider.js +1 -25
  20. package/dist-sdk/src/core/types/app.d.ts +26 -1
  21. package/dist-sdk/src/engine/build/context.d.ts +58 -0
  22. package/dist-sdk/src/engine/build/context.js +11 -1
  23. package/dist-sdk/src/engine/build/source-context.d.ts +45 -0
  24. package/dist-sdk/src/engine/build/source-context.js +23 -0
  25. package/dist-sdk/src/engine/pull/context.d.ts +15 -0
  26. package/dist-sdk/src/engine/pull/org.d.ts +10 -0
  27. package/dist-sdk/src/engine/pull/org.js +34 -4
  28. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  29. package/dist-sdk/src/engine/tf/index.js +2 -2
  30. package/dist-sdk/src/engine/tf/labels.d.ts +54 -0
  31. package/dist-sdk/src/engine/tf/labels.js +75 -0
  32. package/dist-sdk/src/engine/tf/parse.d.ts +15 -0
  33. package/dist-sdk/src/engine/tf/parse.js +162 -0
  34. package/dist-sdk/src/entities/access-policy/build.d.ts +26 -0
  35. package/dist-sdk/src/entities/access-policy/build.js +7 -0
  36. package/dist-sdk/src/entities/access-policy/filter.d.ts +61 -0
  37. package/dist-sdk/src/entities/access-policy/filter.js +83 -0
  38. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +66 -0
  39. package/dist-sdk/src/entities/access-policy/from-tf.js +187 -0
  40. package/dist-sdk/src/entities/access-policy/module.d.ts +3 -0
  41. package/dist-sdk/src/entities/access-policy/module.js +17 -0
  42. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +43 -0
  43. package/dist-sdk/src/entities/access-policy/to-tf.js +164 -0
  44. package/dist-sdk/src/entities/access-policy/types.d.ts +4 -0
  45. package/dist-sdk/src/entities/access-policy/types.js +10 -0
  46. package/dist-sdk/src/entities/agent/build.d.ts +2 -0
  47. package/dist-sdk/src/entities/agent/build.js +1 -0
  48. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +38 -3
  49. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +257 -32
  50. package/dist-sdk/src/entities/agent/from-tf.d.ts +29 -9
  51. package/dist-sdk/src/entities/agent/from-tf.js +146 -19
  52. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  53. package/dist-sdk/src/entities/agent/module.js +14 -4
  54. package/dist-sdk/src/entities/agent/to-tf.d.ts +46 -1
  55. package/dist-sdk/src/entities/agent/to-tf.js +160 -14
  56. package/dist-sdk/src/entities/agent/tools.d.ts +88 -9
  57. package/dist-sdk/src/entities/agent/tools.js +46 -7
  58. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.d.ts +17 -0
  59. package/dist-sdk/src/entities/agent-a2a-skill/from-tf.js +64 -0
  60. package/dist-sdk/src/entities/agent-a2a-skill/module.d.ts +4 -0
  61. package/dist-sdk/src/entities/agent-a2a-skill/module.js +14 -0
  62. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.d.ts +40 -0
  63. package/dist-sdk/src/entities/agent-a2a-skill/to-tf.js +47 -0
  64. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +51 -4
  65. package/dist-sdk/src/entities/agent-tool/from-tf.js +131 -35
  66. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +11 -4
  67. package/dist-sdk/src/entities/agent-tool/to-tf.js +176 -30
  68. package/dist-sdk/src/entities/agent-tool/types.d.ts +5 -4
  69. package/dist-sdk/src/entities/agent-tool/types.js +38 -6
  70. package/dist-sdk/src/entities/app/build.d.ts +91 -13
  71. package/dist-sdk/src/entities/app/build.js +63 -5
  72. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +3 -0
  73. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -1
  74. package/dist-sdk/src/entities/app/from-tf.js +32 -22
  75. package/dist-sdk/src/entities/app/index.d.ts +4 -1
  76. package/dist-sdk/src/entities/app/index.js +2 -1
  77. package/dist-sdk/src/entities/app/module.js +10 -2
  78. package/dist-sdk/src/entities/app/to-tf.d.ts +5 -0
  79. package/dist-sdk/src/entities/app/to-tf.js +45 -4
  80. package/dist-sdk/src/entities/automation/build.d.ts +57 -13
  81. package/dist-sdk/src/entities/automation/build.js +62 -42
  82. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +25 -8
  83. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +16 -1
  84. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +206 -47
  85. package/dist-sdk/src/entities/automation/filter.d.ts +37 -3
  86. package/dist-sdk/src/entities/automation/filter.js +54 -3
  87. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -27
  88. package/dist-sdk/src/entities/automation/from-tf.js +1344 -222
  89. package/dist-sdk/src/entities/automation/index.d.ts +4 -0
  90. package/dist-sdk/src/entities/automation/index.js +4 -0
  91. package/dist-sdk/src/entities/automation/module.js +29 -32
  92. package/dist-sdk/src/entities/automation/operators.d.ts +29 -2
  93. package/dist-sdk/src/entities/automation/operators.js +27 -1
  94. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +19 -0
  95. package/dist-sdk/src/entities/automation/output-key-wire-name.js +24 -0
  96. package/dist-sdk/src/entities/automation/script-code.d.ts +10 -21
  97. package/dist-sdk/src/entities/automation/script-code.js +272 -5
  98. package/dist-sdk/src/entities/automation/tasks.d.ts +125 -19
  99. package/dist-sdk/src/entities/automation/tasks.js +83 -15
  100. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -29
  101. package/dist-sdk/src/entities/automation/to-tf.js +1291 -230
  102. package/dist-sdk/src/entities/automation/triggers.d.ts +9 -1
  103. package/dist-sdk/src/entities/automation/types.d.ts +29 -4
  104. package/dist-sdk/src/entities/automation/types.js +76 -46
  105. package/dist-sdk/src/entities/element/build.d.ts +44 -13
  106. package/dist-sdk/src/entities/element/build.js +45 -3
  107. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -1
  108. package/dist-sdk/src/entities/element/from-tf.js +28 -14
  109. package/dist-sdk/src/entities/element/index.d.ts +4 -1
  110. package/dist-sdk/src/entities/element/index.js +2 -1
  111. package/dist-sdk/src/entities/element/module.js +4 -1
  112. package/dist-sdk/src/entities/element/to-tf.js +26 -3
  113. package/dist-sdk/src/entities/field/build.d.ts +61 -14
  114. package/dist-sdk/src/entities/field/build.js +10 -0
  115. package/dist-sdk/src/entities/field/calc/runtime.js +4 -0
  116. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -3
  117. package/dist-sdk/src/entities/field/from-tf.js +118 -7
  118. package/dist-sdk/src/entities/field/module.js +3 -2
  119. package/dist-sdk/src/entities/field/to-tf.d.ts +46 -11
  120. package/dist-sdk/src/entities/field/to-tf.js +166 -17
  121. package/dist-sdk/src/entities/field/types.d.ts +26 -0
  122. package/dist-sdk/src/entities/field/types.js +34 -12
  123. package/dist-sdk/src/entities/file-reader/build.d.ts +108 -50
  124. package/dist-sdk/src/entities/file-reader/build.js +23 -23
  125. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.d.ts +6 -0
  126. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.js +109 -0
  127. package/dist-sdk/src/entities/file-reader/from-tf.d.ts +13 -0
  128. package/dist-sdk/src/entities/file-reader/from-tf.js +172 -0
  129. package/dist-sdk/src/entities/file-reader/index.d.ts +8 -3
  130. package/dist-sdk/src/entities/file-reader/index.js +7 -2
  131. package/dist-sdk/src/entities/file-reader/module.d.ts +3 -0
  132. package/dist-sdk/src/entities/file-reader/module.js +115 -0
  133. package/dist-sdk/src/entities/file-reader/to-tf.d.ts +14 -0
  134. package/dist-sdk/src/entities/file-reader/to-tf.js +84 -0
  135. package/dist-sdk/src/entities/file-reader/types.d.ts +32 -0
  136. package/dist-sdk/src/entities/file-reader/types.js +30 -0
  137. package/dist-sdk/src/entities/org/ai-provider.d.ts +13 -0
  138. package/dist-sdk/src/entities/org/ai-provider.js +46 -0
  139. package/dist-sdk/src/entities/org/connector.d.ts +8 -1
  140. package/dist-sdk/src/entities/org/connector.js +12 -14
  141. package/dist-sdk/src/entities/org/group.js +10 -1
  142. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  143. package/dist-sdk/src/entities/org/index.js +1 -0
  144. package/dist-sdk/src/entities/org/user.js +10 -1
  145. package/dist-sdk/src/entities/shared/filters/ast.d.ts +59 -9
  146. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  147. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +17 -0
  148. package/dist-sdk/src/entities/shared/tool-field-ref.js +46 -0
  149. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -1
  150. package/dist-sdk/src/entities/shared/types/field-types.js +9 -0
  151. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +19 -0
  152. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +128 -11
  153. package/dist-sdk/src/entities/skill/from-tf.js +4 -3
  154. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  155. package/dist-sdk/src/entities/skill/module.js +7 -1
  156. package/dist-sdk/src/entities/skill/to-tf.d.ts +26 -0
  157. package/dist-sdk/src/entities/skill/to-tf.js +65 -4
  158. package/dist-sdk/src/entities/skill/tools.d.ts +37 -8
  159. package/dist-sdk/src/entities/skill/tools.js +43 -1
  160. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +34 -4
  161. package/dist-sdk/src/entities/skill-tool/from-tf.js +128 -18
  162. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +13 -1
  163. package/dist-sdk/src/entities/skill-tool/to-tf.js +164 -25
  164. package/dist-sdk/src/entities/skill-tool/types.d.ts +5 -7
  165. package/dist-sdk/src/entities/skill-tool/types.js +47 -11
  166. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -2
  167. package/dist-sdk/src/entities/view/from-tf.js +11 -9
  168. package/dist-sdk/src/entities/view/to-tf.d.ts +9 -7
  169. package/dist-sdk/src/entities/view/to-tf.js +39 -18
  170. package/dist-sdk/src/entities/view/types.d.ts +1 -1
  171. package/dist-sdk/src/entities/view/types.js +1 -1
  172. package/dist-sdk/src/graph/deferred-catalog-render.d.ts +0 -5
  173. package/dist-sdk/src/graph/deferred-catalog-render.js +1 -20
  174. package/dist-sdk/src/graph/index.d.ts +8 -0
  175. package/dist-sdk/src/graph/index.js +13 -9
  176. package/dist-sdk/src/graph/modules.js +8 -1
  177. package/dist-sdk/src/graph/types.d.ts +98 -4
  178. package/package.json +49 -16
  179. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +0 -76
  180. package/dist-sdk/src/entities/automation/value-ref-tf.js +0 -190
@@ -1,266 +1,1327 @@
1
+ import { EntityTfError } from "../../engine/entity.js";
2
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEY_SET } from "../../core/system-fields.js";
3
+ import { appResourceLabelPrefix, appScopedResourceLabel, expr, isTfExpr, isUuid, sanitizeName, snakeSlug, tsLabelToTfLabel, } from "../../engine/tf/index.js";
4
+ import { CONNECTOR_ORG_BAG } from "../org/connector.js";
5
+ import { FILE_READER_SUB_TYPE_BY_RESOURCE, FILE_READER_SUB_TYPE_BY_TYPE_KEY } from "../file-reader/types.js";
6
+ import { AUTOMATION_RESOURCE_TYPE, WORKFLOW_PUBLISH_RESOURCE_TYPE } from "./types.js";
7
+ function scopedLabel(appTfLabel, label) {
8
+ return appScopedResourceLabel(appTfLabel, label);
9
+ }
10
+ function scopedOptionLocalName(localName, owner) {
11
+ for (const suffix of ["_options_by_label", "_option_ids_by_label"]) {
12
+ if (!localName.endsWith(suffix))
13
+ continue;
14
+ const fieldLabel = localName.slice(0, -suffix.length);
15
+ if (fieldLabel === `${owner.appTfLabel}_status` || fieldLabel === `${owner.appTfLabel}_stage`) {
16
+ return localName;
17
+ }
18
+ const prefix = appResourceLabelPrefix(owner.appTfLabel);
19
+ if (prefix !== "" && fieldLabel.startsWith(prefix))
20
+ return localName;
21
+ return `${scopedLabel(owner.appTfLabel, fieldLabel)}${suffix}`;
22
+ }
23
+ return localName;
24
+ }
25
+ const TRIGGER_RESOURCES = {
26
+ createRecord: "elementum_record_created_trigger",
27
+ updateRecord: "elementum_record_updated_trigger",
28
+ attachment: "elementum_attachment_added_trigger",
29
+ commentAdded: "elementum_comment_added_trigger",
30
+ conversationEnd: "elementum_agent_conversation_ended_trigger",
31
+ slackMessage: "elementum_slack_message_trigger",
32
+ onDemand: "elementum_on_demand_trigger",
33
+ webhook: "elementum_webhook_trigger",
34
+ emailReceived: "elementum_email_ingestion_trigger",
35
+ approvalChain: "elementum_approval_chain_trigger",
36
+ datamine: "elementum_datamine_trigger",
37
+ survey: "elementum_survey_trigger",
38
+ };
1
39
  /**
2
- * Automation emission (Phase 1). `automationToTf` consumes the discovered
3
- * `DeployableEntity` (the `defineAutomation` def() payload) and emits the
4
- * COMPOSITE ei dialect:
5
- *
6
- * elementum_automation.<autoLabel> — identity (app_id, name, ...)
7
- * elementum_<trigger>_trigger.<autoLabel> — the one trigger (automation ref)
8
- * elementum_<task>_task.<autoLabel>_<task> — one per task, parent-chained
9
- * elementum_workflow_publish.<autoLabel> — version + depends_on(all tasks)
10
- *
11
- * Labels follow ei's export: the automation label is `sanitizeName(name)` and a
12
- * task label is `<autoLabel>_<sanitizeName(taskName)>` — so build output matches
13
- * ei's addresses for adoption/build-vs-export. Ordering is encoded exactly as ei does it:
14
- * each task's `parent` points at the previous task (or the trigger, for the
15
- * first). References are BARE resource refs (`elementum_automation.x`, no `.id`),
16
- * matching the capture.
17
- *
18
- * Phase 1 carries the onDemand trigger and the executeScript + setVariable
19
- * (create form → elementum_variable_task) tasks. Any other trigger/task kind, or
20
- * an operator (forEach/forkJoin/switch), degrades through `diagnostics` —
21
- * reported, never silently dropped (plan §6). Task BODY attributes beyond the
22
- * Phase-1 set are reconciled against a fresh live capture (see the tranche plan).
40
+ * setVariable tasks share one wire key ("variable") but two distinct
41
+ * resource types depending on create vs. update — TASK_RESOURCES can't
42
+ * carry both under one key. Shared by preRegister (so an explicit
43
+ * hclParent onto an update-variant task resolves to the right type — see
44
+ * edk#287) and emitTasks's own block emission, so the two can never
45
+ * disagree again.
23
46
  */
24
- import { EntityTfError } from "../../engine/entity.js";
25
- import { expr, sanitizeName } from "../../engine/tf/index.js";
26
- import { APP_RESOURCE_TYPE } from "../app/module.js";
27
- import { indexVariableIds, wireRefToTf } from "./value-ref-tf.js";
28
- import { AUTOMATION_RESOURCE_TYPE, AUTOMATION_SUB_TYPE_BY_TYPE_KEY, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
29
- /** A bare resource reference (`elementum_automation.x`, no attribute path). */
30
- function bareRef(type, label) {
31
- return expr.resourceAttr(type, label, []);
47
+ function variableTaskResourceType(taskBody, refKey) {
48
+ const creates = Array.isArray(taskBody.create) ? taskBody.create : [];
49
+ const updates = Array.isArray(taskBody.update) ? taskBody.update : [];
50
+ if (creates.length + updates.length !== 1) {
51
+ throw new EntityTfError(`setVariable task "${refKey}" must contain exactly one create or update for Terraform`);
52
+ }
53
+ return creates.length === 1 ? "elementum_variable_task" : "elementum_update_variable_task";
32
54
  }
33
- /** Discriminant + body of a one-of wire object (`{ onDemand: {...} }`). */
34
- function oneOf(wire) {
35
- if (wire === undefined || typeof wire !== "object")
36
- return undefined;
37
- const key = Object.keys(wire)[0];
38
- if (key === undefined)
55
+ const TASK_RESOURCES = {
56
+ message: "elementum_message_task",
57
+ updateField: "elementum_update_field_task",
58
+ variable: "elementum_variable_task",
59
+ createRecord: "elementum_create_record_task",
60
+ recordSearch: "elementum_record_search_task",
61
+ tableRecordsSearch: "elementum_table_records_search_task",
62
+ sendEmail: "elementum_send_email_task",
63
+ initiateCall: "elementum_initiate_call_task",
64
+ approvalChain: "elementum_approval_chain_task",
65
+ approvalStatusUpdate: "elementum_approval_status_update_task",
66
+ findRelatedRecords: "elementum_find_related_records_task",
67
+ api: "elementum_api_task",
68
+ aiAgent: "elementum_ai_agent_task",
69
+ forEach: "elementum_for_each_task",
70
+ switch: "elementum_switch_task",
71
+ forkJoin: "elementum_fork_join_task",
72
+ addWatcher: "elementum_add_watcher_task",
73
+ notification: "elementum_notification_task",
74
+ relateRecords: "elementum_relate_records_task",
75
+ aiClassify: "elementum_ai_classify_task",
76
+ aiSummarize: "elementum_ai_summarize_task",
77
+ aiSearchTable: "elementum_ai_search_table_task",
78
+ aiTransform: "elementum_ai_transform_task",
79
+ saveAttachment: "elementum_save_attachment_task",
80
+ userSearch: "elementum_user_search_task",
81
+ calculation: "elementum_calculation_task",
82
+ executeScript: "elementum_execute_script_task",
83
+ documentModel: "elementum_file_reader_task",
84
+ procedure: "elementum_procedure_task",
85
+ runAutomation: "elementum_run_automation_task",
86
+ aspectRecordFieldLocking: "elementum_aspect_record_field_locking_task",
87
+ aiFileAnalysis: "elementum_ai_file_read_task",
88
+ };
89
+ const CONFIG_ATTRS = {
90
+ aspectId: "object_id",
91
+ relatedAspectId: "object_id",
92
+ aspectFieldId: "field_id",
93
+ changedFieldIds: "changed_fields",
94
+ thinkUi: "think_ui",
95
+ conversationType: "conversation_type",
96
+ customResponse: "custom_response",
97
+ showTriggeredBy: "show_triggered_by",
98
+ datamineId: "datamine_id",
99
+ fireOnAlert: "fire_on_alert",
100
+ fireOnRecovery: "fire_on_recovery",
101
+ emailAliasId: "email_alias_id",
102
+ approvalChainTemplateId: "approval_chain_template_id",
103
+ surveyTemplateId: "survey_template_id",
104
+ workflowFields: "fields",
105
+ recordReference: "record_reference",
106
+ recordId: "record_reference",
107
+ sourceRecordIds: "source_record_ids",
108
+ targetRecordId: "target_record_id",
109
+ tableId: "table_id",
110
+ messageBody: "message_body",
111
+ fromUsername: "from_username",
112
+ fromPersonal: "from_personal",
113
+ externalEmails: "external_emails",
114
+ emailAttachments: "attachments",
115
+ contentsReference: "message",
116
+ agentId: "agent_id",
117
+ agentPrompt: "prompt",
118
+ outputType: "output_type",
119
+ jsonFields: "json_fields",
120
+ aiProviderConnectorId: "ai_provider_connector_id",
121
+ outputSchema: "output_schema",
122
+ urlReference: "url",
123
+ responseType: "response_type",
124
+ continueOnError: "continue_on_error",
125
+ searchTableId: "search_table_id",
126
+ textToSummarize: "text_to_summarize",
127
+ textToClassify: "text_to_classify",
128
+ fieldType: "field_type",
129
+ categorySource: "category_source",
130
+ titleReference: "title",
131
+ messageReference: "message",
132
+ userValueReferences: "user_value_references",
133
+ groupValueReferences: "group_value_references",
134
+ notifyWatchers: "notify_watchers",
135
+ fieldId: "field_id",
136
+ userId: "user_id",
137
+ groupId: "group_id",
138
+ fieldsToLock: "fields_to_lock",
139
+ fieldsToUnlock: "fields_to_unlock",
140
+ fileInput: "file",
141
+ viewState: "view_state",
142
+ targetAutomationId: "target_automation_id",
143
+ targetAutomationRef: "target_automation_ref",
144
+ inputMappings: "input_mappings",
145
+ dynamicInputMappings: "dynamic_input_mappings",
146
+ outputMappings: "output_mappings",
147
+ fileReaderId: "file_reader_id",
148
+ rawText: "raw_text",
149
+ cloudLinkId: "cloudlink_id",
150
+ // provider schema calls this stored_function_id; see from-tf.ts's matching comment.
151
+ procedureId: "stored_function_id",
152
+ };
153
+ function isObject(value) {
154
+ return value !== null && typeof value === "object" && !Array.isArray(value);
155
+ }
156
+ function onlyEntry(value, subject) {
157
+ if (!isObject(value))
158
+ throw new EntityTfError(`${subject} must be an object`);
159
+ const entries = Object.entries(value);
160
+ if (entries.length !== 1 || !isObject(entries[0][1])) {
161
+ throw new EntityTfError(`${subject} must contain exactly one supported type`);
162
+ }
163
+ return entries[0];
164
+ }
165
+ function token(value) {
166
+ if (!isObject(value) || typeof value.__kind !== "string" || typeof value.refName !== "string")
39
167
  return undefined;
40
- const body = wire[key];
41
- return { key, body: body !== null && typeof body === "object" ? body : {} };
168
+ return value;
169
+ }
170
+ function addressExpr(address, path = ["id"]) {
171
+ const dot = address.indexOf(".");
172
+ if (dot === -1)
173
+ throw new EntityTfError(`invalid terraform address "${address}"`);
174
+ return expr.resourceAttr(address.slice(0, dot), address.slice(dot + 1), [...path]);
42
175
  }
43
176
  /**
44
- * Type-specific task-body attributes for the implemented task kinds. Returns
45
- * `unsupported` (the caller reports it) when the body carries something the
46
- * terraform dialect can't encode — never emits it wrong.
177
+ * A field token whose `parent` names a DIFFERENT app/element than the one
178
+ * this automation belongs to (e.g. a `recordSearch` task's filter against
179
+ * another app's field) — resolved via a `data.elementum_field` lookup keyed
180
+ * by the owner's id + the field's display name, mirroring
181
+ * `field/to-tf.ts`'s `resolveRelatedLabelField` for a relation field's
182
+ * `relatedLabelField`. Self-contained: `parentKind`/`parentName` (stamped by
183
+ * `appCatalog`/`elementCatalog` — see `FieldRef`) carry everything needed to
184
+ * register the owner's own `data.elementum_app`/`data.elementum_element`
185
+ * lookup here too, rather than depending on that owner also appearing
186
+ * elsewhere in this same payload (e.g. as the task's own `app:` target).
187
+ * The label is kind-prefixed for the same reason `field/to-tf.ts` prefixes
188
+ * its own foreign-field label: an app and an element can share a refName,
189
+ * and `elementum_field` is one shared data-source type for both.
47
190
  */
48
- function taskBodyAttrs(typeKey, body, refCtx) {
49
- switch (typeKey) {
50
- case "executeScript": {
51
- const attrs = {};
52
- attrs["code"] = typeof body["code"] === "string" ? body["code"] : "";
53
- // Inputs: [{name, value: <ref envelope>}] → [{name, value: refs-syntax expr | literal}].
54
- const inputs = [];
55
- for (const entry of body["inputs"] ?? []) {
56
- if (typeof entry?.name !== "string")
57
- continue;
58
- const converted = wireRefToTf(entry.value, refCtx);
59
- if ("unsupported" in converted) {
60
- return { unsupported: `input "${entry.name}": ${converted.unsupported}` };
191
+ function crossAppFieldToTf(value, ctx, dataBlocks) {
192
+ const parent = value.parent;
193
+ if (parent === undefined)
194
+ throw new EntityTfError(`field ref "${value.refName}" has no parent`);
195
+ // `parentKind`/`parentName` are stamped ALONGSIDE `parent` by
196
+ // `appCatalog`/`elementCatalog` (see `FieldRef`'s doc comment) — never one
197
+ // without the other for a genuine cross-aspect ref. Defaulting either one
198
+ // here instead of failing loudly is exactly the failure mode that
199
+ // previously produced `data.elementum_app.tickets { name = "tickets" }`
200
+ // for what was actually an ELEMENT with a real display name of "Tickets"
201
+ // — a lookup that builds cleanly and misses silently at apply.
202
+ if (value.parentKind === undefined) {
203
+ throw new EntityTfError(`field ref "${value.refName}" has a parent ("${parent}") but no parentKind — incomplete foreign-field provenance; can't tell whether the owner is an app or an element`);
204
+ }
205
+ if (value.parentName === undefined) {
206
+ throw new EntityTfError(`field ref "${value.refName}" has a parent ("${parent}") but no parentName — incomplete foreign-field provenance; the owner lookup would key on the refName instead of its real display name and silently miss at apply`);
207
+ }
208
+ const fieldName = value.name ?? value.refName;
209
+ const ownerType = value.parentKind === "element" ? "elementum_element" : "elementum_app";
210
+ const ownerLabel = tsLabelToTfLabel(parent);
211
+ const objectId = expr.dataAttr(ownerType, ownerLabel, ["id"]);
212
+ const fieldLabel = `${value.parentKind}_${ownerLabel}_${tsLabelToTfLabel(value.refName)}`;
213
+ // Route through the build-wide `orgRefs` registry (same one `agent-tool`/
214
+ // `agent`/`skill`/`field` use) instead of this call's own local
215
+ // `dataBlocks` map, so two DIFFERENT automation files referencing the same
216
+ // foreign app/element/field collapse to one `data.tf` entry instead of
217
+ // each emitting its own identically-addressed `data` block into its own
218
+ // per-automation `.tf` file — a duplicate resource address OpenTofu
219
+ // rejects at `validate`/`plan`. `dataBlocks` remains the fallback for
220
+ // callers that don't supply `orgRefs` (unit tests).
221
+ if (ctx.orgRefs !== undefined) {
222
+ if (value.parentKind === "element") {
223
+ ctx.orgRefs.foreignElement(ownerLabel, value.parentName);
224
+ }
225
+ else {
226
+ ctx.orgRefs.foreignApp(ownerLabel, value.parentName);
227
+ }
228
+ ctx.orgRefs.foreignField("elementum_field", fieldLabel, objectId, fieldName);
229
+ }
230
+ else {
231
+ dataBlocks.set(`${ownerType}.${ownerLabel}`, {
232
+ kind: "data",
233
+ type: ownerType,
234
+ label: ownerLabel,
235
+ attrs: { name: value.parentName },
236
+ });
237
+ dataBlocks.set(`elementum_field.${fieldLabel}`, {
238
+ kind: "data",
239
+ type: "elementum_field",
240
+ label: fieldLabel,
241
+ attrs: { object_id: objectId, name: fieldName },
242
+ });
243
+ }
244
+ return expr.dataAttr("elementum_field", fieldLabel, ["id"]);
245
+ }
246
+ function tokenToTf(value, ctx, dataBlocks) {
247
+ switch (value.__kind) {
248
+ case "userField":
249
+ return value.refName;
250
+ case "app":
251
+ case "element":
252
+ if (value.refName !== ctx.appRefName) {
253
+ if (!value.name)
254
+ throw new EntityTfError(`cross-aspect ref "${value.refName}" has no lookup name`);
255
+ const type = value.__kind === "element" ? "elementum_element" : "elementum_app";
256
+ const label = tsLabelToTfLabel(value.refName);
257
+ // See `crossAppFieldToTf`'s comment: route through the build-wide
258
+ // `orgRefs` registry so multiple automations referencing the same
259
+ // foreign app/element collapse to one `data.tf` entry instead of
260
+ // each stamping a duplicate `data` block into its own file.
261
+ if (ctx.orgRefs !== undefined) {
262
+ if (value.__kind === "element") {
263
+ ctx.orgRefs.foreignElement(label, value.name);
264
+ }
265
+ else {
266
+ ctx.orgRefs.foreignApp(label, value.name);
267
+ }
61
268
  }
62
- inputs.push({ name: entry.name, value: converted.value });
269
+ else {
270
+ dataBlocks.set(`${type}.${label}`, {
271
+ kind: "data",
272
+ type,
273
+ label,
274
+ attrs: { name: value.name },
275
+ });
276
+ }
277
+ return expr.dataAttr(type, label, ["id"]);
63
278
  }
64
- attrs["inputs"] = inputs;
65
- // The provider takes output_schema as a JSON-encoDED string.
66
- if (body["outputSchema"] !== undefined) {
67
- attrs["output_schema"] = { $expr: "jsonencode", value: body["outputSchema"] };
279
+ return expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]);
280
+ case "field": {
281
+ // `!== ctx.appRefName` alone isn't enough: an app and a FOREIGN
282
+ // ELEMENT can share a refName (workspace keys disambiguate by
283
+ // kind+refName, not refName alone), so a same-named element field
284
+ // must still resolve as foreign — the automation's own app is
285
+ // always an app (automations are app-owned only, for now).
286
+ if (value.parent !== undefined && (value.parent !== ctx.appRefName || value.parentKind === "element")) {
287
+ return crossAppFieldToTf(value, ctx, dataBlocks);
68
288
  }
69
- return { attrs };
70
- }
71
- case "variable": {
72
- // The tf dialect carries ONE variable per task: variable_name /
73
- // variable_type / value. (The compose id is stamped for the compose
74
- // path; the provider's variable_id is Computed — no id in HCL.)
75
- const create = body["create"] ?? [];
76
- if (create.length !== 1) {
77
- return { unsupported: `elementum_variable_task carries exactly one variable; got ${create.length}` };
289
+ const address = ctx.fieldAddresses.get(value.refName);
290
+ return address === undefined
291
+ ? expr.local(`${ctx.appTfLabel}_${tsLabelToTfLabel(value.refName)}_field_id`)
292
+ : addressExpr(address);
293
+ }
294
+ case "connector": {
295
+ const tsLabel = value.parent !== undefined ? `${value.parent}.${value.refName}` : value.refName;
296
+ const resolved = ctx.orgRefs?.byTsLabel(CONNECTOR_ORG_BAG, tsLabel);
297
+ if (resolved === undefined) {
298
+ throw new EntityTfError(`connector token "${tsLabel}" is not in the org catalog — re-run \`elementum pull org --data-only\``);
78
299
  }
79
- const decl = create[0];
80
- const attrs = {
81
- variable_name: decl.name ?? "",
82
- variable_type: decl.type ?? "TEXT",
83
- };
84
- if (decl.value !== undefined) {
85
- const converted = wireRefToTf(decl.value, refCtx);
86
- if ("unsupported" in converted) {
87
- return { unsupported: `variable "${decl.name}": ${converted.unsupported}` };
300
+ return expr.dataAttr("elementum_ai_provider_connector", resolved.tfLabel, ["id"]);
301
+ }
302
+ case "cloudLink": {
303
+ if (!value.name)
304
+ throw new EntityTfError(`cloud link token "${value.refName}" has no lookup name`);
305
+ const label = tsLabelToTfLabel(value.refName);
306
+ dataBlocks.set(`elementum_cloudlink.${label}`, {
307
+ kind: "data",
308
+ type: "elementum_cloudlink",
309
+ label,
310
+ attrs: { name: value.name },
311
+ });
312
+ return expr.dataAttr("elementum_cloudlink", label, ["id"]);
313
+ }
314
+ case "automation":
315
+ if (value.parent !== undefined && value.parent !== ctx.appRefName) {
316
+ throw new EntityTfError(`cross-app automation ref "${value.parent}.${value.refName}" is not supported`);
317
+ }
318
+ return expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
319
+ case "agent":
320
+ return expr.resourceAttr("elementum_agent", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
321
+ case "searchTable":
322
+ return expr.resourceAttr("elementum_ai_search_table", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
323
+ case "approvalChain":
324
+ return value.unresolvedId !== undefined
325
+ ? value.unresolvedId
326
+ : expr.resourceAttr("elementum_approval_process", scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
327
+ case "documentModel": {
328
+ const subType = FILE_READER_SUB_TYPE_BY_TYPE_KEY.get(value.readerType ?? "");
329
+ // "xml"/"ai" are declared sub-types (FILE_READER_SUB_TYPES) but don't
330
+ // build yet - matches fileReaderToTf's own implemented guard. Without
331
+ // this, a readFile task referencing one would silently emit a
332
+ // reference to a resource block that's never written, failing only at
333
+ // `tofu plan`/`apply` instead of at build.
334
+ if (subType === undefined || subType.implemented !== true) {
335
+ throw new EntityTfError(`file reader token "${value.refName}" has no recognized readerType ("${value.readerType}") — was it built with defineFileReader?`);
336
+ }
337
+ return expr.resourceAttr(subType.resourceType, scopedLabel(ctx.appTfLabel, tsLabelToTfLabel(value.refName)), ["id"]);
338
+ }
339
+ default:
340
+ throw new EntityTfError(`catalog ref kind "${value.__kind}" has no automation HCL representation`);
341
+ }
342
+ }
343
+ function templateToTf(value, refs) {
344
+ const template = value.template;
345
+ const parameters = value.parameters;
346
+ if (typeof template !== "string" || !Array.isArray(parameters)) {
347
+ throw new EntityTfError("invalid templateReference");
348
+ }
349
+ const byName = new Map();
350
+ for (const parameter of parameters) {
351
+ if (!isObject(parameter) || !isObject(parameter.value) || typeof parameter.value.name !== "string") {
352
+ throw new EntityTfError("nested/list template parameters are not supported by the Terraform contract");
353
+ }
354
+ byName.set(parameter.value.name, valueToTf(parameter.value.value, refs));
355
+ }
356
+ const parts = [];
357
+ let cursor = 0;
358
+ const pattern = /\{\{\{([^}]+)\}\}\}/g;
359
+ for (let match = pattern.exec(template); match !== null; match = pattern.exec(template)) {
360
+ if (match.index > cursor)
361
+ parts.push(template.slice(cursor, match.index));
362
+ const part = byName.get(match[1]);
363
+ if (part === undefined || !isTfExpr(part)) {
364
+ throw new EntityTfError(`template parameter "${match[1]}" is missing or is not a reference`);
365
+ }
366
+ parts.push(part);
367
+ cursor = match.index + match[0].length;
368
+ }
369
+ if (cursor < template.length)
370
+ parts.push(template.slice(cursor));
371
+ return expr.template(parts);
372
+ }
373
+ const TS_REF_SEGMENT_TO_WIRE = {
374
+ record: "Record",
375
+ changedFieldIds: "Changed Fields",
376
+ records: "All found records",
377
+ iteration: "Iteration",
378
+ id: "ID",
379
+ title: "Title",
380
+ };
381
+ const TS_TRIGGER_REF_TO_WIRE = {
382
+ createdByEmail: "Created by Email",
383
+ updatedByManagerEmail: "Updated by Manager Email",
384
+ slackThreadId: "Slack Thread ID",
385
+ slackChannelId: "Slack Channel ID",
386
+ messageAuthorEmail: "Message Author Email",
387
+ messageAuthorId: "Message Author ID",
388
+ messageAuthorName: "Message Author Name",
389
+ messageContent: "Message Content",
390
+ messageId: "Message ID",
391
+ messageMetadata: "Message Metadata",
392
+ };
393
+ const DISPLAY_REF_CANONICAL_CASE = Object.fromEntries(Object.values(TS_TRIGGER_REF_TO_WIRE).map((value) => [value.toLowerCase(), value]));
394
+ const FIELD_REF_SUFFIX_TO_WIRE = {
395
+ "": "",
396
+ id: " ID",
397
+ label: " Label",
398
+ email: " Email",
399
+ name: " Name",
400
+ fieldId: " Field ID",
401
+ // Matches the literal path segment from-tf.ts now produces for this suffix
402
+ // ("as text", not camelCase "asText") - Ref<T> has no ".asText" property
403
+ // anywhere in the type system, so authored code can only reach this suffix
404
+ // through the unresolved-segment bracket-access escape
405
+ // (`(ctx.trigger.record.x as any)["as text"]`), which accumulates the
406
+ // literal string "as text" as the RefData path segment at runtime.
407
+ "as text": " as text",
408
+ "employee.manager": " Manager",
409
+ "employee.manager.email": " Manager Email",
410
+ "employee.manager.name": " Manager Name",
411
+ };
412
+ function wireRefName(name, ctx) {
413
+ const known = TS_TRIGGER_REF_TO_WIRE[name];
414
+ if (known !== undefined)
415
+ return known;
416
+ const canonicalDisplay = DISPLAY_REF_CANONICAL_CASE[name.toLowerCase()];
417
+ if (canonicalDisplay !== undefined)
418
+ return canonicalDisplay;
419
+ const parts = name.split(".");
420
+ if (parts[0] === "record" && parts.length >= 2) {
421
+ const fieldKey = parts[1];
422
+ // System fields (title/status/stage/createdBy/...) have no entry in
423
+ // ctx.fieldNames - that map only carries the app's custom fields bag.
424
+ // Fall back to the provider's default display name for them; a renamed
425
+ // system field won't match and still throws below, same as an unknown
426
+ // custom field key would.
427
+ const fieldName = ctx.fieldNames.get(fieldKey) ??
428
+ (SYSTEM_FIELD_KEY_SET.has(fieldKey) ? DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[fieldKey] : undefined);
429
+ if (fieldName === undefined) {
430
+ throw new EntityTfError(`automation reference "${name}" targets field "${parts[1]}" which does not exist in app "${ctx.appRefName}"`);
431
+ }
432
+ const suffix = parts.slice(2).join(".");
433
+ const wireSuffix = FIELD_REF_SUFFIX_TO_WIRE[suffix];
434
+ if (wireSuffix === undefined) {
435
+ throw new EntityTfError(`automation reference "${name}" has unsupported record-field path "${suffix}"`);
436
+ }
437
+ // The platform lowercases a system field's trailing " By" when it's the
438
+ // PREFIX of a compound ref phrase (e.g. "Created By" + " Email" -> wire
439
+ // ref key "Created by Email") but keeps it capitalized standalone -
440
+ // confirmed live: plan failed with "Invalid index" against the real
441
+ // refs map until this matched. from-tf.ts already reads refs
442
+ // case-insensitively; build must reproduce the platform's exact casing
443
+ // since terraform's refs[] map lookup is case-sensitive.
444
+ const prefix = wireSuffix.length > 0 && fieldName.endsWith(" By") ? `${fieldName.slice(0, -3)} by` : fieldName;
445
+ return `${prefix}${wireSuffix}`;
446
+ }
447
+ // A webhook trigger's body/headers refs (ctx.trigger.body["X"]) can only
448
+ // type-check against DeepRefs<WebhookTriggerOutput>, so parts[0] being
449
+ // "body"/"headers" here already guarantees a genuine webhook reference -
450
+ // no trigger-type gate needed (unlike from-tf.ts's read-side regex, which
451
+ // has to guess at an arbitrary platform string). Reverses the "Body
452
+ // (Plain Text)" -> ["body", "Plain Text"] split from-tf.ts performs.
453
+ if ((parts[0] === "body" || parts[0] === "headers") && parts.length === 2) {
454
+ const label = parts[0] === "body" ? "Body" : "Headers";
455
+ return `${label} (${parts[1]})`;
456
+ }
457
+ parts[0] = TS_REF_SEGMENT_TO_WIRE[parts[0]] ?? parts[0];
458
+ return parts.join(".");
459
+ }
460
+ function valueToTf(value, refs) {
461
+ const catalog = token(value);
462
+ if (catalog !== undefined)
463
+ return tokenToTf(catalog, refs.owner, refs.dataBlocks);
464
+ if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean")
465
+ return value;
466
+ if (Array.isArray(value))
467
+ return value.map((item) => valueToTf(item, refs));
468
+ if (!isObject(value))
469
+ throw new EntityTfError(`unsupported automation value ${String(value)}`);
470
+ if ("value" in value && Object.keys(value).length === 1)
471
+ return valueToTf(value.value, refs);
472
+ if (isObject(value.variableReference) && typeof value.variableReference.id === "string") {
473
+ const target = refs.variableById.get(value.variableReference.id);
474
+ if (target === undefined)
475
+ throw new EntityTfError("unresolved variable ref " + value.variableReference.id);
476
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: target.name }]);
477
+ }
478
+ if (isObject(value.triggerReference) && typeof value.triggerReference.name === "string") {
479
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.triggerReference.name, refs.owner) }]);
480
+ }
481
+ if (isObject(value.taskReference) && typeof value.taskReference.taskRefKey === "string" && typeof value.taskReference.name === "string") {
482
+ const target = refs.tasks.get(value.taskReference.taskRefKey);
483
+ if (target === undefined)
484
+ throw new EntityTfError(`unresolved task ref "${value.taskReference.taskRefKey}"`);
485
+ // aiFileAnalysis/readFile's refs are keyed by whatever arbitrary field
486
+ // names the file reader schema itself defines (e.g. "title",
487
+ // "document_type") - wireRefName's generic segment table
488
+ // (TS_REF_SEGMENT_TO_WIRE) is for a DIFFERENT thing (a task's own
489
+ // canonical record-identity fields, e.g. createRecord's generic "id"/
490
+ // "title"), and wrongly rewrites a reader field literally named "title"
491
+ // into the wire key "Title", which doesn't exist in these two
492
+ // resources' actual refs map - confirmed live via a real apply's
493
+ // "Invalid index" error. Their field names pass through verbatim.
494
+ const isFileReaderTask = target.type === "elementum_ai_file_read_task" || target.type === "elementum_file_reader_task";
495
+ const refKey = isFileReaderTask ? value.taskReference.name : wireRefName(value.taskReference.name, refs.owner);
496
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: refKey }]);
497
+ }
498
+ if (isObject(value.forEachReference) && typeof value.forEachReference.forEachTaskRefKey === "string" && typeof value.forEachReference.name === "string") {
499
+ const target = refs.tasks.get(value.forEachReference.forEachTaskRefKey);
500
+ if (target === undefined)
501
+ throw new EntityTfError(`unresolved forEach ref "${value.forEachReference.forEachTaskRefKey}"`);
502
+ return expr.resourceAttr(target.type, target.label, ["refs", { index: wireRefName(value.forEachReference.name, refs.owner) }]);
503
+ }
504
+ if (isObject(value.templateReference))
505
+ return templateToTf(value.templateReference, refs);
506
+ if (isObject(value.secretReference) && typeof value.secretReference.secretId === "string") {
507
+ throw new EntityTfError("secret references have no provider HCL representation");
508
+ }
509
+ if (typeof value.kind === "string") {
510
+ if (value.kind === "localRef" && typeof value.localName === "string" && Array.isArray(value.path)) {
511
+ return expr.local(scopedOptionLocalName(value.localName, refs.owner), value.path);
512
+ }
513
+ if (value.kind === "unresolved" && typeof value.uuid === "string")
514
+ return value.uuid;
515
+ if (value.kind === "literal" && "value" in value)
516
+ return valueToTf(value.value, refs);
517
+ }
518
+ if (isTfExpr(value))
519
+ return value;
520
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, valueToTf(child, refs)]));
521
+ }
522
+ function snake(name) {
523
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/-/g, "_").toLowerCase();
524
+ }
525
+ function unwrapDefault(value) {
526
+ if (!isObject(value))
527
+ return value;
528
+ const values = Object.values(value);
529
+ return values.length === 1 ? values[0] : value;
530
+ }
531
+ function filterReferenceToTf(value, refs) {
532
+ // Raw pass-through for a filter left side the pull-time deserializer
533
+ // couldn't decode to a typed ref (filter.ts's leftDescriptor, matching the
534
+ // UNRESOLVED_REFERENCE_MARKER case) - reproduces the original value_reference
535
+ // string verbatim rather than dispatching on a type that was never captured.
536
+ if (isObject(value) && typeof value.__rawFilterReference === "string")
537
+ return value.__rawFilterReference;
538
+ if (!isObject(value) || typeof value.type !== "string") {
539
+ throw new EntityTfError("invalid automation filter reference");
540
+ }
541
+ switch (value.type.toUpperCase()) {
542
+ case "TRIGGER": {
543
+ if (typeof value.name !== "string")
544
+ throw new EntityTfError("trigger filter reference has no name");
545
+ // ei's dialect encodes a FILTER's reference to a trigger-record field as
546
+ // a plain "trigger.record.<fieldId>[.<suffix>]" string — a different
547
+ // convention from the `.refs[...]` map lookup used for task inputs.
548
+ // Reproduce it via a template so the field id stays a real reference
549
+ // (never hardcoded), matching the actual export byte-for-byte.
550
+ const parts = value.name.split(".");
551
+ if (parts[0] === "record" && parts.length >= 2) {
552
+ const fieldKey = parts[1];
553
+ const address = refs.owner.fieldAddresses.get(fieldKey);
554
+ const suffix = parts.slice(2).join(".");
555
+ if (address !== undefined) {
556
+ return expr.template([
557
+ "trigger.record.",
558
+ addressExpr(address, ["id"]),
559
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
560
+ ]);
561
+ }
562
+ // System fields (id/title/status/createdBy/updatedBy/...) have no
563
+ // resource block of their own - ei's export addresses their id via a
564
+ // `<appTfLabel>_<field>_field_id` local instead, mirroring
565
+ // tokenToTf's plain-field-ref fallback above. Reproduce that exact
566
+ // shape rather than falling through to the generic `.refs[...]`
567
+ // lookup below - confirmed live: that resourceAttr form evaluates to
568
+ // a DIFFERENT computed JSON envelope than the plain string ei
569
+ // exports/binds in state, so every apply after a pull replanned this
570
+ // filter as a spurious in-place update.
571
+ if (SYSTEM_FIELD_KEY_SET.has(fieldKey)) {
572
+ return expr.template([
573
+ "trigger.record.",
574
+ expr.local(`${refs.owner.appTfLabel}_${tsLabelToTfLabel(fieldKey)}_field_id`),
575
+ ...(suffix.length > 0 ? [`.${suffix}`] : []),
576
+ ]);
577
+ }
578
+ // Orphaned field reference: from-tf.ts round-trips a filter
579
+ // value_reference whose field id resolves to nothing in the app
580
+ // export (deleted/recreated field - same drift class as orphaned
581
+ // picklist option ids) as the raw id verbatim, via the generic
582
+ // unresolved-path escape. There's no field to look up here either -
583
+ // pass the original wire string straight through unchanged rather
584
+ // than routing it through wireRefName, which assumes a real field key.
585
+ if (isUuid(fieldKey)) {
586
+ return `trigger.${value.name}`;
88
587
  }
89
- attrs["value"] = converted.value;
90
588
  }
91
- return { attrs };
589
+ return expr.resourceAttr(refs.trigger.type, refs.trigger.label, ["refs", { index: wireRefName(value.name, refs.owner) }]);
92
590
  }
591
+ case "TASK": {
592
+ if (typeof value.taskRefKey !== "string" || typeof value.name !== "string")
593
+ throw new EntityTfError("task filter reference is incomplete");
594
+ const task = refs.tasks.get(value.taskRefKey);
595
+ if (task === undefined)
596
+ throw new EntityTfError(`unresolved task filter ref "${value.taskRefKey}"`);
597
+ return expr.resourceAttr(task.type, task.label, ["refs", { index: value.name }]);
598
+ }
599
+ case "FOR_EACH": {
600
+ if (typeof value.forEachTaskRefKey !== "string" || typeof value.name !== "string")
601
+ throw new EntityTfError("forEach filter reference is incomplete");
602
+ const task = refs.tasks.get(value.forEachTaskRefKey);
603
+ if (task === undefined)
604
+ throw new EntityTfError(`unresolved forEach filter ref "${value.forEachTaskRefKey}"`);
605
+ return expr.resourceAttr(task.type, task.label, ["refs", { index: value.name }]);
606
+ }
607
+ case "VALUE":
608
+ return valueToTf(value.value, refs);
93
609
  default:
94
- return { unsupported: `no terraform body mapping for task kind "${typeKey}"` };
610
+ throw new EntityTfError(`unsupported filter reference type "${value.type}"`);
95
611
  }
96
612
  }
97
- /** The composite ei dialect for one automation. */
98
- export function automationToTf(entity, ctx) {
99
- if (entity.kind !== "automation") {
100
- throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}" (refName "${entity.refName}")`);
613
+ function picklistFilterValueToTf(value, field, refs) {
614
+ if (typeof value !== "string" ||
615
+ field?.__kind !== "field" ||
616
+ field.fieldType !== "PICKLIST" ||
617
+ field.options === undefined)
618
+ return undefined;
619
+ if (!field.options.includes(value)) {
620
+ // Status/dropdown options can be deleted and recreated (new ids)
621
+ // without the platform updating automations that already filtered on
622
+ // the old ones - confirmed live: a filter can reference an option id
623
+ // that matches none of the field's current live options. from-tf.ts
624
+ // already round-trips a value it can't resolve to a label as the raw
625
+ // literal string; passing a UUID-shaped one through unresolved (instead
626
+ // of throwing) lets build reproduce that exact orphaned reference
627
+ // rather than blocking on platform data it can't fix.
628
+ if (isUuid(value))
629
+ return undefined;
630
+ throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" uses unknown option ${JSON.stringify(value)}; expected one of: ${field.options.map((option) => JSON.stringify(option)).join(", ")}`);
101
631
  }
102
- const payload = entity.payload;
103
- if (payload === null || typeof payload !== "object" || typeof payload.name !== "string") {
104
- throw new EntityTfError(`automation "${entity.refName}" has no payload.name — was it built with defineAutomation?`);
105
- }
106
- const name = payload.name;
107
- const autoLabel = sanitizeName(name);
108
- const where = `automation "${name}"`;
109
- const blocks = [];
110
- // 1. elementum_automation — identity. `triggers_other_automations` is a
111
- // platform-derived flag (true iff another automation calls this one);
112
- // Phase 1 authors a single, uncalled automation, so it is false.
113
- blocks.push({
114
- kind: "resource",
115
- type: AUTOMATION_RESOURCE_TYPE,
116
- label: autoLabel,
117
- attrs: {
118
- app_id: expr.resourceAttr(APP_RESOURCE_TYPE, ctx.appTfLabel, ["id"]),
119
- name,
120
- triggers_other_automations: false,
121
- },
122
- });
123
- // 2. the trigger — one per automation, references the automation.
124
- const trig = oneOf(payload.trigger);
125
- if (trig === undefined)
126
- throw new EntityTfError(`${where} has no trigger`);
127
- const trigRow = AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(trig.key);
128
- if (trigRow?.implemented !== true) {
129
- throw new EntityTfError(`${where}: trigger "${trig.key}" is not carried by the terraform path yet (Phase 1 supports onDemand)`);
130
- }
131
- const triggerType = trigRow.resourceType;
132
- const triggerAttrs = { automation: bareRef(AUTOMATION_RESOURCE_TYPE, autoLabel) };
133
- // onDemand parameter declarations live ON the trigger resource
134
- // (parameters = [{name, type, required, multiple, default_value}]).
135
- const wireInputs = trig.body["inputs"] ?? [];
136
- if (wireInputs.length > 0) {
137
- triggerAttrs["parameters"] = wireInputs.map((i) => {
138
- // The tf schema takes the lowercase authoring alias ("text"), not the
139
- // wire form ("TEXT"); wire "BOOL" is the alias "boolean".
140
- const wireType = String(i["type"] ?? "TEXT").toLowerCase();
141
- const param = {
142
- name: String(i["name"] ?? ""),
143
- type: wireType === "bool" ? "boolean" : wireType,
144
- required: i["required"] === true,
145
- multiple: i["multiple"] === true,
632
+ if (field.parent !== undefined && (field.parent !== refs.owner.appRefName || field.parentKind === "element")) {
633
+ // The options-by-label local only exists for a field owned by THIS
634
+ // automation's own app — `appendFieldLocals` (field/locals.ts) only
635
+ // walks the current stream root's own field resources, and there is no
636
+ // `data.elementum_field`-style lookup for a foreign aspect's option
637
+ // label → id mapping. Building the same local reference here would
638
+ // point at a local that plan/apply can never resolve ("reference to
639
+ // undeclared local value") instead of failing at build time, where the
640
+ // problem is actually diagnosable.
641
+ throw new EntityTfError(`automation filter for picklist field "${field.name ?? field.refName}" belongs to a foreign ${field.parentKind ?? "app"} ("${field.parent}") — filtering a foreign picklist field by option label is not supported on the terraform path yet; filter by option id instead`);
642
+ }
643
+ const localName = field.tags?.includes("STATUS")
644
+ ? `${refs.owner.appTfLabel}_status_options_by_label`
645
+ : field.tags?.includes("STAGE")
646
+ ? `${refs.owner.appTfLabel}_stage_options_by_label`
647
+ : `${scopedLabel(refs.owner.appTfLabel, tsLabelToTfLabel(field.refName))}_options_by_label`;
648
+ return expr.local(localName, [{ index: value }]);
649
+ }
650
+ function filterValueToTf(value, refs, field) {
651
+ if (!isObject(value) || typeof value.type !== "string")
652
+ return valueToTf(value, refs);
653
+ const type = value.type.toLowerCase();
654
+ const result = { type };
655
+ if (value.realType !== undefined)
656
+ result.real_type = String(value.realType).toLowerCase();
657
+ if (type === "current_user" && typeof value.currentUserType === "string") {
658
+ result.current_user_type = value.currentUserType;
659
+ }
660
+ if (value.value !== undefined) {
661
+ // The provider's `filter.value` schema splits "static" from "dynamic"
662
+ // across two distinct attributes — `value` vs `value_reference` — same
663
+ // split `left_value` already respects just above. A reference-typed
664
+ // value belongs under `value_reference`; the provider rejects it under
665
+ // `value` ("value_reference is required for reference type").
666
+ if (type === "reference") {
667
+ result.value_reference = filterReferenceToTf(value.value, refs);
668
+ }
669
+ else {
670
+ result.value = picklistFilterValueToTf(value.value, field, refs) ?? valueToTf(value.value, refs);
671
+ }
672
+ }
673
+ return result;
674
+ }
675
+ function fieldFromFilterLeftValue(value, refs) {
676
+ if (!isObject(value) || !isObject(value.value) || value.value.type?.toString().toUpperCase() !== "TRIGGER") {
677
+ return undefined;
678
+ }
679
+ const name = value.value.name;
680
+ if (typeof name !== "string")
681
+ return undefined;
682
+ const path = name.split(".");
683
+ if (path[0] !== "record" || path.length < 2)
684
+ return undefined;
685
+ const refName = path[1];
686
+ const metadata = refs.owner.fieldMetadata.get(refName);
687
+ if (metadata === undefined)
688
+ return undefined;
689
+ return { __kind: "field", refName, ...metadata };
690
+ }
691
+ function filterToTf(value, refs) {
692
+ if (!isObject(value) || typeof value.type !== "string")
693
+ throw new EntityTfError("invalid automation filter");
694
+ const result = { type: value.type.toLowerCase() };
695
+ const field = token(value.field) ?? fieldFromFilterLeftValue(value.leftValue, refs);
696
+ for (const [key, child] of Object.entries(value)) {
697
+ if (key === "type")
698
+ continue;
699
+ if (key === "field") {
700
+ result.field_id = valueToTf(child, refs);
701
+ continue;
702
+ }
703
+ if (key === "leftValue") {
704
+ if (!isObject(child))
705
+ throw new EntityTfError("invalid filter leftValue");
706
+ result.left_value = {
707
+ value_reference: filterReferenceToTf(child.value, refs),
708
+ ...(child.realType !== undefined ? { real_type: String(child.realType).toLowerCase() } : {}),
146
709
  };
147
- // Wire default is a typed envelope ({text: "..."} etc.) — the tf attr is
148
- // the bare string.
149
- const dv = i["defaultValue"];
150
- if (dv !== null && typeof dv === "object") {
151
- const inner = Object.values(dv)[0];
152
- if (inner !== undefined)
153
- param["default_value"] = String(inner);
154
- }
155
- return param;
156
- });
710
+ continue;
711
+ }
712
+ if (key === "children") {
713
+ if (!Array.isArray(child))
714
+ throw new EntityTfError("filter children must be an array");
715
+ result.children = child.map((item) => filterToTf(item, refs));
716
+ continue;
717
+ }
718
+ if (key === "value") {
719
+ result.value = filterValueToTf(child, refs, field);
720
+ continue;
721
+ }
722
+ if (key === "values") {
723
+ if (!Array.isArray(child))
724
+ throw new EntityTfError("filter values must be an array");
725
+ result.values = child.map((item) => filterValueToTf(item, refs, field));
726
+ continue;
727
+ }
728
+ if (key === "mode") {
729
+ if (typeof child !== "string")
730
+ throw new EntityTfError("filter mode must be a string");
731
+ result.mode = child.toLowerCase();
732
+ continue;
733
+ }
734
+ result[snake(key)] = valueToTf(child, refs);
157
735
  }
158
- if (trig.body["showTriggeredBy"] === true)
159
- triggerAttrs["show_triggered_by"] = true;
160
- blocks.push({ kind: "resource", type: triggerType, label: autoLabel, attrs: triggerAttrs });
161
- // Value-reference conversion context, shared by task bodies + outputs.
162
- const refCtx = {
163
- autoLabel,
164
- triggerType,
165
- paramNames: wireInputs.map((i) => String(i["name"] ?? "")).filter((n) => n !== ""),
166
- taskType: (refKey) => {
167
- const entry = (payload.tasks ?? []).find((t) => t.refKey === refKey);
168
- const kind = entry !== undefined ? oneOf(entry.task)?.key : undefined;
169
- const row = kind !== undefined ? AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(kind) : undefined;
170
- return row?.implemented === true ? row.resourceType : undefined;
171
- },
172
- taskResultProps: (refKey) => {
173
- const entry = (payload.tasks ?? []).find((t) => t.refKey === refKey);
174
- const schema = entry !== undefined ? oneOf(entry.task)?.body["outputSchema"] : undefined;
175
- return (schema?.object?.properties ?? [])
176
- .map((prop) => Object.values(prop)[0]?.name)
177
- .filter((n) => typeof n === "string");
178
- },
179
- variableById: indexVariableIds(payload.tasks ?? []),
180
- };
181
- // 3. tasks — parent-chained. First task's parent is the trigger; each
182
- // subsequent task's parent is its predecessor. Ordering IS the payload's
183
- // task array order.
184
- let parentType = triggerType;
185
- let parentLabel = autoLabel;
186
- const taskRefs = [];
187
- const usedTaskLabels = new Map();
188
- for (const t of payload.tasks ?? []) {
189
- const one = oneOf(t.task);
190
- const refKey = typeof t.refKey === "string" ? t.refKey : one !== undefined ? String(one.body.name ?? "") : "";
191
- if (one === undefined || refKey === "") {
192
- ctx.diagnostics.push(`${where}: a task has no recognizable body/refKey; dropped`);
736
+ // The platform silently defaults an unset LIKE mode to "legacy" and always
737
+ // echoes it back on export — emit it explicitly so build and export stay
738
+ // byte-fidelity equal instead of one omitting an attribute the other sets.
739
+ if (result.type === "like" && result.mode === undefined)
740
+ result.mode = "legacy";
741
+ return result;
742
+ }
743
+ function configAttrs(kind, config, refs) {
744
+ const attrs = {};
745
+ for (const [key, raw] of Object.entries(config)) {
746
+ if (key === "name" || key === "type" || key === "aspectId" && kind.endsWith("_trigger"))
747
+ continue;
748
+ // A config value of exactly `undefined` almost always means the
749
+ // authoring builder was called with a required option omitted (e.g. a
750
+ // TS-only-enforced field that jiti/bun never actually type-checks at
751
+ // build time) - name the wire key here, since the generic valueToTf
752
+ // fallback below has no attribute name to report by the time it gets to
753
+ // its own "unsupported value" throw.
754
+ if (raw === undefined) {
755
+ throw new EntityTfError(`${kind}: config value for "${key}" is undefined — likely a missing required option on the authoring builder call that built this task/trigger`);
756
+ }
757
+ // elementum_create_record_task has no "relate to record" boolean
758
+ // attribute - relate_to_record_reference's presence alone conveys the
759
+ // intent (see from-tf.ts's matching comment), so the flag itself is
760
+ // never emitted.
761
+ if (key === "relateToRecord")
762
+ continue;
763
+ if (key === "recordReference" && kind === "elementum_create_record_task") {
764
+ attrs.relate_to_record_reference = valueToTf(raw, refs);
193
765
  continue;
194
766
  }
195
- if (t.children !== undefined) {
196
- ctx.diagnostics.push(`${where}: task "${refKey}" has operator children (forEach/forkJoin/switch), not carried yet; dropped`);
767
+ if (key === "filter") {
768
+ attrs.filter = filterToTf(raw, refs);
197
769
  continue;
198
770
  }
199
- const row = AUTOMATION_SUB_TYPE_BY_TYPE_KEY.get(one.key);
200
- if (row?.implemented !== true) {
201
- ctx.diagnostics.push(`${where}: task "${refKey}" of kind "${one.key}" is not carried by the terraform path yet; dropped`);
771
+ if (key === "categorySource" && kind === "elementum_ai_classify_task") {
772
+ if (!isObject(raw))
773
+ throw new EntityTfError("invalid classification category source");
774
+ if (isObject(raw.static)) {
775
+ const categories = raw.static.categories;
776
+ if (!Array.isArray(categories))
777
+ throw new EntityTfError("static classification categories must be an array");
778
+ attrs.categories = categories.map((item) => {
779
+ if (!isObject(item) || item.name === undefined)
780
+ throw new EntityTfError("invalid static classification category");
781
+ return {
782
+ label: valueToTf(item.name, refs),
783
+ ...(item.description !== undefined ? { description: valueToTf(item.description, refs) } : {}),
784
+ };
785
+ });
786
+ }
787
+ else {
788
+ attrs.category_source = valueToTf(raw, refs);
789
+ }
202
790
  continue;
203
791
  }
204
- const body = taskBodyAttrs(one.key, one.body, refCtx);
205
- if ("unsupported" in body) {
206
- ctx.diagnostics.push(`${where}: task "${refKey}": ${body.unsupported}; dropped`);
792
+ if (key === "fileInput" && kind === "elementum_save_attachment_task") {
793
+ if (!isObject(raw) || raw.file === undefined)
794
+ throw new EntityTfError("saveAttachment file input is invalid");
795
+ attrs.file = valueToTf(raw.file, refs);
207
796
  continue;
208
797
  }
209
- const taskType = row.resourceType;
210
- const taskLabel = `${autoLabel}_${sanitizeName(refKey)}`;
211
- if (usedTaskLabels.has(taskLabel)) {
212
- // Task names are open text, but their labels are sanitizeName(name) —
213
- // two names that sanitize identically ("My Task" / "my_task") would
214
- // collide on the tf address. Report loudly; skip the duplicate.
215
- ctx.diagnostics.push(`${where}: task "${refKey}" sanitizes to the same tf label as task "${usedTaskLabels.get(taskLabel)}" (${taskLabel}); dropped — rename one of them`);
798
+ if (key === "documentModelId") {
799
+ attrs.file_reader_id = valueToTf(raw, refs);
216
800
  continue;
217
801
  }
218
- usedTaskLabels.set(taskLabel, refKey);
219
- const displayName = typeof one.body.name === "string" ? (one.body.name) : refKey;
220
- blocks.push({
221
- kind: "resource",
222
- type: taskType,
223
- label: taskLabel,
224
- attrs: {
225
- parent: bareRef(parentType, parentLabel),
226
- name: displayName,
227
- ...body.attrs,
228
- },
229
- });
230
- taskRefs.push(bareRef(taskType, taskLabel));
231
- parentType = taskType;
232
- parentLabel = taskLabel;
233
- }
234
- // 4. elementum_workflow_publish — versions the workflow, depends on every
235
- // task, and carries the workflow's OUTPUTS ([{name, value}], each value a
236
- // refs-syntax expression).
237
- const publishAttrs = {
238
- automation: bareRef(AUTOMATION_RESOURCE_TYPE, autoLabel),
239
- workflow_revision: payload.workflowRevision ?? "1.0.0",
240
- ...(taskRefs.length > 0 ? { depends_on: taskRefs } : {}),
802
+ // aiFileAnalysis's `attachmentId` config key means the task's single
803
+ // generic `file_id` value reference (confirmed against
804
+ // ai_file_read_task_resource.go's buildAiFileReadInput/schema) - distinct
805
+ // from readFile's mutually-exclusive attachment/attachment_id/file/
806
+ // raw_text data-source union (handled separately via
807
+ // documentModelDataSource, below), which shares the wire key name.
808
+ if (key === "attachmentId" && kind === "elementum_ai_file_read_task") {
809
+ attrs.file_id = valueToTf(raw, refs);
810
+ continue;
811
+ }
812
+ if (key === "documentModelDataSource") {
813
+ if (!isObject(raw))
814
+ throw new EntityTfError("documentModel dataSource must be an object");
815
+ const entries = Object.entries(raw);
816
+ if (entries.length !== 1)
817
+ throw new EntityTfError("documentModel dataSource must have exactly one entry");
818
+ const [dsType, dsValue] = entries[0];
819
+ const attrName = dsType === "rawText" ? "raw_text" : dsType === "attachmentId" ? "attachment_id" : dsType;
820
+ attrs[attrName] = valueToTf(dsValue, refs);
821
+ continue;
822
+ }
823
+ // readFile's optional `record` has no elementum_file_reader_task
824
+ // attribute to carry it - the terraform resource's schema has no
825
+ // record-reference input at all (only the four data-source attrs) -
826
+ // dropped like other authoring knobs the terraform path doesn't model.
827
+ if (key === "recordId" && kind === "elementum_file_reader_task")
828
+ continue;
829
+ if (key === "recordId" && kind === "elementum_save_attachment_task") {
830
+ attrs.record_id = valueToTf(raw, refs);
831
+ continue;
832
+ }
833
+ if (key === "calculations" && kind === "elementum_calculation_task") {
834
+ if (!Array.isArray(raw))
835
+ throw new EntityTfError("calculations must be an array");
836
+ attrs.calculations = raw.map((item) => {
837
+ if (!isObject(item) || typeof item.name !== "string" || !isObject(item.calculationReference)) {
838
+ throw new EntityTfError("invalid calculation entry");
839
+ }
840
+ const reference = item.calculationReference;
841
+ if (!isObject(reference.templateReference))
842
+ throw new EntityTfError("calculation expression is not a template reference");
843
+ const template = reference.templateReference;
844
+ const parameters = template.parameters;
845
+ let formula;
846
+ if (template.template === "{{{p1}}}" && Array.isArray(parameters) && parameters.length === 1) {
847
+ const parameter = parameters[0];
848
+ if (!isObject(parameter) || !isObject(parameter.value) || parameter.value.name !== "p1") {
849
+ throw new EntityTfError("invalid calculation expression parameter");
850
+ }
851
+ formula = valueToTf(parameter.value.value, refs);
852
+ }
853
+ else {
854
+ formula = templateToTf(template, refs);
855
+ }
856
+ return { variable_name: item.name, formula };
857
+ });
858
+ continue;
859
+ }
860
+ if (key === "inputs" && kind === "elementum_on_demand_trigger") {
861
+ if (!Array.isArray(raw))
862
+ throw new EntityTfError("onDemand inputs must be an array");
863
+ const parameters = raw.map((input) => {
864
+ if (!isObject(input))
865
+ throw new EntityTfError("onDemand input must be an object");
866
+ return Object.fromEntries(Object.entries(input).map(([k, v]) => [
867
+ CONFIG_ATTRS[k] ?? snake(k),
868
+ valueToTf(k === "defaultValue" ? unwrapDefault(v) :
869
+ // elementum_on_demand_trigger.parameters[].type's real validator
870
+ // (on_demand_trigger_resource.go) only accepts a bare "attachment"
871
+ // - there is no "attachment_id" variant at this layer, unlike the
872
+ // WorkflowFieldType enum name (ATTACHMENT_ID) the "attachmentId"
873
+ // authoring alias otherwise maps to. A generic lowercase would
874
+ // wrongly emit "attachment_id" and fail plan/apply.
875
+ k === "type" && v === "ATTACHMENT_ID" ? "attachment" :
876
+ k === "type" && typeof v === "string" ? v.toLowerCase() : v, refs),
877
+ ]));
878
+ });
879
+ // The provider normalizes an absent parameter collection to null. An
880
+ // explicit [] therefore creates perpetual [] vs null drift after pull.
881
+ if (parameters.length > 0)
882
+ attrs.parameters = parameters;
883
+ continue;
884
+ }
885
+ if (key === "workflowFields") {
886
+ if (!Array.isArray(raw))
887
+ throw new EntityTfError("workflowFields must be an array");
888
+ attrs.fields = raw.map((field) => {
889
+ if (!isObject(field))
890
+ throw new EntityTfError("workflow field must be an object");
891
+ return {
892
+ field_id: valueToTf(field.aspectFieldId, refs),
893
+ value: valueToTf(field.valueReference, refs),
894
+ };
895
+ });
896
+ continue;
897
+ }
898
+ if (key === "outputSchema") {
899
+ attrs.output_schema = expr.jsonencode(valueToTf(raw, refs));
900
+ continue;
901
+ }
902
+ if (key === "forEach") {
903
+ attrs.list = valueToTf(raw, refs);
904
+ continue;
905
+ }
906
+ if (key === "customResponse") {
907
+ if (!isObject(raw))
908
+ throw new EntityTfError("invalid customResponse");
909
+ const encodeSection = (section) => {
910
+ if (!isObject(section))
911
+ return undefined;
912
+ const encoded = {
913
+ enabled: section.enabled === true,
914
+ format: typeof section.format === "string" ? section.format : "JSON",
915
+ body: valueToTf(section.body, refs),
916
+ };
917
+ if (typeof section.statusCode === "number")
918
+ encoded.status_code = section.statusCode;
919
+ return encoded;
920
+ };
921
+ const success = encodeSection(raw.success);
922
+ const failure = encodeSection(raw.failure);
923
+ if (success !== undefined || failure !== undefined) {
924
+ attrs.custom_response = {
925
+ ...(success !== undefined ? { success } : {}),
926
+ ...(failure !== undefined ? { failure } : {}),
927
+ };
928
+ }
929
+ continue;
930
+ }
931
+ if (key === "outputType") {
932
+ attrs.output_type = typeof raw === "string" ? raw.toUpperCase() : valueToTf(raw, refs);
933
+ continue;
934
+ }
935
+ if (key === "sourceRecordIds") {
936
+ if (Array.isArray(raw)) {
937
+ // ei exports a scalar when there is exactly one source record.
938
+ attrs.source_record_ids = raw.length === 1
939
+ ? valueToTf(raw[0], refs)
940
+ : raw.map((item) => valueToTf(item, refs));
941
+ }
942
+ else {
943
+ attrs.source_record_ids = valueToTf(raw, refs);
944
+ }
945
+ continue;
946
+ }
947
+ if (key === "create" || key === "update")
948
+ continue;
949
+ // apiRequest's bearerAuth/oauth/customBody/multipartBody (and
950
+ // basicAuth's referencePassword) all carry nested multi-word attribute
951
+ // names the provider expects snake_case (reference_token, client_id,
952
+ // content_type, attachment_id, ...) - the generic valueToTf object
953
+ // fallback below preserves nested keys verbatim, so these need the same
954
+ // explicit per-key mapping as customResponse above, not the generic path.
955
+ if (key === "basicAuth" && kind === "elementum_api_task") {
956
+ if (!isObject(raw))
957
+ throw new EntityTfError("apiRequest basicAuth must be an object");
958
+ attrs.basic_auth = {
959
+ username: valueToTf(raw.username, refs),
960
+ ...(raw.referencePassword !== undefined ? { reference_password: valueToTf(raw.referencePassword, refs) } : {}),
961
+ };
962
+ continue;
963
+ }
964
+ if (key === "bearerAuth" && kind === "elementum_api_task") {
965
+ if (!isObject(raw))
966
+ throw new EntityTfError("apiRequest bearerAuth must be an object");
967
+ attrs.bearer_auth = {
968
+ ...(raw.token !== undefined ? { token: valueToTf(raw.token, refs) } : {}),
969
+ ...(raw.referenceToken !== undefined ? { reference_token: valueToTf(raw.referenceToken, refs) } : {}),
970
+ };
971
+ continue;
972
+ }
973
+ if (key === "oauth" && kind === "elementum_api_task") {
974
+ if (!isObject(raw))
975
+ throw new EntityTfError("apiRequest oauth must be an object");
976
+ const headers = Array.isArray(raw.headers)
977
+ ? raw.headers.map((h) => {
978
+ if (!isObject(h))
979
+ throw new EntityTfError("invalid apiRequest oauth header");
980
+ return { name: valueToTf(h.name, refs), value: valueToTf(h.value, refs) };
981
+ })
982
+ : undefined;
983
+ attrs.oauth = {
984
+ request_type: valueToTf(raw.requestType, refs),
985
+ ...(raw.url !== undefined ? { url: valueToTf(raw.url, refs) } : {}),
986
+ ...(raw.clientId !== undefined ? { client_id: valueToTf(raw.clientId, refs) } : {}),
987
+ ...(raw.clientSecret !== undefined ? { client_secret: valueToTf(raw.clientSecret, refs) } : {}),
988
+ ...(headers !== undefined ? { headers } : {}),
989
+ };
990
+ continue;
991
+ }
992
+ if (key === "customBody" && kind === "elementum_api_task") {
993
+ if (!isObject(raw))
994
+ throw new EntityTfError("apiRequest customBody must be an object");
995
+ attrs.custom_body = {
996
+ content_type: valueToTf(raw.contentType, refs),
997
+ content: valueToTf(raw.content, refs),
998
+ };
999
+ continue;
1000
+ }
1001
+ if (key === "multipartBody" && kind === "elementum_api_task") {
1002
+ if (!isObject(raw) || !Array.isArray(raw.parts))
1003
+ throw new EntityTfError("apiRequest multipartBody.parts must be an array");
1004
+ attrs.multipart_body = {
1005
+ parts: raw.parts.map((part) => {
1006
+ if (!isObject(part))
1007
+ throw new EntityTfError("invalid apiRequest multipartBody part");
1008
+ return {
1009
+ name: valueToTf(part.name, refs),
1010
+ ...(part.value !== undefined ? { value: valueToTf(part.value, refs) } : {}),
1011
+ ...(part.attachment !== undefined ? { attachment: valueToTf(part.attachment, refs) } : {}),
1012
+ ...(part.attachmentId !== undefined ? { attachment_id: valueToTf(part.attachmentId, refs) } : {}),
1013
+ ...(part.file !== undefined ? { file: valueToTf(part.file, refs) } : {}),
1014
+ };
1015
+ }),
1016
+ };
1017
+ continue;
1018
+ }
1019
+ const attr = CONFIG_ATTRS[key] ?? snake(key);
1020
+ attrs[attr] = valueToTf(raw, refs);
1021
+ }
1022
+ return attrs;
1023
+ }
1024
+ /** Bare file-reader addresses referenced by any task's `file_reader_id`.
1025
+ * Stamped onto `elementum_automation.depends_on` so destroy waits for the
1026
+ * automation itself — the task→reader edge alone lets tofu destroy the
1027
+ * reader in parallel with the automation, and the platform still treats
1028
+ * the live workflow as a document-model usage. */
1029
+ function fileReaderDependsOn(blocks) {
1030
+ const seen = new Set();
1031
+ const deps = [];
1032
+ for (const block of blocks) {
1033
+ const idRef = block.attrs.file_reader_id;
1034
+ if (!isTfExpr(idRef) || idRef.$expr !== "resource-attr")
1035
+ continue;
1036
+ if (!FILE_READER_SUB_TYPE_BY_RESOURCE.has(idRef.type))
1037
+ continue;
1038
+ const key = `${idRef.type}.${idRef.label}`;
1039
+ if (seen.has(key))
1040
+ continue;
1041
+ seen.add(key);
1042
+ deps.push(expr.resourceAttr(idRef.type, idRef.label));
1043
+ }
1044
+ deps.sort((a, b) => {
1045
+ const left = a.$expr === "resource-attr" ? `${a.type}.${a.label}` : "";
1046
+ const right = b.$expr === "resource-attr" ? `${b.type}.${b.label}` : "";
1047
+ return left.localeCompare(right);
1048
+ });
1049
+ return deps;
1050
+ }
1051
+ function taskLabel(automationLabel, refKey) {
1052
+ // ei's task label is `<auto>_<sanitizeName(task name)>` (CLAUDE.md), and
1053
+ // from-tf.ts's taskRefKey either preserves the task's raw display name
1054
+ // verbatim (when it already round-trips through sanitizeName unchanged,
1055
+ // e.g. "Send_field_update") or camelCases it via tfLabelToTsLabel (e.g.
1056
+ // "notify_reviewer" -> "notifyReviewer"). sanitizeName reproduces the
1057
+ // correct tf label for BOTH forms - splitCamelCase inserts the missing
1058
+ // word boundary for the camelCase case, and is a no-op for the
1059
+ // already-separated case. snakeSlug lowercases FIRST, so it never finds a
1060
+ // boundary to split in pure camelCase input ("notifyReviewer" ->
1061
+ // "notifyreviewer", no underscore) - confirmed live: this exact mismatch
1062
+ // plans a spurious destroy+create pair on every apply.
1063
+ const normalized = sanitizeName(refKey);
1064
+ return normalized.startsWith(`${automationLabel}_`) ? normalized : `${automationLabel}_${normalized}`;
1065
+ }
1066
+ /** App-owned `defineAutomation` entity → provider HCL blocks. */
1067
+ export function automationToTf(entity, ctx) {
1068
+ const owner = {
1069
+ appRefName: ctx.appRefName ?? entity.parent,
1070
+ appTfLabel: ctx.appTfLabel,
1071
+ fieldAddresses: ctx.fieldAddresses ?? new Map(),
1072
+ fieldNames: ctx.fieldNames ?? new Map(),
1073
+ fieldMetadata: ctx.fieldMetadata ?? new Map(),
1074
+ orgRefs: ctx.orgRefs,
241
1075
  };
242
- const outputs = payload.outputProperties
243
- ?.outputs;
244
- if (outputs !== undefined && outputs.length > 0) {
245
- const converted = [];
246
- for (const o of outputs) {
247
- if (typeof o?.name !== "string")
248
- continue;
249
- const value = wireRefToTf(o.value, refCtx);
250
- if ("unsupported" in value) {
251
- ctx.diagnostics.push(`${where}: output "${o.name}": ${value.unsupported}; dropped`);
252
- continue;
1076
+ if (entity.kind !== "automation")
1077
+ throw new EntityTfError(`automationToTf expects kind "automation"; got "${entity.kind}"`);
1078
+ if (entity.parent !== owner.appRefName) {
1079
+ throw new EntityTfError("automation " + entity.refName + " is owned by " + entity.parent + ", not app " + owner.appRefName);
1080
+ }
1081
+ const payload = entity.payload;
1082
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload))
1083
+ throw new EntityTfError(`automation "${entity.refName}" has a non-object payload`);
1084
+ if (typeof payload.workflowRevision !== "string")
1085
+ throw new EntityTfError(`automation "${entity.refName}" has no workflowRevision`);
1086
+ const label = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(entity.refName));
1087
+ const automation = {
1088
+ kind: "resource",
1089
+ type: AUTOMATION_RESOURCE_TYPE,
1090
+ label,
1091
+ attrs: {
1092
+ app_id: expr.resourceAttr("elementum_app", ctx.appTfLabel, ["id"]),
1093
+ name: payload.name ?? "",
1094
+ ...(payload.description !== undefined ? { description: payload.description } : {}),
1095
+ ...(payload.triggersOtherAutomations !== undefined ? { triggers_other_automations: payload.triggersOtherAutomations } : {}),
1096
+ },
1097
+ };
1098
+ const [triggerKey, triggerConfig] = onlyEntry(payload.trigger, `automation "${entity.refName}" trigger`);
1099
+ const triggerType = TRIGGER_RESOURCES[triggerKey];
1100
+ if (triggerType === undefined)
1101
+ throw new EntityTfError(`trigger type "${triggerKey}" is not supported by the provider HCL contract`);
1102
+ const taskRefs = new Map();
1103
+ const variableById = new Map();
1104
+ const usedLabels = new Map(); // tf label → the refKey that claimed it
1105
+ const preRegister = (tasks) => {
1106
+ for (const task of tasks) {
1107
+ const refKey = task.refKey;
1108
+ if (typeof refKey !== "string" || refKey === "")
1109
+ throw new EntityTfError("automation task has no refKey");
1110
+ if (taskRefs.has(refKey))
1111
+ throw new EntityTfError(`duplicate task refKey "${refKey}"`);
1112
+ const [wireType, taskBody] = onlyEntry(task.task, "task " + refKey);
1113
+ const resourceType = wireType === "variable" ? variableTaskResourceType(taskBody, refKey) : TASK_RESOURCES[wireType];
1114
+ if (resourceType === undefined)
1115
+ throw new EntityTfError(`task type "${wireType}" is not supported by the provider HCL contract`);
1116
+ const registeredLabel = taskLabel(label, refKey);
1117
+ const collidingRefKey = usedLabels.get(registeredLabel);
1118
+ if (collidingRefKey !== undefined) {
1119
+ throw new EntityTfError(`task "${refKey}" sanitizes to the same tf label as task "${collidingRefKey}" (${registeredLabel}) — rename one of them`);
1120
+ }
1121
+ usedLabels.set(registeredLabel, refKey);
1122
+ taskRefs.set(refKey, { type: resourceType, label: registeredLabel });
1123
+ if (wireType === "variable" && Array.isArray(taskBody.create)) {
1124
+ for (const candidate of taskBody.create) {
1125
+ if (isObject(candidate) && typeof candidate.id === "string" && typeof candidate.name === "string") {
1126
+ variableById.set(candidate.id, { type: "elementum_variable_task", label: registeredLabel, name: candidate.name });
1127
+ }
1128
+ }
253
1129
  }
254
- converted.push({ name: o.name, value: value.value });
1130
+ for (const child of task.children ?? [])
1131
+ preRegister(child.tasks ?? []);
255
1132
  }
256
- if (converted.length > 0)
257
- publishAttrs["outputs"] = converted;
1133
+ };
1134
+ preRegister(payload.tasks ?? []);
1135
+ const dataBlocks = new Map();
1136
+ const refs = { trigger: { type: triggerType, label }, tasks: taskRefs, owner, dataBlocks, variableById };
1137
+ let triggerAttrs;
1138
+ try {
1139
+ triggerAttrs = configAttrs(triggerType, triggerConfig, refs);
1140
+ }
1141
+ catch (err) {
1142
+ const message = err instanceof Error ? err.message : String(err);
1143
+ throw new EntityTfError(`automation "${entity.refName}"'s ${triggerKey} trigger: ${message}`);
258
1144
  }
259
- blocks.push({
1145
+ const trigger = {
260
1146
  kind: "resource",
261
- type: WORKFLOW_PUBLISH_RESOURCE_TYPE,
262
- label: autoLabel,
263
- attrs: publishAttrs,
264
- });
265
- return { blocks, address: `${AUTOMATION_RESOURCE_TYPE}.${autoLabel}` };
1147
+ type: triggerType,
1148
+ label,
1149
+ attrs: { automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label), ...triggerAttrs },
1150
+ };
1151
+ const blocks = [automation, trigger];
1152
+ const dependencies = [expr.resourceAttr(triggerType, label)];
1153
+ const runAutomationPublishes = new Set();
1154
+ const emitTasks = (tasks, initialParent) => {
1155
+ let parent = initialParent;
1156
+ let first;
1157
+ for (const task of tasks) {
1158
+ const refKey = task.refKey;
1159
+ const [wireType, inner] = onlyEntry(task.task, `task "${refKey}"`);
1160
+ const resourceType = TASK_RESOURCES[wireType];
1161
+ const tfLabel = taskRefs.get(refKey).label;
1162
+ const displayName = typeof inner.name === "string" ? inner.name : refKey;
1163
+ let taskParent = parent;
1164
+ if (task.hclParent === "trigger") {
1165
+ taskParent = expr.resourceAttr(triggerType, label);
1166
+ }
1167
+ else if (task.hclParent !== undefined) {
1168
+ const explicitParent = taskRefs.get(task.hclParent);
1169
+ if (explicitParent === undefined) {
1170
+ throw new EntityTfError(`task "${refKey}" has unresolved explicit parent "${task.hclParent}"`);
1171
+ }
1172
+ taskParent = expr.resourceAttr(explicitParent.type, explicitParent.label);
1173
+ }
1174
+ if (wireType === "variable") {
1175
+ const variableType = variableTaskResourceType(inner, refKey);
1176
+ const isCreate = variableType === "elementum_variable_task";
1177
+ const creates = Array.isArray(inner.create) ? inner.create : [];
1178
+ const updates = Array.isArray(inner.update) ? inner.update : [];
1179
+ const item = (isCreate ? creates[0] : updates[0]);
1180
+ if (!isObject(item))
1181
+ throw new EntityTfError(`invalid setVariable item on "${refKey}"`);
1182
+ const variableAttrs = { parent: taskParent, name: displayName };
1183
+ if (isCreate) {
1184
+ if (typeof item.name !== "string" || typeof item.type !== "string")
1185
+ throw new EntityTfError(`variable task "${refKey}" requires name and type`);
1186
+ variableAttrs.variable_name = item.name;
1187
+ variableAttrs.variable_type = item.type;
1188
+ if (item.value !== undefined)
1189
+ variableAttrs.value = valueToTf(item.value, refs);
1190
+ }
1191
+ else {
1192
+ // elementum_update_variable_task's real attribute is
1193
+ // variable_reference (see from-tf.ts's matching comment).
1194
+ variableAttrs.variable_reference = valueToTf(item.variable, refs);
1195
+ variableAttrs.value = valueToTf(item.value, refs);
1196
+ }
1197
+ blocks.push({ kind: "resource", type: variableType, label: tfLabel, attrs: variableAttrs });
1198
+ const address = expr.resourceAttr(variableType, tfLabel);
1199
+ dependencies.push(address);
1200
+ first ??= address;
1201
+ parent = address;
1202
+ continue;
1203
+ }
1204
+ let taskAttrs;
1205
+ try {
1206
+ taskAttrs = configAttrs(resourceType, inner, refs);
1207
+ }
1208
+ catch (err) {
1209
+ const message = err instanceof Error ? err.message : String(err);
1210
+ throw new EntityTfError(`automation "${entity.refName}"'s task "${refKey}" (${wireType}): ${message}`);
1211
+ }
1212
+ const attrs = { parent: taskParent, name: displayName, ...taskAttrs };
1213
+ const block = { kind: "resource", type: resourceType, label: tfLabel, attrs };
1214
+ if (wireType === "runAutomation") {
1215
+ const target = token(inner.targetAutomationId) ?? (isObject(inner.targetAutomationRef) ? token(inner.targetAutomationRef.value) : undefined);
1216
+ if (target === undefined || target.__kind !== "automation")
1217
+ throw new EntityTfError(`runAutomation task "${refKey}" has an unresolved target`);
1218
+ const targetLabel = scopedLabel(owner.appTfLabel, tsLabelToTfLabel(target.refName));
1219
+ block.attrs.depends_on = [expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, targetLabel)];
1220
+ runAutomationPublishes.add(targetLabel);
1221
+ }
1222
+ blocks.push(block);
1223
+ const address = expr.resourceAttr(resourceType, tfLabel);
1224
+ dependencies.push(address);
1225
+ first ??= address;
1226
+ // Only chain linear siblings; explicit hclParent keeps parallel roots under trigger.
1227
+ if (task.hclParent === undefined)
1228
+ parent = address;
1229
+ if (wireType === "forEach") {
1230
+ const children = task.children ?? [];
1231
+ if (children.length !== 1)
1232
+ throw new EntityTfError(`forEach task "${refKey}" must have exactly one child body`);
1233
+ const childResult = emitTasks(children[0].tasks ?? [], expr.resourceAttr(resourceType, tfLabel, ["inner"]));
1234
+ if (childResult !== undefined)
1235
+ parent = childResult.terminal;
1236
+ }
1237
+ else if (wireType === "switch" || wireType === "forkJoin") {
1238
+ const children = task.children ?? [];
1239
+ if (children.length === 0)
1240
+ throw new EntityTfError(`${wireType} task "${refKey}" must have branches`);
1241
+ let previous;
1242
+ for (const [index, child] of children.entries()) {
1243
+ const branchType = wireType === "switch" ? "elementum_switch_case" : "elementum_fork_join_branch";
1244
+ // ei's own resource label follows the branch's real display text
1245
+ // (a default branch renamed "Default Path" exports as
1246
+ // "..._default_path", not a hardcoded "..._default") - confirmed live.
1247
+ const branchLabel = `${tfLabel}_${snakeSlug(child.label ?? child.defaultLabel ?? "default")}`;
1248
+ const branchAttrs = {
1249
+ [wireType === "switch" ? "switch_task" : "fork_join_task"]: address,
1250
+ label: child.label ?? child.defaultLabel ?? "Default",
1251
+ ...(previous !== undefined ? { [wireType === "switch" ? "previous_case_id" : "previous_branch_id"]: { ...previous, path: ["id"] } } : {}),
1252
+ };
1253
+ if (wireType === "switch") {
1254
+ if (child.label === null) {
1255
+ // The provider schema documents `filter`/`is_default` as
1256
+ // mutually exclusive ways to mark a switch default case, but
1257
+ // the platform doesn't retroactively normalize existing cases
1258
+ // to one shape - both are live-confirmed on real orgs for the
1259
+ // identical case pattern (#157: one org's default case carries
1260
+ // `is_default = true` with no `filter`, another's carries
1261
+ // `filter = {type:"true"}` with no `is_default`). Emitting the
1262
+ // "wrong" one for an already-adopted case proposes a spurious
1263
+ // update that provider bug #157 can't actually apply, so
1264
+ // from-tf.ts's defaultSwitchShape records which shape a pulled
1265
+ // case actually has and we reproduce it here; a
1266
+ // freshly-authored default branch (no defaultFilterMode) still
1267
+ // gets the newer is_default form.
1268
+ if (child.defaultFilterMode === "explicitTrueFilter") {
1269
+ branchAttrs.filter = { type: "true" };
1270
+ }
1271
+ else {
1272
+ branchAttrs.is_default = true;
1273
+ }
1274
+ }
1275
+ else if (child.filter !== undefined) {
1276
+ branchAttrs.filter = filterToTf(child.filter, refs);
1277
+ }
1278
+ else {
1279
+ throw new EntityTfError(`switch case ${index + 1} on "${refKey}" has no filter`);
1280
+ }
1281
+ }
1282
+ blocks.push({ kind: "resource", type: branchType, label: branchLabel, attrs: branchAttrs });
1283
+ const branchAddress = expr.resourceAttr(branchType, branchLabel);
1284
+ dependencies.push(branchAddress);
1285
+ emitTasks(child.tasks ?? [], branchAddress);
1286
+ previous = branchAddress;
1287
+ }
1288
+ }
1289
+ else if ((task.children?.length ?? 0) > 0) {
1290
+ throw new EntityTfError(`non-operator task "${refKey}" has child tasks`);
1291
+ }
1292
+ }
1293
+ return first === undefined ? undefined : { root: first, terminal: parent };
1294
+ };
1295
+ emitTasks(payload.tasks ?? [], expr.resourceAttr(triggerType, label));
1296
+ const fileReaderDeps = fileReaderDependsOn(blocks);
1297
+ if (fileReaderDeps.length > 0) {
1298
+ automation.attrs.depends_on = fileReaderDeps;
1299
+ }
1300
+ {
1301
+ const outputValues = payload.outputProperties?.outputs ?? [];
1302
+ const publish = {
1303
+ kind: "resource",
1304
+ type: WORKFLOW_PUBLISH_RESOURCE_TYPE,
1305
+ label,
1306
+ attrs: {
1307
+ automation: expr.resourceAttr(AUTOMATION_RESOURCE_TYPE, label),
1308
+ workflow_revision: payload.workflowRevision,
1309
+ ...(dependencies.length > 0 || runAutomationPublishes.size > 0
1310
+ ? { depends_on: [
1311
+ ...[...runAutomationPublishes].sort().map((target) => expr.resourceAttr(WORKFLOW_PUBLISH_RESOURCE_TYPE, target)),
1312
+ ...dependencies,
1313
+ ] }
1314
+ : {}),
1315
+ ...(outputValues.length > 0
1316
+ ? { outputs: outputValues.map((output) => {
1317
+ if (typeof output.name !== "string")
1318
+ throw new EntityTfError("automation output has no name");
1319
+ return { name: output.name, value: valueToTf(output.value, refs) };
1320
+ }) }
1321
+ : {}),
1322
+ },
1323
+ };
1324
+ blocks.push(publish);
1325
+ }
1326
+ return { blocks: [...[...dataBlocks.values()].sort((a, b) => (a.type + "." + a.label).localeCompare(b.type + "." + b.label)), ...blocks], address: AUTOMATION_RESOURCE_TYPE + "." + label };
266
1327
  }