@elementumai/edk 0.8.0-preview.11 → 0.8.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.
Files changed (165) hide show
  1. package/README.md +378 -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 +65 -2
  6. package/dist-sdk/src/catalog/from-authoring.js +6 -1
  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 +83 -6
  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 +14 -0
  14. package/dist-sdk/src/catalog/types.d.ts +60 -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 +20 -1
  21. package/dist-sdk/src/engine/build/context.d.ts +18 -0
  22. package/dist-sdk/src/engine/build/source-context.d.ts +45 -0
  23. package/dist-sdk/src/engine/build/source-context.js +23 -0
  24. package/dist-sdk/src/engine/pull/context.d.ts +15 -0
  25. package/dist-sdk/src/engine/pull/org.d.ts +10 -0
  26. package/dist-sdk/src/engine/pull/org.js +34 -4
  27. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  28. package/dist-sdk/src/engine/tf/index.js +1 -1
  29. package/dist-sdk/src/engine/tf/labels.d.ts +45 -0
  30. package/dist-sdk/src/engine/tf/labels.js +71 -0
  31. package/dist-sdk/src/entities/access-policy/build.d.ts +26 -0
  32. package/dist-sdk/src/entities/access-policy/build.js +7 -0
  33. package/dist-sdk/src/entities/access-policy/filter.d.ts +61 -0
  34. package/dist-sdk/src/entities/access-policy/filter.js +83 -0
  35. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +48 -0
  36. package/dist-sdk/src/entities/access-policy/from-tf.js +189 -0
  37. package/dist-sdk/src/entities/access-policy/module.d.ts +3 -0
  38. package/dist-sdk/src/entities/access-policy/module.js +17 -0
  39. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +36 -0
  40. package/dist-sdk/src/entities/access-policy/to-tf.js +149 -0
  41. package/dist-sdk/src/entities/access-policy/types.d.ts +4 -0
  42. package/dist-sdk/src/entities/access-policy/types.js +10 -0
  43. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.d.ts +38 -3
  44. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +199 -32
  45. package/dist-sdk/src/entities/agent/from-tf.d.ts +18 -3
  46. package/dist-sdk/src/entities/agent/from-tf.js +135 -15
  47. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  48. package/dist-sdk/src/entities/agent/module.js +8 -2
  49. package/dist-sdk/src/entities/agent/to-tf.js +62 -10
  50. package/dist-sdk/src/entities/agent/tools.d.ts +88 -9
  51. package/dist-sdk/src/entities/agent/tools.js +46 -7
  52. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +51 -4
  53. package/dist-sdk/src/entities/agent-tool/from-tf.js +131 -35
  54. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +4 -2
  55. package/dist-sdk/src/entities/agent-tool/to-tf.js +103 -17
  56. package/dist-sdk/src/entities/agent-tool/types.d.ts +5 -4
  57. package/dist-sdk/src/entities/agent-tool/types.js +38 -6
  58. package/dist-sdk/src/entities/app/build.d.ts +63 -13
  59. package/dist-sdk/src/entities/app/build.js +48 -1
  60. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +3 -0
  61. package/dist-sdk/src/entities/app/from-tf.d.ts +1 -1
  62. package/dist-sdk/src/entities/app/from-tf.js +32 -15
  63. package/dist-sdk/src/entities/app/index.d.ts +4 -1
  64. package/dist-sdk/src/entities/app/index.js +2 -1
  65. package/dist-sdk/src/entities/app/module.js +9 -2
  66. package/dist-sdk/src/entities/app/to-tf.d.ts +5 -0
  67. package/dist-sdk/src/entities/app/to-tf.js +33 -4
  68. package/dist-sdk/src/entities/automation/build.d.ts +57 -13
  69. package/dist-sdk/src/entities/automation/build.js +48 -36
  70. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +25 -8
  71. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +16 -1
  72. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +179 -43
  73. package/dist-sdk/src/entities/automation/filter.d.ts +15 -3
  74. package/dist-sdk/src/entities/automation/filter.js +12 -2
  75. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -27
  76. package/dist-sdk/src/entities/automation/from-tf.js +1229 -223
  77. package/dist-sdk/src/entities/automation/index.d.ts +4 -0
  78. package/dist-sdk/src/entities/automation/index.js +4 -0
  79. package/dist-sdk/src/entities/automation/module.js +29 -32
  80. package/dist-sdk/src/entities/automation/operators.d.ts +29 -2
  81. package/dist-sdk/src/entities/automation/operators.js +27 -1
  82. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +19 -0
  83. package/dist-sdk/src/entities/automation/output-key-wire-name.js +24 -0
  84. package/dist-sdk/src/entities/automation/script-code.d.ts +10 -21
  85. package/dist-sdk/src/entities/automation/script-code.js +272 -5
  86. package/dist-sdk/src/entities/automation/tasks.d.ts +125 -19
  87. package/dist-sdk/src/entities/automation/tasks.js +83 -15
  88. package/dist-sdk/src/entities/automation/to-tf.d.ts +10 -29
  89. package/dist-sdk/src/entities/automation/to-tf.js +1134 -231
  90. package/dist-sdk/src/entities/automation/triggers.d.ts +9 -1
  91. package/dist-sdk/src/entities/automation/types.d.ts +29 -4
  92. package/dist-sdk/src/entities/automation/types.js +76 -46
  93. package/dist-sdk/src/entities/element/build.d.ts +23 -10
  94. package/dist-sdk/src/entities/element/build.js +1 -0
  95. package/dist-sdk/src/entities/element/from-tf.d.ts +1 -1
  96. package/dist-sdk/src/entities/element/from-tf.js +18 -3
  97. package/dist-sdk/src/entities/element/index.d.ts +4 -1
  98. package/dist-sdk/src/entities/element/index.js +2 -1
  99. package/dist-sdk/src/entities/element/module.js +3 -1
  100. package/dist-sdk/src/entities/element/to-tf.js +21 -3
  101. package/dist-sdk/src/entities/field/build.d.ts +56 -13
  102. package/dist-sdk/src/entities/field/build.js +10 -0
  103. package/dist-sdk/src/entities/field/calc/runtime.js +4 -0
  104. package/dist-sdk/src/entities/field/from-tf.d.ts +5 -3
  105. package/dist-sdk/src/entities/field/from-tf.js +118 -7
  106. package/dist-sdk/src/entities/field/module.js +3 -2
  107. package/dist-sdk/src/entities/field/to-tf.d.ts +27 -9
  108. package/dist-sdk/src/entities/field/to-tf.js +62 -17
  109. package/dist-sdk/src/entities/field/types.d.ts +26 -0
  110. package/dist-sdk/src/entities/field/types.js +34 -12
  111. package/dist-sdk/src/entities/file-reader/build.d.ts +108 -50
  112. package/dist-sdk/src/entities/file-reader/build.js +23 -23
  113. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.d.ts +6 -0
  114. package/dist-sdk/src/entities/file-reader/deserializer/print-file-reader.js +109 -0
  115. package/dist-sdk/src/entities/file-reader/from-tf.d.ts +13 -0
  116. package/dist-sdk/src/entities/file-reader/from-tf.js +172 -0
  117. package/dist-sdk/src/entities/file-reader/index.d.ts +8 -3
  118. package/dist-sdk/src/entities/file-reader/index.js +7 -2
  119. package/dist-sdk/src/entities/file-reader/module.d.ts +3 -0
  120. package/dist-sdk/src/entities/file-reader/module.js +115 -0
  121. package/dist-sdk/src/entities/file-reader/to-tf.d.ts +14 -0
  122. package/dist-sdk/src/entities/file-reader/to-tf.js +84 -0
  123. package/dist-sdk/src/entities/file-reader/types.d.ts +32 -0
  124. package/dist-sdk/src/entities/file-reader/types.js +30 -0
  125. package/dist-sdk/src/entities/org/ai-provider.d.ts +13 -0
  126. package/dist-sdk/src/entities/org/ai-provider.js +46 -0
  127. package/dist-sdk/src/entities/org/connector.d.ts +8 -1
  128. package/dist-sdk/src/entities/org/connector.js +12 -14
  129. package/dist-sdk/src/entities/org/group.js +10 -1
  130. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  131. package/dist-sdk/src/entities/org/index.js +1 -0
  132. package/dist-sdk/src/entities/org/user.js +10 -1
  133. package/dist-sdk/src/entities/shared/filters/ast.d.ts +44 -9
  134. package/dist-sdk/src/entities/shared/filters/types.d.ts +1 -1
  135. package/dist-sdk/src/entities/shared/tool-field-ref.d.ts +17 -0
  136. package/dist-sdk/src/entities/shared/tool-field-ref.js +31 -0
  137. package/dist-sdk/src/entities/shared/types/field-types.d.ts +10 -1
  138. package/dist-sdk/src/entities/shared/types/field-types.js +9 -0
  139. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +19 -0
  140. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +36 -8
  141. package/dist-sdk/src/entities/skill/from-tf.js +4 -3
  142. package/dist-sdk/src/entities/skill/index.d.ts +1 -1
  143. package/dist-sdk/src/entities/skill/module.js +6 -1
  144. package/dist-sdk/src/entities/skill/to-tf.js +3 -2
  145. package/dist-sdk/src/entities/skill/tools.d.ts +25 -3
  146. package/dist-sdk/src/entities/skill/tools.js +17 -0
  147. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +15 -2
  148. package/dist-sdk/src/entities/skill-tool/from-tf.js +32 -11
  149. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +2 -0
  150. package/dist-sdk/src/entities/skill-tool/to-tf.js +32 -9
  151. package/dist-sdk/src/entities/view/from-tf.d.ts +6 -2
  152. package/dist-sdk/src/entities/view/from-tf.js +11 -9
  153. package/dist-sdk/src/entities/view/to-tf.d.ts +9 -7
  154. package/dist-sdk/src/entities/view/to-tf.js +33 -18
  155. package/dist-sdk/src/entities/view/types.d.ts +1 -1
  156. package/dist-sdk/src/entities/view/types.js +1 -1
  157. package/dist-sdk/src/graph/deferred-catalog-render.d.ts +0 -5
  158. package/dist-sdk/src/graph/deferred-catalog-render.js +1 -20
  159. package/dist-sdk/src/graph/index.d.ts +8 -0
  160. package/dist-sdk/src/graph/index.js +13 -9
  161. package/dist-sdk/src/graph/modules.js +6 -1
  162. package/dist-sdk/src/graph/types.d.ts +77 -3
  163. package/package.json +42 -14
  164. package/dist-sdk/src/entities/automation/value-ref-tf.d.ts +0 -76
  165. package/dist-sdk/src/entities/automation/value-ref-tf.js +0 -190
@@ -1,252 +1,1258 @@
1
+ import { EntityTfError } from "../../engine/entity.js";
2
+ import { OUTPUT_KEY_WIRE_NAME } from "./output-key-wire-name.js";
3
+ import { USER_FIELD_KEYS } from "../../catalog/types.js";
4
+ import { DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES, SYSTEM_FIELD_KEYS } from "../../core/system-fields.js";
5
+ import { bareChildResourceLabel, childPartFromScopedLabel, isTfExpr, sanitizeName, scopedLabelToBagKey, tfLabelToTsLabel, } from "../../engine/tf/index.js";
6
+ import { IMPLEMENTED_FILE_READER_RESOURCE_TYPES } from "../file-reader/types.js";
7
+ import { ALL_AUTOMATION_TASK_TYPE_SET, AUTOMATION_BRANCH_TYPE_SET, AUTOMATION_RESOURCE_TYPE, AUTOMATION_TRIGGER_TYPE_SET, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
8
+ const TRIGGER_KINDS = {
9
+ elementum_record_created_trigger: "recordCreate",
10
+ elementum_record_updated_trigger: "recordUpdate",
11
+ elementum_attachment_added_trigger: "attachment",
12
+ elementum_comment_added_trigger: "commentAdded",
13
+ elementum_agent_conversation_ended_trigger: "conversationEnd",
14
+ elementum_slack_message_trigger: "slackMessage",
15
+ elementum_on_demand_trigger: "onDemand",
16
+ elementum_webhook_trigger: "webhook",
17
+ elementum_email_ingestion_trigger: "emailReceived",
18
+ elementum_approval_chain_trigger: "approvalProcessStatusUpdated",
19
+ elementum_datamine_trigger: "dataMine",
20
+ elementum_survey_trigger: "surveyResponseCreate",
21
+ };
22
+ const TASK_FACTORIES = {
23
+ elementum_message_task: "postComment",
24
+ elementum_update_field_task: "updateField",
25
+ elementum_variable_task: "setVariable",
26
+ elementum_update_variable_task: "setVariable",
27
+ elementum_create_record_task: "createRecord",
28
+ elementum_record_search_task: "recordSearch",
29
+ elementum_table_records_search_task: "tableRecordsSearch",
30
+ elementum_send_email_task: "sendEmail",
31
+ elementum_initiate_call_task: "initiateCall",
32
+ elementum_approval_chain_task: "approvalChain",
33
+ elementum_approval_status_update_task: "approvalStatusUpdate",
34
+ elementum_find_related_records_task: "findRelatedRecords",
35
+ elementum_api_task: "apiRequest",
36
+ elementum_ai_agent_task: "aiAgent",
37
+ elementum_for_each_task: "forEach",
38
+ elementum_switch_task: "switchTask",
39
+ elementum_fork_join_task: "forkJoin",
40
+ elementum_add_watcher_task: "addWatcher",
41
+ elementum_notification_task: "notification",
42
+ elementum_relate_records_task: "relateRecords",
43
+ elementum_ai_classify_task: "aiClassify",
44
+ elementum_ai_summarize_task: "aiSummarize",
45
+ elementum_ai_search_table_task: "aiSearchTable",
46
+ elementum_ai_transform_task: "aiTransform",
47
+ elementum_save_attachment_task: "saveAttachment",
48
+ elementum_user_search_task: "userSearch",
49
+ elementum_calculation_task: "calculation",
50
+ elementum_execute_script_task: "executeScript",
51
+ elementum_file_reader_task: "documentModel",
52
+ elementum_procedure_task: "procedure",
53
+ elementum_run_automation_task: "runAutomation",
54
+ elementum_aspect_record_field_locking_task: "recordFieldLocking",
55
+ elementum_ai_file_read_task: "aiFileAnalysis",
56
+ };
57
+ const ATTR_TO_ARG = {
58
+ object_id: "app",
59
+ table_id: "table",
60
+ record_reference: "recordRef",
61
+ source_record_ids: "sources",
62
+ target_record_id: "target",
63
+ message_body: "body",
64
+ from_username: "fromUsername",
65
+ from_personal: "fromDisplayName",
66
+ external_emails: "toAddresses",
67
+ users: "toUsers",
68
+ groups: "toGroups",
69
+ contents: "contents",
70
+ message: "contents",
71
+ agent_id: "agent",
72
+ prompt: "prompt",
73
+ output_type: "outputType",
74
+ json_fields: "schema",
75
+ ai_provider_connector_id: "connector",
76
+ url: "url",
77
+ response_type: "responseType",
78
+ continue_on_error: "continueOnError",
79
+ search_table_id: "table",
80
+ text_to_summarize: "text",
81
+ text_to_classify: "text",
82
+ field_type: "fieldType",
83
+ category_source: "categorySource",
84
+ user_ids: "userIds",
85
+ group_ids: "groupIds",
86
+ user_value_references: "userRefs",
87
+ group_value_references: "groupRefs",
88
+ notify_watchers: "notifyWatchers",
89
+ fields_to_lock: "fieldsToLock",
90
+ fields_to_unlock: "fieldsToUnlock",
91
+ view_state: "viewState",
92
+ target_automation_id: "automation",
93
+ target_automation_ref: "automation",
94
+ dynamic_input_mappings: "inputs",
95
+ output_mappings: "outputs",
96
+ file_reader_id: "documentModel",
97
+ file_id: "attachmentId",
98
+ cloudlink_id: "cloudLinkId",
99
+ // provider schema calls this stored_function_id; the authoring option
100
+ // stayed "procedureId" (pre-dating the provider's rename) to avoid an
101
+ // unnecessary breaking change to ProcedureOptions.
102
+ stored_function_id: "procedureId",
103
+ };
104
+ function isObject(value) {
105
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !("$expr" in value);
106
+ }
1
107
  /**
2
- * Automation extraction (Phase 1). `automationFromTf` consumes the composite
3
- * HCL blocks for ONE automation (its `elementum_automation` + trigger + task
4
- * blocks + `elementum_workflow_publish`) and produces the `AutomationAst` the
5
- * existing `printAutomationV2` renders to editable `.ts`.
6
- *
7
- * Task ORDER is reconstructed by walking the `parent` chain from the trigger:
8
- * the first task's `parent` is the trigger, each subsequent task's `parent` is
9
- * its predecessor. Unimplemented trigger/task kinds are REPORTED (plan §6),
10
- * never silently dropped — but note a kind we can't reconstruct also can't be
11
- * adopted (see module.ts), so in a full pull they never reach here.
12
- *
13
- * Per the tranche's typing decision: rather than a name-allowlist drift-guard
14
- * (the agent-tool `KNOWN_TOOL_ATTRS` pattern), each IMPLEMENTED kind has its own
15
- * small typed extractor naming the wire fields it reads. The declared-only kinds
16
- * carry no extractor — they are metadata for reporting, never parsed.
108
+ * Detects a switch task's default/catch-all branch and which of the two
109
+ * mutually-exclusive wire shapes the platform is currently using to mark it.
110
+ * Both are live-confirmed on real orgs for the identical case pattern (#157:
111
+ * one org's default case carries `is_default = true` with no `filter`;
112
+ * another's carries `filter = {type:"true"}` with no `is_default`) - the
113
+ * platform doesn't retroactively normalize existing cases to one shape, so
114
+ * this is a genuine per-case fact, not just export-version drift. Returning
115
+ * which shape was found (not just a boolean) lets to-tf.ts round-trip the
116
+ * same shape back on rebuild instead of guessing, so a re-pull doesn't
117
+ * propose a spurious "update" that provider bug #157 can't actually apply.
17
118
  */
18
- import { isTfExpr, sanitizeName } from "../../engine/tf/index.js";
19
- import { tfRefToAst } from "./value-ref-tf.js";
20
- import { AUTOMATION_RESOURCE_TYPE, AUTOMATION_SUB_TYPE_BY_RESOURCE, WORKFLOW_PUBLISH_RESOURCE_TYPE, } from "./types.js";
21
- /** The wire discriminant → the printer's factory name (TASK_FACTORY_V2 keys). */
22
- const FACTORY_BY_TYPE_KEY = {
23
- executeScript: "executeScript",
24
- variable: "setVariable",
119
+ function defaultSwitchShape(block) {
120
+ if (block.attrs.is_default === true)
121
+ return "isDefault";
122
+ const filter = block.attrs.filter;
123
+ if (block.label?.endsWith("_default") === true &&
124
+ block.attrs.label === "Default" &&
125
+ isObject(filter) &&
126
+ filter.type === "true") {
127
+ return "explicitTrueFilter";
128
+ }
129
+ return undefined;
130
+ }
131
+ function resourceRef(value) {
132
+ return isTfExpr(value) && value.$expr === "resource-attr"
133
+ ? { type: value.type, label: value.label, path: value.path }
134
+ : undefined;
135
+ }
136
+ function references(value, type, label) {
137
+ const ref = resourceRef(value);
138
+ return ref?.type === type && ref.label === label;
139
+ }
140
+ function assertAllowed(block, allowed) {
141
+ for (const key of Object.keys(block.attrs)) {
142
+ if (!allowed.has(key))
143
+ throw new EntityTfError(`${block.type}.${block.label}: unsupported attribute "${key}"`);
144
+ }
145
+ }
146
+ const TRIGGER_ATTRIBUTES = new Set([
147
+ "automation", "filter", "changed_fields", "think_ui", "conversation_type",
148
+ "authenticated", "custom_response", "show_triggered_by", "parameters",
149
+ "approval_chain_template_id", "status", "datamine_id", "fire_on_alert",
150
+ "fire_on_recovery", "email_alias_id", "survey_template_id",
151
+ ]);
152
+ const TASK_ATTRIBUTES = new Set([
153
+ "parent", "name", "depends_on", "filter", "fields", "inputs", "output_schema",
154
+ "list", "code", "variable_name", "variable_type", "variable", "value",
155
+ "object_id", "table_id", "record_reference", "record_id", "source_record_ids",
156
+ "target_record_id", "message", "message_body", "body", "from_username",
157
+ "from_personal", "external_emails", "users", "groups", "attachments", "contents",
158
+ "agent_id", "prompt", "output_type", "json_fields", "ai_provider_connector_id",
159
+ "url", "response_type", "continue_on_error", "search_table_id",
160
+ "text_to_summarize", "text_to_classify", "field_type", "category_source",
161
+ "title", "user_ids", "group_ids", "user_value_references",
162
+ "group_value_references", "notify_watchers", "field_id", "user_id", "group_id",
163
+ "fields_to_lock", "fields_to_unlock", "file", "file_id", "attachment", "attachment_id", "view_state", "target_automation_id",
164
+ "target_automation_ref", "input_mappings", "dynamic_input_mappings",
165
+ "output_mappings", "file_reader_id", "raw_text", "procedure_id",
166
+ "calculations", "categories", "limit", "sort", "tag", "tags", "context", "length",
167
+ "subject", "phone_service_id", "phone_number", "default_language", "first_message",
168
+ "synchronous", "cloudlink_id", "stored_function_id", "variable_reference",
169
+ "relate_to_record_reference", "method", "parameters", "headers",
170
+ "basic_auth", "bearer_auth", "oauth", "json_body", "form_body", "custom_body", "multipart_body",
171
+ ]);
172
+ const BRANCH_ATTRIBUTES = new Set([
173
+ "switch_task", "fork_join_task", "label", "is_default", "filter",
174
+ "previous_case_id", "previous_branch_id",
175
+ ]);
176
+ const PUBLISH_ATTRIBUTES = new Set([
177
+ "automation", "workflow_revision", "depends_on", "outputs",
178
+ ]);
179
+ function appRef(appRefName) {
180
+ return { kind: "app", appHandle: appRefName };
181
+ }
182
+ // Fixed, well-known ref keys ONLY - keys derived from a field's display name
183
+ // plus a suffix (e.g. "Created By" + " Email" -> "Created By Email") must NOT
184
+ // be added here. A hardcoded flat entry here short-circuits triggerRefPath's
185
+ // field-name+suffix matching below (pathNames runs first), producing an
186
+ // invalid, un-typed property name instead of the real ["record", field.key,
187
+ // "email"] path - confirmed live: "Created by Email"/"Updated by Manager
188
+ // Email" were hardcoded this way and printed as ctx.trigger.createdByEmail /
189
+ // ctx.trigger.updatedByManagerEmail, neither of which exists on the typed
190
+ // ctx, so every pulled automation using them failed `tsc --noEmit`.
191
+ const WIRE_REF_SEGMENT_TO_TS = {
192
+ "Record": "record",
193
+ "Changed Fields": "changedFieldIds",
194
+ "All found records": "records",
195
+ "Iteration": "iteration",
196
+ "Slack Thread ID": "slackThreadId",
197
+ "Slack Channel ID": "slackChannelId",
198
+ "Message Author Email": "messageAuthorEmail",
199
+ "Message Author ID": "messageAuthorId",
200
+ "Message Author Name": "messageAuthorName",
201
+ "Message Content": "messageContent",
202
+ "Message ID": "messageId",
203
+ "Message Metadata": "messageMetadata",
25
204
  };
26
- function str(v) {
27
- return typeof v === "string" ? v : undefined;
28
- }
29
- /** Per-implemented-kind typed arg extraction (the from-tf half of the bridge). */
30
- function taskArgs(typeKey, attrs, refCtx) {
31
- switch (typeKey) {
32
- case "executeScript": {
33
- const args = { code: str(attrs["code"]) ?? "" };
34
- const rawInputs = Array.isArray(attrs["inputs"]) ? attrs["inputs"] : [];
35
- if (rawInputs.length > 0) {
36
- const inputs = {};
37
- for (const entry of rawInputs) {
38
- const inputName = str(entry?.name);
39
- if (inputName === undefined)
40
- continue;
41
- const converted = tfRefToAst((entry.value ?? ""), refCtx);
42
- if ("unsupported" in converted)
43
- return { unsupported: `input "${inputName}": ${converted.unsupported}` };
44
- inputs[inputName] = converted.ast;
45
- }
46
- args["inputs"] = inputs;
47
- }
48
- const rawSchema = attrs["output_schema"];
49
- if (rawSchema !== undefined) {
50
- // Emitted as jsonencode({object:{properties:[{string:{name}},...]}}) —
51
- // invert to the authoring alias record ({NAME: "text"|...}).
52
- const schema = (isTfExpr(rawSchema) && rawSchema.$expr === "jsonencode" ? rawSchema.value : rawSchema);
53
- const aliasByTag = { string: "text", integer: "integer", number: "number", bool: "boolean" };
54
- const outputs = {};
55
- for (const prop of schema?.object?.properties ?? []) {
56
- const tag = Object.keys(prop)[0];
57
- const propName = tag !== undefined ? prop[tag]?.name : undefined;
58
- if (tag !== undefined && typeof propName === "string")
59
- outputs[propName] = aliasByTag[tag] ?? "text";
60
- }
61
- if (Object.keys(outputs).length > 0)
62
- args["outputs"] = outputs;
205
+ const FIELD_REF_SUFFIX_FROM_WIRE = [
206
+ [" Manager Email", ["employee", "manager", "email"]],
207
+ [" Manager Name", ["employee", "manager", "name"]],
208
+ [" Manager", ["employee", "manager"]],
209
+ [" Field ID", ["fieldId"]],
210
+ // Deliberately the literal suffix text, not a camelCase "asText" segment:
211
+ // Ref<T> has no ".asText" projection anywhere in the type system (checked
212
+ // shared/ref.ts - it's a sealed brand, nothing else), so claiming one as a
213
+ // resolved identifier printed a property that could never type-check. The
214
+ // space keeps this segment identifier-unsafe, so printPathAccess's
215
+ // unresolved-segment escape (`as any` + bracket access) kicks in instead of
216
+ // printing a false, never-valid `.asText` access.
217
+ [" as text", ["as text"]],
218
+ [" Label", ["label"]],
219
+ [" Email", ["email"]],
220
+ [" Name", ["name"]],
221
+ [" ID", ["id"]],
222
+ ["", []],
223
+ ];
224
+ function pathNames(path) {
225
+ return path.map((segment) => {
226
+ const name = typeof segment === "string" ? segment : segment.index;
227
+ return WIRE_REF_SEGMENT_TO_TS[name] ?? name;
228
+ });
229
+ }
230
+ /**
231
+ * A webhook trigger's `body`/`headers` refs come back as "Body (Plain
232
+ * Text)"/"Headers (Content-Type)" - one wire segment naming both the
233
+ * top-level property (always "body"/"headers", both typed
234
+ * `Record<string, unknown>` on WebhookTriggerOutput) and an arbitrary
235
+ * sub-key. Splitting it lets the sub-key print as a plain bracket access on
236
+ * an already string-indexable type, instead of a false top-level property
237
+ * like `ctx.trigger["Body (Plain Text)"]` that WebhookTriggerOutput never
238
+ * declares. Gated on the trigger's actual resource type, not just the
239
+ * string shape - a different trigger's field could otherwise coincidentally
240
+ * be named "Body (something)" and get misinterpreted as this webhook-only
241
+ * convention.
242
+ */
243
+ const WEBHOOK_REF_PATTERN = /^(Body|Headers) \((.+)\)$/;
244
+ function triggerRefPath(path, ctx) {
245
+ const names = pathNames(path);
246
+ if (names.length !== 1)
247
+ return names;
248
+ const wireName = names[0];
249
+ if (ctx.trigger.type === "elementum_webhook_trigger") {
250
+ const webhookMatch = WEBHOOK_REF_PATTERN.exec(wireName);
251
+ if (webhookMatch)
252
+ return [webhookMatch[1].toLowerCase(), webhookMatch[2]];
253
+ }
254
+ // Case-insensitive: the platform re-cases "By" to "by" when building some
255
+ // compound ref phrases (e.g. field "Created By" -> ref key "Created by
256
+ // Email"), so a case-sensitive compare against the field's own display
257
+ // name misses the match entirely.
258
+ const wireNameLower = wireName.toLowerCase();
259
+ for (const field of ctx.fieldById.values()) {
260
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
261
+ if (wireNameLower === `${field.name}${suffix}`.toLowerCase()) {
262
+ return ["record", field.key, ...suffixPath];
63
263
  }
64
- return { args };
65
264
  }
66
- case "variable": {
67
- // One variable per tf task: variable_name/variable_type/value.
68
- const decl = {
69
- name: str(attrs["variable_name"]) ?? "",
70
- type: str(attrs["variable_type"]) ?? "TEXT",
71
- };
72
- if (attrs["value"] !== undefined) {
73
- const converted = tfRefToAst(attrs["value"], refCtx);
74
- if ("unsupported" in converted)
75
- return { unsupported: `variable value: ${converted.unsupported}` };
76
- decl["value"] = converted.ast;
265
+ }
266
+ // System fields (id/title/status/stage/createdBy/updatedBy/...) have no
267
+ // `*_field` resource block of their own - they're elementum_app computed
268
+ // attributes, so they never appear in ctx.fieldById. Try their canonical
269
+ // bag keys against the provider's default display name too (e.g.
270
+ // "Created By" + " Email"). A renamed system field's ref key won't match
271
+ // here and falls through to the raw-name fallback below - no worse than
272
+ // today, since system fields were never matched at all before this.
273
+ for (const key of SYSTEM_FIELD_KEYS) {
274
+ const defaultName = DEPLOY_DEFAULT_SYSTEM_FIELD_NAMES[key];
275
+ for (const [suffix, suffixPath] of FIELD_REF_SUFFIX_FROM_WIRE) {
276
+ if (wireNameLower === `${defaultName}${suffix}`.toLowerCase()) {
277
+ return ["record", key, ...suffixPath];
77
278
  }
78
- return { args: { create: [decl] } };
79
279
  }
80
- default:
81
- return { args: {} };
82
280
  }
281
+ return names;
83
282
  }
84
- /** Wire parameter type ("TEXT") → the authoring alias ("text"). */
85
- function paramTypeAlias(wireType) {
86
- const lower = wireType.toLowerCase();
87
- return lower === "bool" ? "boolean" : lower;
283
+ function decodeReferenceString(value, ctx) {
284
+ const pieces = value.split(".");
285
+ if (pieces[0] === "trigger" && pieces.length > 1) {
286
+ const path = pieces.slice(1);
287
+ if (path[0] === "record" && path.length >= 2 && /^[a-f0-9-]{36}$/.test(path[1])) {
288
+ const sourceFieldId = path[1];
289
+ const field = ctx.fieldById.get(sourceFieldId);
290
+ // Orphaned: the field this filter's value_reference points at no
291
+ // longer exists in the app export at all (deleted/recreated field,
292
+ // same drift class as the orphaned picklist option ids and skill_ids
293
+ // fixed elsewhere) - confirmed live: a switch_case filter can
294
+ // reference a field id no custom or system field resolves to.
295
+ // Round-trip the raw id verbatim (printPathAccess's existing "as any"
296
+ // unresolved-segment escape already degrades a non-identifier path
297
+ // segment like this one) rather than throwing and losing the whole
298
+ // automation.
299
+ return { kind: "triggerRef", path: ["record", field?.key ?? sourceFieldId, ...path.slice(2)] };
300
+ }
301
+ return { kind: "triggerRef", path };
302
+ }
303
+ if (pieces[0] === "task" && pieces.length > 2)
304
+ return { kind: "taskRef", task: pieces[1], path: pieces.slice(2) };
305
+ return undefined;
88
306
  }
89
- /** Build the `TriggerAst` for an implemented trigger block. */
90
- function triggerAst(typeKey, attrs) {
91
- switch (typeKey) {
92
- case "onDemand": {
93
- const params = Array.isArray(attrs["parameters"]) ? attrs["parameters"] : [];
94
- const inputs = params
95
- .map((p) => {
96
- const name = str(p["name"]);
97
- if (name === undefined)
98
- return undefined;
307
+ /**
308
+ * Inverse of filterReferenceToTf's TRIGGER case (automation/to-tf.ts): a
309
+ * filter's value_reference for a trigger-record field renders as a template
310
+ * (`"trigger.record." + <live field ref> + ".<suffix>"?`), not a plain
311
+ * string, so decodeReferenceString never sees it. Recognize that exact shape
312
+ * and decode straight to a triggerRef, matching decodeReferenceString's
313
+ * output — anything else falls through to decodeValue's generic "template"
314
+ * kind, which refDataToFilterReference rejects (correctly, for a real
315
+ * interpolated string that isn't this specific field-address pattern).
316
+ */
317
+ function decodeTemplateTriggerRecordFieldRef(value, ctx) {
318
+ if (!isTfExpr(value) || value.$expr !== "template")
319
+ return undefined;
320
+ const [prefix, fieldPart, suffixPart] = value.parts;
321
+ if (prefix !== "trigger.record." || fieldPart === undefined || typeof fieldPart === "string")
322
+ return undefined;
323
+ if (suffixPart !== undefined && typeof suffixPart !== "string")
324
+ return undefined;
325
+ const fieldKey = fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx);
326
+ if (fieldKey === undefined)
327
+ return undefined;
328
+ const suffix = suffixPart === undefined ? [] : suffixPart.replace(/^\./, "").split(".").filter((s) => s.length > 0);
329
+ return { kind: "triggerRef", path: ["record", fieldKey, ...suffix] };
330
+ }
331
+ /**
332
+ * Resolve the field-id expression at the middle of a `trigger.record.<id>[.suffix]`
333
+ * template. A custom field's id is a `resource-attr` (`elementum_x_field.<label>.id`);
334
+ * a system field (id/title/status/createdBy/updatedBy/...) has no resource block of
335
+ * its own, so ei emits its id via a `<appTfLabel>_<field>_field_id` local instead -
336
+ * confirmed live on a switch-case condition keyed off `updatedBy`. Mirrors
337
+ * decodeValue's generic local handling, but resolves to a triggerRef bag key
338
+ * instead of a "field" RefExpr so it stays a valid filter LHS.
339
+ */
340
+ function fieldKeyFromTriggerFieldIdExpr(fieldPart, ctx) {
341
+ if (fieldPart.$expr === "resource-attr" && fieldPart.type.endsWith("_field") && fieldPart.path[0] === "id") {
342
+ return scopedLabelToBagKey(ctx.appTfLabel, fieldPart.label);
343
+ }
344
+ if (fieldPart.$expr === "local") {
345
+ const prefix = `${ctx.appTfLabel}_`;
346
+ if (fieldPart.name.startsWith(prefix) && fieldPart.name.endsWith("_field_id")) {
347
+ return tfLabelToTsLabel(fieldPart.name.slice(prefix.length, -9));
348
+ }
349
+ }
350
+ return undefined;
351
+ }
352
+ /** Same provider/model derivation as `agentFromTf` and `renderAiProvidersBag`, read off the stream's own data blocks. */
353
+ function resolveConnectorRef(connectorType, connectorLabel, ctx) {
354
+ const connectorBlock = ctx.dataBlocks.get(`${connectorType}.${connectorLabel}`);
355
+ const modelName = connectorBlock?.attrs["model_name"];
356
+ const handle = typeof modelName === "string" ? tfLabelToTsLabel(sanitizeName(modelName)) : tfLabelToTsLabel(connectorLabel);
357
+ const providerIdAttr = connectorBlock?.attrs["provider_id"];
358
+ if (providerIdAttr === undefined || !isTfExpr(providerIdAttr) || providerIdAttr.$expr !== "data-attr")
359
+ return { handle };
360
+ const providerBlock = ctx.dataBlocks.get(`${providerIdAttr.type}.${providerIdAttr.label}`);
361
+ const providerName = providerBlock?.attrs["name"];
362
+ if (typeof providerName !== "string")
363
+ return { handle };
364
+ return { handle, providerKey: tfLabelToTsLabel(sanitizeName(providerName)) };
365
+ }
366
+ function decodeValue(value, ctx) {
367
+ if (isTfExpr(value)) {
368
+ if (value.$expr === "template") {
369
+ return { kind: "template", parts: value.parts.map((part) => typeof part === "string" ? part : decodeValue(part, ctx)) };
370
+ }
371
+ if (value.$expr === "jsonencode")
372
+ return decodePlain(value.value, ctx);
373
+ if (value.$expr === "resource-attr") {
374
+ if (value.type === ctx.trigger.type && value.label === ctx.trigger.label && value.path[0] === "refs") {
375
+ return { kind: "triggerRef", path: triggerRefPath(value.path.slice(1), ctx) };
376
+ }
377
+ const task = ctx.taskByAddress.get(`${value.type}.${value.label}`);
378
+ if (task !== undefined && value.path[0] === "refs") {
379
+ const keyPath = pathNames(value.path.slice(1)).flatMap((segment) => segment.split("."));
380
+ if (task.block.type === "elementum_variable_task") {
381
+ return { kind: "variableParamRef", varTask: task.refKey, name: keyPath.join(".") };
382
+ }
383
+ // Inverse of build.ts's OUTPUT_KEY_WIRE_NAME: a single-scalar-output
384
+ // task kind's wire name (e.g. aiClassify's "Response") reads back as
385
+ // the generic `output` accessor its EDK factory actually exposes.
386
+ const taskKind = task.block.type !== undefined ? TASK_FACTORIES[task.block.type] : undefined;
387
+ const wireOutputKey = taskKind !== undefined ? OUTPUT_KEY_WIRE_NAME[taskKind] : undefined;
388
+ const outputKeyPath = wireOutputKey !== undefined && keyPath[0] === wireOutputKey
389
+ ? ["output", ...keyPath.slice(1)]
390
+ : keyPath;
391
+ return { kind: "taskRef", task: task.refKey, path: outputKeyPath };
392
+ }
393
+ if (value.type === "elementum_app" && value.label === ctx.appTfLabel && value.path[0] === "id")
394
+ return appRef(ctx.appRefName);
395
+ if (value.type.endsWith("_field") && value.path[0] === "id") {
396
+ return {
397
+ kind: "field",
398
+ appHandle: ctx.appRefName,
399
+ fieldKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
400
+ };
401
+ }
402
+ if (value.type === AUTOMATION_RESOURCE_TYPE && value.path[0] === "id") {
403
+ return {
404
+ kind: "automation",
405
+ appHandle: ctx.appRefName,
406
+ automationKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
407
+ };
408
+ }
409
+ if (value.type === "elementum_agent" && value.path[0] === "id") {
410
+ return { kind: "agent", appHandle: ctx.appRefName, agentKey: scopedLabelToBagKey(ctx.appTfLabel, value.label), name: value.label };
411
+ }
412
+ // IMPLEMENTED only, not ALL: a readFile task can reference an
413
+ // unimplemented reader type (ai/xml) - fileReaderFromTf correctly
414
+ // excludes those from extraction (no catalog entry is ever printed for
415
+ // them), so accepting the reference here would print a
416
+ // catalog.<app>.fileReaders.<key> access to a key that will never
417
+ // exist. Falling through to the throw below instead routes through
418
+ // automationOwnedAddresses (via extractAutomations' catch), which
419
+ // excludes the automation's FULL graph from adoption - not just this
420
+ // reference - the same safety net already proven for other
421
+ // unreconstructable references.
422
+ if (IMPLEMENTED_FILE_READER_RESOURCE_TYPES.includes(value.type) && value.path[0] === "id") {
423
+ return {
424
+ kind: "documentModel",
425
+ appHandle: ctx.appRefName,
426
+ documentModelKey: scopedLabelToBagKey(ctx.appTfLabel, value.label),
427
+ };
428
+ }
429
+ if (value.type === "elementum_approval_process" && value.path[0] === "id") {
430
+ const bare = bareChildResourceLabel(ctx.appTfLabel, value.label);
431
+ const unresolvedId = ctx.resourceImportIds.get(`${value.type}.${value.label}`);
99
432
  return {
100
- name,
101
- type: paramTypeAlias(str(p["type"]) ?? "TEXT"),
102
- ...(p["required"] === true ? { required: true } : {}),
103
- ...(p["multiple"] === true ? { multiple: true } : {}),
104
- ...(str(p["default_value"]) !== undefined ? { defaultValue: str(p["default_value"]) } : {}),
433
+ kind: "approvalChain",
434
+ appHandle: ctx.appRefName,
435
+ approvalChainKey: tfLabelToTsLabel(bare),
436
+ ...(unresolvedId !== undefined ? { unresolvedId } : {}),
105
437
  };
106
- })
107
- .filter((p) => p !== undefined);
438
+ }
439
+ throw new EntityTfError(`unreconstructable resource reference ${value.type}.${value.label}`);
440
+ }
441
+ if (value.$expr === "data-attr" && (value.type === "elementum_app" || value.type === "elementum_element") && value.path[0] === "id") {
442
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
443
+ const name = lookup?.attrs.name;
444
+ return {
445
+ kind: "app",
446
+ appHandle: tfLabelToTsLabel(value.label),
447
+ entityType: value.type === "elementum_element" ? "element" : "app",
448
+ ...(typeof name === "string" ? { name } : {}),
449
+ };
450
+ }
451
+ if (value.$expr === "data-attr" && value.type === "elementum_ai_provider_connector" && value.path[0] === "id") {
452
+ return { kind: "connector", id: "", ...resolveConnectorRef(value.type, value.label, ctx) };
453
+ }
454
+ if (value.$expr === "data-attr" && value.type === "elementum_cloudlink" && value.path[0] === "id") {
455
+ const lookup = ctx.dataBlocks.get(`${value.type}.${value.label}`);
456
+ const name = lookup?.attrs.name;
108
457
  return {
109
- kind: "onDemand",
110
- inputs,
111
- ...(attrs["show_triggered_by"] === true ? { showTriggeredBy: true } : {}),
458
+ kind: "cloudLink",
459
+ handle: tfLabelToTsLabel(value.label),
460
+ ...(typeof name === "string" ? { name } : {}),
112
461
  };
113
462
  }
114
- default:
463
+ if (value.$expr === "local") {
464
+ const prefix = `${ctx.appTfLabel}_`;
465
+ if (value.name.startsWith(prefix) && value.name.endsWith("_field_id")) {
466
+ return { kind: "field", appHandle: ctx.appRefName, fieldKey: tfLabelToTsLabel(value.name.slice(prefix.length, -9)) };
467
+ }
468
+ // Outside filter values, preserve option lookups as an explicit local
469
+ // reference. Filters intentionally collapse the same expression to its
470
+ // readable label in filterValue(); task field assignments must retain
471
+ // the exact lookup so build reproduces the exported HCL.
472
+ if (picklistOptionLabel(value) !== undefined) {
473
+ return { kind: "localRef", localName: value.name, path: value.path };
474
+ }
475
+ throw new EntityTfError(`unreconstructable local reference local.${value.name}`);
476
+ }
477
+ throw new EntityTfError(`unsupported expression kind "${value.$expr}" in automation`);
478
+ }
479
+ if (Array.isArray(value))
480
+ return value.map((item) => decodeValue(item, ctx));
481
+ if (isObject(value))
482
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, decodeValue(child, ctx)]));
483
+ return { kind: "literal", value };
484
+ }
485
+ function decodePlain(value, ctx) {
486
+ const decoded = decodeValue(value, ctx);
487
+ if (isObject(decoded) && typeof decoded.kind === "string")
488
+ return decoded;
489
+ if (Array.isArray(decoded))
490
+ return decoded;
491
+ if (isObject(decoded))
492
+ return Object.fromEntries(Object.entries(decoded).map(([key, child]) => [key, decodePlain(child, ctx)]));
493
+ return decoded;
494
+ }
495
+ function decodeCustomResponse(value, ctx) {
496
+ if (!isObject(value))
497
+ throw new EntityTfError("invalid custom_response");
498
+ const decodeSection = (section) => {
499
+ if (!isObject(section))
115
500
  return undefined;
501
+ const format = typeof section.format === "string" ? section.format : "JSON";
502
+ // The provider contract stores webhook bodies as strings, including JSON
503
+ // strings. Decoding a plain string as a generic automation value wraps it
504
+ // in a literal RefExpr; stringifying that wrapper on every pull grows an
505
+ // additional { kind: "literal", value: ... } layer each round trip.
506
+ const bodyValue = typeof section.body === "string"
507
+ ? section.body
508
+ : section.body !== undefined ? decodeValue(section.body, ctx) : "";
509
+ const body = typeof bodyValue === "string" ? bodyValue : JSON.stringify(bodyValue);
510
+ return {
511
+ enabled: section.enabled === true,
512
+ format: format,
513
+ ...(typeof section.status_code === "number" ? { statusCode: section.status_code } : {}),
514
+ body,
515
+ };
516
+ };
517
+ const success = decodeSection(value.success);
518
+ const failure = decodeSection(value.failure);
519
+ if (success === undefined && failure === undefined)
520
+ return undefined;
521
+ return { ...(success !== undefined ? { success } : {}), ...(failure !== undefined ? { failure } : {}) };
522
+ }
523
+ function fieldRef(value, ctx) {
524
+ const decoded = decodeValue(value, ctx);
525
+ if (isObject(decoded) && decoded.kind === "field")
526
+ return decoded;
527
+ if (typeof value === "string")
528
+ return { kind: "unresolved", uuid: value, hint: "field" };
529
+ throw new EntityTfError("field reference cannot be reconstructed");
530
+ }
531
+ const USER_FIELD_KEY_SET = new Set(USER_FIELD_KEYS);
532
+ function userFieldRef(value, ctx) {
533
+ if (typeof value === "string" && USER_FIELD_KEY_SET.has(value)) {
534
+ return { kind: "userField", fieldKey: value };
116
535
  }
536
+ return fieldRef(value, ctx);
537
+ }
538
+ function picklistOptionLabel(value) {
539
+ if (value === undefined || !isTfExpr(value) || value.$expr !== "local" || value.path.length !== 1)
540
+ return undefined;
541
+ const segment = value.path[0];
542
+ const isOptionsLookup = value.name.endsWith("_options_by_label") || value.name.endsWith("_option_ids_by_label");
543
+ return isOptionsLookup &&
544
+ typeof segment === "object" &&
545
+ segment !== null &&
546
+ "index" in segment &&
547
+ typeof segment.index === "string"
548
+ ? segment.index
549
+ : undefined;
550
+ }
551
+ // The platform emits a system-stage filter as a KEY-keyed local
552
+ // `<appTfLabel>_stage_ids_by_key["<stageKey>"]` (unlike status/dropdown, which are
553
+ // LABEL-keyed). Resolve the key against the app's reconstructed stages so the filter
554
+ // decodes to the stage name instead of leaking the raw local expression (#116).
555
+ function stageFilterName(value, ctx) {
556
+ if (value === undefined || !isTfExpr(value) || value.$expr !== "local" || value.path.length !== 1)
557
+ return undefined;
558
+ if (value.name !== `${ctx.appTfLabel}_stage_ids_by_key`)
559
+ return undefined;
560
+ const segment = value.path[0];
561
+ if (typeof segment !== "object" || segment === null || !("index" in segment) || typeof segment.index !== "string")
562
+ return undefined;
563
+ return ctx.stagesByKey.get(segment.index);
564
+ }
565
+ function filterValue(value, ctx) {
566
+ const directOptionLabel = picklistOptionLabel(value);
567
+ if (directOptionLabel !== undefined)
568
+ return { kind: "text", value: directOptionLabel };
569
+ const directStageName = stageFilterName(value, ctx);
570
+ if (directStageName !== undefined)
571
+ return { kind: "text", value: directStageName };
572
+ if (!isObject(value) || isTfExpr(value))
573
+ return decodeValue(value, ctx);
574
+ const type = typeof value.type === "string" ? value.type.toLowerCase() : undefined;
575
+ if (type === undefined)
576
+ return decodeValue(value, ctx);
577
+ if (type === "null")
578
+ return { kind: "null" };
579
+ if (type === "current_user") {
580
+ const raw = typeof value.current_user_type === "string" ? value.current_user_type.toLowerCase() : "id";
581
+ const currentUserType = raw === "email" || raw === "domain" ? raw : "id";
582
+ return { kind: "currentUser", currentUserType };
583
+ }
584
+ if (type === "reference")
585
+ return { kind: "reference", ref: decodeValue(value.value, ctx) };
586
+ if (["text", "number", "boolean", "uuid", "date", "datetime"].includes(type)) {
587
+ const optionLabel = picklistOptionLabel(value.value);
588
+ if (optionLabel !== undefined)
589
+ return { kind: "text", value: optionLabel };
590
+ const stageName = stageFilterName(value.value, ctx);
591
+ if (stageName !== undefined)
592
+ return { kind: "text", value: stageName };
593
+ const raw = value.value;
594
+ return { kind: type, value: raw };
595
+ }
596
+ if (type === "field")
597
+ return { kind: "reference", ref: fieldRef(value.value, ctx) };
598
+ throw new EntityTfError(`unsupported filter value type "${type}"`);
599
+ }
600
+ function decodeFilter(value, ctx, fieldScope = "app") {
601
+ if (!isObject(value) || isTfExpr(value) || typeof value.type !== "string")
602
+ throw new EntityTfError("invalid filter object");
603
+ const type = value.type.toLowerCase();
604
+ if (type === "true" || type === "false")
605
+ return { kind: type };
606
+ if (type === "and" || type === "or") {
607
+ if (!Array.isArray(value.children))
608
+ throw new EntityTfError(`${type} filter has no children`);
609
+ return { kind: type, children: value.children.map((child) => decodeFilter(child, ctx, fieldScope)) };
610
+ }
611
+ const left = value.field_id !== undefined
612
+ ? fieldScope === "user" ? userFieldRef(value.field_id, ctx) : fieldRef(value.field_id, ctx)
613
+ : isObject(value.left_value) && value.left_value.value_reference !== undefined
614
+ ? typeof value.left_value.value_reference === "string"
615
+ ? decodeReferenceString(value.left_value.value_reference, ctx)
616
+ : decodeTemplateTriggerRecordFieldRef(value.left_value.value_reference, ctx)
617
+ ?? decodeValue(value.left_value.value_reference, ctx)
618
+ : value.left_value !== undefined ? decodeValue(value.left_value, ctx) : undefined;
619
+ if (left === undefined)
620
+ throw new EntityTfError(`${type} filter has no left side`);
621
+ const not = value.not === true ? { not: true } : {};
622
+ if (type === "is_null")
623
+ return { kind: "isNull", left, ...not };
624
+ if (type === "in") {
625
+ if (!Array.isArray(value.values))
626
+ throw new EntityTfError("in filter has no values");
627
+ return { kind: "in", left, values: value.values.map((item) => filterValue(item, ctx)), ...not };
628
+ }
629
+ if (type === "between") {
630
+ if (!Array.isArray(value.values) || value.values.length !== 2)
631
+ throw new EntityTfError("between filter requires two values");
632
+ return { kind: "between", left, values: [filterValue(value.values[0], ctx), filterValue(value.values[1], ctx)], ...not };
633
+ }
634
+ const kindByType = {
635
+ equals: "eq", greater_than: "gt", greater_than_equals: "gte", less_than: "lt", less_than_equals: "lte", like: "like",
636
+ };
637
+ const kind = kindByType[type];
638
+ if (kind === undefined || value.value === undefined)
639
+ throw new EntityTfError(`unsupported filter type "${type}"`);
640
+ const right = filterValue(value.value, ctx);
641
+ return kind === "like"
642
+ ? { kind, left, right, ...not, ...(typeof value.case_insensitive === "boolean" ? { caseInsensitive: value.case_insensitive } : {}), ...(typeof value.mode === "string" ? { mode: value.mode.toLowerCase() } : {}) }
643
+ : { kind, left, right, ...not };
644
+ }
645
+ function triggerFromBlock(block, ctx) {
646
+ const kind = TRIGGER_KINDS[block.type];
647
+ if (kind === undefined)
648
+ throw new EntityTfError(`unknown trigger resource type "${block.type}"`);
649
+ const app = appRef(ctx.appRefName);
650
+ const filter = block.attrs.filter !== undefined ? decodeFilter(block.attrs.filter, ctx) : undefined;
651
+ switch (kind) {
652
+ case "onDemand": {
653
+ const parameters = block.attrs.parameters ?? [];
654
+ if (!Array.isArray(parameters))
655
+ throw new EntityTfError("on-demand parameters must be an array");
656
+ return { kind, inputs: parameters.map((parameter) => {
657
+ if (!isObject(parameter) || typeof parameter.name !== "string" || typeof parameter.type !== "string")
658
+ throw new EntityTfError("invalid on-demand parameter");
659
+ // Inverse of to-tf's "attachment" special case above — the wire has
660
+ // no "attachmentId" spelling at all, but the authoring alias
661
+ // (onDemand's TriggerFieldTypeAlias) does. Map back so printed
662
+ // source uses a type-checkable alias instead of a raw wire string
663
+ // "attachment" that TriggerFieldTypeAlias doesn't accept.
664
+ const type = parameter.type === "attachment" ? "attachmentId" : parameter.type;
665
+ return { name: parameter.name, type, ...(parameter.required === true ? { required: true } : {}), ...(parameter.multiple === true ? { multiple: true } : {}), ...(parameter.default_value !== undefined ? { defaultValue: parameter.default_value } : {}), ...(typeof parameter.description === "string" ? { description: parameter.description } : {}) };
666
+ }), ...(block.attrs.show_triggered_by === true ? { showTriggeredBy: true } : {}) };
667
+ }
668
+ case "recordCreate":
669
+ case "recordUpdate":
670
+ case "attachment":
671
+ return { kind, app, ...(filter ? { filter } : {}), ...(Array.isArray(block.attrs.changed_fields) ? { changedFields: block.attrs.changed_fields.map((item) => fieldRef(item, ctx)) } : {}), ...(typeof block.attrs.think_ui === "boolean" ? { thinkUi: block.attrs.think_ui } : {}) };
672
+ case "commentAdded":
673
+ if (typeof block.attrs.conversation_type !== "string")
674
+ throw new EntityTfError("comment trigger requires conversation_type");
675
+ return { kind, app, conversationType: block.attrs.conversation_type, ...(filter ? { filter } : {}) };
676
+ case "conversationEnd":
677
+ if (typeof block.attrs.conversation_type !== "string")
678
+ throw new EntityTfError("conversation trigger requires conversation_type");
679
+ return { kind, app, conversationType: block.attrs.conversation_type };
680
+ case "webhook":
681
+ return {
682
+ kind,
683
+ ...(typeof block.attrs.authenticated === "boolean" ? { authenticated: block.attrs.authenticated } : {}),
684
+ ...(block.attrs.custom_response !== undefined ? { customResponse: decodeCustomResponse(block.attrs.custom_response, ctx) } : {}),
685
+ };
686
+ case "approvalProcessStatusUpdated": {
687
+ if (block.attrs.approval_chain_template_id === undefined || typeof block.attrs.status !== "string")
688
+ throw new EntityTfError("approval trigger is incomplete");
689
+ const approvalChain = typeof block.attrs.approval_chain_template_id === "string"
690
+ ? block.attrs.approval_chain_template_id
691
+ : decodeValue(block.attrs.approval_chain_template_id, ctx);
692
+ if (typeof approvalChain !== "string" && (!isObject(approvalChain) || approvalChain.kind !== "approvalChain")) {
693
+ throw new EntityTfError("approval trigger has an unreconstructable approval chain");
694
+ }
695
+ return { kind, app, approvalChain: approvalChain, status: block.attrs.status };
696
+ }
697
+ case "dataMine":
698
+ if (typeof block.attrs.datamine_id !== "string")
699
+ throw new EntityTfError("datamine trigger requires datamine_id");
700
+ return { kind, datamineId: block.attrs.datamine_id, ...(typeof block.attrs.fire_on_alert === "boolean" ? { fireOnAlert: block.attrs.fire_on_alert } : {}), ...(typeof block.attrs.fire_on_recovery === "boolean" ? { fireOnRecovery: block.attrs.fire_on_recovery } : {}) };
701
+ case "emailReceived":
702
+ if (typeof block.attrs.email_alias_id !== "string")
703
+ throw new EntityTfError("email trigger requires email_alias_id");
704
+ return { kind, emailAliasId: block.attrs.email_alias_id };
705
+ case "slackMessage": return { kind };
706
+ case "surveyResponseCreate":
707
+ if (typeof block.attrs.survey_template_id !== "string")
708
+ throw new EntityTfError("survey trigger requires survey_template_id");
709
+ return { kind, app, survey: block.attrs.survey_template_id };
710
+ default: throw new EntityTfError(`trigger "${kind}" is outside the Terraform contract`);
711
+ }
712
+ }
713
+ function taskArgs(block, factory, ctx) {
714
+ const args = {};
715
+ for (const [attr, value] of Object.entries(block.attrs)) {
716
+ if (attr === "parent" || attr === "name" || attr === "depends_on")
717
+ continue;
718
+ if (attr === "filter") {
719
+ args.filter = decodeFilter(value, ctx, factory === "userSearch" ? "user" : "app");
720
+ continue;
721
+ }
722
+ if (attr === "fields" && (factory === "createRecord" || factory === "updateField")) {
723
+ if (!Array.isArray(value))
724
+ throw new EntityTfError(`${block.type}.${block.label}: fields must be an array`);
725
+ const values = {};
726
+ for (const item of value) {
727
+ if (!isObject(item) || item.field_id === undefined)
728
+ throw new EntityTfError(`${block.type}.${block.label}: invalid field assignment`);
729
+ const field = fieldRef(item.field_id, ctx);
730
+ // Unlike an orphaned TRIGGER record-path field ref (which degrades
731
+ // gracefully - see decodeReferenceString), an unresolved field_id
732
+ // here means ei's own export couldn't resolve the field either (most
733
+ // commonly: a createRecord/updateField task targets a FOREIGN app via
734
+ // object_id, and `--recursive=false` never discovers that app's
735
+ // fields at all). ei's raw export still writes a bare field_id string
736
+ // plus an unresolved-value placeholder (with its own "Unresolved
737
+ // value references" warning) - the live platform's Read() resolves
738
+ // the real field fine (it exists), so that placeholder permanently
739
+ // mismatches state on every plan. Nothing on the TS side can fix a
740
+ // gap in ei's own export scope, so - confirmed live against
741
+ // demoapptwo's "Create record app external" automation, whose target
742
+ // field lives on a different app - throw here (same as any other
743
+ // unreconstructable reference) so the automation's full graph is
744
+ // excluded from adoption via automationOwnedAddresses, rather than
745
+ // permanently failing the adoption gate for the whole app.
746
+ if (field.kind !== "field") {
747
+ throw new EntityTfError(`${block.type}.${block.label}: field assignment references an unresolvable field (${field.kind === "unresolved" ? field.uuid : "unknown"})`);
748
+ }
749
+ values[field.fieldKey] = decodeValue(item.value, ctx);
750
+ }
751
+ args.values = values;
752
+ continue;
753
+ }
754
+ if (attr === "inputs" && factory === "executeScript") {
755
+ if (!Array.isArray(value))
756
+ throw new EntityTfError("script inputs must be an array");
757
+ args.inputs = Object.fromEntries(value.map((item) => {
758
+ if (!isObject(item) || typeof item.name !== "string")
759
+ throw new EntityTfError("invalid script input");
760
+ return [item.name, decodeValue(item.value, ctx)];
761
+ }));
762
+ continue;
763
+ }
764
+ if (attr === "output_schema" && factory === "executeScript") {
765
+ const raw = isTfExpr(value) && value.$expr === "jsonencode" ? value.value : value;
766
+ const props = isObject(raw) && isObject(raw.object) && Array.isArray(raw.object.properties) ? raw.object.properties : [];
767
+ args.outputs = Object.fromEntries(props.map((property) => {
768
+ if (!isObject(property))
769
+ throw new EntityTfError("invalid script output schema");
770
+ const [type, definition] = Object.entries(property)[0] ?? [];
771
+ if (type === undefined || !isObject(definition) || typeof definition.name !== "string")
772
+ throw new EntityTfError("invalid script output property");
773
+ return [definition.name, type === "bool" ? "boolean" : type];
774
+ }));
775
+ continue;
776
+ }
777
+ if (attr === "calculations" && factory === "calculation") {
778
+ if (!Array.isArray(value))
779
+ throw new EntityTfError("calculations must be an array");
780
+ args.calculations = value.map((item) => {
781
+ if (!isObject(item) || typeof item.variable_name !== "string" || item.formula === undefined) {
782
+ throw new EntityTfError(`${block.type}.${block.label}: invalid calculation entry`);
783
+ }
784
+ return { name: item.variable_name, expression: decodeValue(item.formula, ctx) };
785
+ });
786
+ continue;
787
+ }
788
+ if (attr === "categories" && factory === "aiClassify") {
789
+ if (!Array.isArray(value))
790
+ throw new EntityTfError("classification categories must be an array");
791
+ args.categorySource = {
792
+ type: "static",
793
+ categories: value.map((item) => {
794
+ if (!isObject(item) || item.label === undefined)
795
+ throw new EntityTfError("invalid classification category");
796
+ return {
797
+ name: decodeValue(item.label, ctx),
798
+ ...(item.description !== undefined ? { description: decodeValue(item.description, ctx) } : {}),
799
+ };
800
+ }),
801
+ };
802
+ continue;
803
+ }
804
+ if (attr === "list" && factory === "forEach") {
805
+ args.collection = decodeValue(value, ctx);
806
+ continue;
807
+ }
808
+ if (attr === "code" && factory === "executeScript") {
809
+ args.code = value;
810
+ continue;
811
+ }
812
+ if (attr === "record_id" && factory === "saveAttachment") {
813
+ args.recordRef = decodeValue(value, ctx);
814
+ continue;
815
+ }
816
+ if (attr === "source_record_ids" && factory === "relateRecords") {
817
+ const decoded = decodeValue(value, ctx);
818
+ args.sources = Array.isArray(decoded) ? decoded : [decoded];
819
+ continue;
820
+ }
821
+ if (attr === "output_type" && factory === "aiAgent") {
822
+ args.outputType = typeof value === "string" ? value.toLowerCase() : decodeValue(value, ctx);
823
+ continue;
824
+ }
825
+ // procedure()'s wire shape wraps each positional argument as
826
+ // `{index, value}` (see tasks.ts's procedure()); ProcedureOptions.parameters
827
+ // is a plain, position-ordered array - unwrap rather than round-tripping
828
+ // the index wrapper verbatim, which procedure() doesn't accept.
829
+ if (attr === "parameters" && factory === "procedure") {
830
+ if (!Array.isArray(value))
831
+ throw new EntityTfError(`${block.type}.${block.label}: procedure parameters must be an array`);
832
+ const sorted = [...value].sort((a, b) => {
833
+ const ai = isObject(a) && typeof a.index === "number" ? a.index : 0;
834
+ const bi = isObject(b) && typeof b.index === "number" ? b.index : 0;
835
+ return ai - bi;
836
+ });
837
+ args.parameters = sorted.map((item) => {
838
+ if (!isObject(item) || item.value === undefined)
839
+ throw new EntityTfError(`${block.type}.${block.label}: invalid procedure parameter`);
840
+ return decodeValue(item.value, ctx);
841
+ });
842
+ continue;
843
+ }
844
+ // createRecord's relate-to-record feature is carried by ONE attribute on
845
+ // the wire (relate_to_record_reference) - its presence alone implies
846
+ // relateToRecord: true (the provider has no separate boolean attribute).
847
+ if (attr === "relate_to_record_reference" && factory === "createRecord") {
848
+ args.record = decodeValue(value, ctx);
849
+ args.relateToRecord = true;
850
+ continue;
851
+ }
852
+ // elementum_file_reader_task's four data-source attrs are mutually
853
+ // exclusive (the provider schema enforces exactly one) - readFile's
854
+ // authoring shape collapses them into one discriminated dataSource arg.
855
+ if (factory === "documentModel" && (attr === "raw_text" || attr === "attachment" || attr === "attachment_id" || attr === "file")) {
856
+ const type = attr === "raw_text" ? "rawText" : attr === "attachment_id" ? "attachmentId" : attr;
857
+ args.dataSource = { type, value: decodeValue(value, ctx) };
858
+ continue;
859
+ }
860
+ if (attr === "source_record_ids" && factory === "relateRecords") {
861
+ const decoded = decodeValue(value, ctx);
862
+ args.sources = Array.isArray(decoded) ? decoded : [decoded];
863
+ continue;
864
+ }
865
+ // apiRequest's bearer_auth/oauth/custom_body/multipart_body (and
866
+ // basic_auth's reference_password) carry nested multi-word wire
867
+ // attribute names - the generic decodeValue object walk below preserves
868
+ // nested keys verbatim (snake_case, as exported), so these need the
869
+ // same explicit per-key mapping as tasks.ts's matching to-tf encode.
870
+ if (attr === "basic_auth" && factory === "apiRequest") {
871
+ if (!isObject(value))
872
+ throw new EntityTfError(`${block.type}.${block.label}: basic_auth must be an object`);
873
+ args.basicAuth = {
874
+ username: decodeValue(value.username, ctx),
875
+ ...(value.reference_password !== undefined ? { referencePassword: decodeValue(value.reference_password, ctx) } : {}),
876
+ };
877
+ continue;
878
+ }
879
+ if (attr === "bearer_auth" && factory === "apiRequest") {
880
+ if (!isObject(value))
881
+ throw new EntityTfError(`${block.type}.${block.label}: bearer_auth must be an object`);
882
+ args.bearerAuth = {
883
+ ...(value.token !== undefined ? { token: value.token } : {}),
884
+ ...(value.reference_token !== undefined ? { referenceToken: decodeValue(value.reference_token, ctx) } : {}),
885
+ };
886
+ continue;
887
+ }
888
+ if (attr === "oauth" && factory === "apiRequest") {
889
+ if (!isObject(value))
890
+ throw new EntityTfError(`${block.type}.${block.label}: oauth must be an object`);
891
+ const headers = Array.isArray(value.headers)
892
+ ? value.headers.map((h) => {
893
+ if (!isObject(h))
894
+ throw new EntityTfError(`${block.type}.${block.label}: invalid oauth header`);
895
+ return { name: h.name, value: decodeValue(h.value, ctx) };
896
+ })
897
+ : undefined;
898
+ args.oauth = {
899
+ requestType: value.request_type,
900
+ ...(value.url !== undefined ? { url: decodeValue(value.url, ctx) } : {}),
901
+ ...(value.client_id !== undefined ? { clientId: value.client_id } : {}),
902
+ ...(value.client_secret !== undefined ? { clientSecret: value.client_secret } : {}),
903
+ ...(headers !== undefined ? { headers } : {}),
904
+ };
905
+ continue;
906
+ }
907
+ if (attr === "form_body" && factory === "apiRequest") {
908
+ if (!Array.isArray(value))
909
+ throw new EntityTfError(`${block.type}.${block.label}: form_body must be an array`);
910
+ args.formBody = value.map((item) => {
911
+ if (!isObject(item))
912
+ throw new EntityTfError(`${block.type}.${block.label}: invalid form_body entry`);
913
+ return { key: item.key, value: decodeValue(item.value, ctx) };
914
+ });
915
+ continue;
916
+ }
917
+ if (attr === "custom_body" && factory === "apiRequest") {
918
+ if (!isObject(value))
919
+ throw new EntityTfError(`${block.type}.${block.label}: custom_body must be an object`);
920
+ args.customBody = {
921
+ contentType: value.content_type,
922
+ content: decodeValue(value.content, ctx),
923
+ };
924
+ continue;
925
+ }
926
+ if (attr === "multipart_body" && factory === "apiRequest") {
927
+ if (!isObject(value) || !Array.isArray(value.parts))
928
+ throw new EntityTfError(`${block.type}.${block.label}: multipart_body.parts must be an array`);
929
+ args.multipartBody = {
930
+ parts: value.parts.map((part) => {
931
+ if (!isObject(part))
932
+ throw new EntityTfError(`${block.type}.${block.label}: invalid multipart_body part`);
933
+ return {
934
+ name: part.name,
935
+ ...(part.value !== undefined ? { value: decodeValue(part.value, ctx) } : {}),
936
+ ...(part.attachment !== undefined ? { attachment: decodeValue(part.attachment, ctx) } : {}),
937
+ ...(part.attachment_id !== undefined ? { attachmentId: decodeValue(part.attachment_id, ctx) } : {}),
938
+ ...(part.file !== undefined ? { file: decodeValue(part.file, ctx) } : {}),
939
+ };
940
+ }),
941
+ };
942
+ continue;
943
+ }
944
+ // elementum_notification_task's `message` wire attribute means
945
+ // notification()'s `message` option, not postComment()'s `contents` -
946
+ // ATTR_TO_ARG's message → "contents" entry is correct for
947
+ // elementum_message_task (which shares the same wire attribute name)
948
+ // but wrong here. See edk#112.
949
+ if (attr === "message" && factory === "notification") {
950
+ args.message = decodeValue(value, ctx);
951
+ continue;
952
+ }
953
+ const arg = ATTR_TO_ARG[attr] ?? attr.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
954
+ args[arg] = decodeValue(value, ctx);
955
+ }
956
+ if (["recordSearch", "createRecord", "updateField"].includes(factory))
957
+ args.app ??= appRef(ctx.appRefName);
958
+ if (factory === "findRelatedRecords") {
959
+ args.relatedApp = args.app ?? appRef(ctx.appRefName);
960
+ delete args.app;
961
+ }
962
+ if (factory === "setVariable") {
963
+ if (block.type === "elementum_variable_task") {
964
+ if (typeof block.attrs.variable_name !== "string" || typeof block.attrs.variable_type !== "string")
965
+ throw new EntityTfError("variable task is incomplete");
966
+ return { create: [{ name: block.attrs.variable_name, type: block.attrs.variable_type, ...(block.attrs.value !== undefined ? { value: decodeValue(block.attrs.value, ctx) } : {}) }] };
967
+ }
968
+ // The provider's real attribute is variable_reference (renamed from a
969
+ // prior "variable" - confirmed against update_variable_task_resource.go's
970
+ // current schema); the AST/authoring key stays "variable" (SetVariableOptions.update[].variable).
971
+ return { update: [{ variable: decodeValue(block.attrs.variable_reference, ctx), value: decodeValue(block.attrs.value, ctx) }] };
972
+ }
973
+ return args;
974
+ }
975
+ function parentAddress(block) {
976
+ const parent = resourceRef(block.attrs.parent);
977
+ if (parent === undefined)
978
+ throw new EntityTfError(`${block.type}.${block.label}: missing or invalid parent`);
979
+ const suffix = parent.path.length > 0 ? `.${pathNames(parent.path).join(".")}` : "";
980
+ return `${parent.type}.${parent.label}${suffix}`;
981
+ }
982
+ function taskRefKey(block, automationLabel, appTfLabel) {
983
+ const autoChild = childPartFromScopedLabel(appTfLabel, automationLabel, "app");
984
+ const taskChild = childPartFromScopedLabel(appTfLabel, block.label ?? "", "app");
985
+ const tail = taskChild.startsWith(`${autoChild}_`) ? taskChild.slice(autoChild.length + 1) : taskChild;
986
+ const taskName = typeof block.attrs.name === "string" ? block.attrs.name : undefined;
987
+ if (taskName !== undefined && sanitizeName(taskName) === tail && (taskName === tail || /[_\s-]/.test(taskName)))
988
+ return taskName;
989
+ return tfLabelToTsLabel(tail);
117
990
  }
118
991
  /**
119
- * Reconstruct one automation. `blocks` are the family blocks that belong to it
120
- * (already grouped by the caller: same `automation` ref / workflow_publish
121
- * depends_on set). Returns `{ automation }` or `{ skippedReason }`.
992
+ * Best-effort resource footprint of one automation, used ONLY when whole-
993
+ * automation extraction throws (module.ts's `extractAutomations` catch
994
+ * branch) so adoption can exclude the FULL graph - not just the automation
995
+ * root - from its import scope. Without this, a trigger/task/branch/publish
996
+ * address is individually still an "adoptable" resource TYPE (the kind
997
+ * works fine for OTHER automations), so it gets imported into state anyway;
998
+ * build then can't reproduce what it never wrote to source, and `plan`
999
+ * shows those addresses as destroy-on-apply (confirmed live: several
1000
+ * automations that failed extraction were imported into state anyway,
1001
+ * driving spurious destroys). Deliberately lenient - tolerant of the exact
1002
+ * conditions that make real extraction fail (zero/multiple triggers, an
1003
+ * unrecognized task kind) - so it over-collects rather than under-collects:
1004
+ * a false positive here just leaves one more resource unmanaged, a false
1005
+ * negative would silently destroy a live automation on apply.
122
1006
  */
123
- export function automationFromTf(blocks, ctx) {
124
- const automation = blocks.find((b) => b.type === AUTOMATION_RESOURCE_TYPE);
125
- if (automation === undefined || automation.label === undefined) {
126
- return { skippedReason: "no elementum_automation block in the group" };
127
- }
128
- const autoLabel = automation.label;
129
- const name = str(automation.attrs["name"]) ?? autoLabel;
130
- const where = `automation "${name}"`;
131
- // Trigger — exactly one per automation.
132
- const triggerBlock = blocks.find((b) => {
133
- const row = b.type !== undefined ? AUTOMATION_SUB_TYPE_BY_RESOURCE.get(b.type) : undefined;
134
- return row !== undefined && b.type?.endsWith("_trigger");
135
- });
136
- if (triggerBlock === undefined || triggerBlock.type === undefined) {
137
- return { skippedReason: `${where}: no trigger block` };
138
- }
139
- const triggerRow = AUTOMATION_SUB_TYPE_BY_RESOURCE.get(triggerBlock.type);
140
- if (triggerRow.implemented !== true) {
141
- ctx.diagnostics.push(`${where}: trigger kind ${triggerBlock.type} is not carried yet; skipped`);
142
- return { skippedReason: `${where}: unimplemented trigger ${triggerBlock.type}` };
143
- }
144
- const trigger = triggerAst(triggerRow.typeKey, triggerBlock.attrs);
145
- if (trigger === undefined)
146
- return { skippedReason: `${where}: no triggerAst for ${triggerRow.typeKey}` };
147
- // Tasks — walk the parent chain from the trigger to recover order.
148
- const taskBlocks = blocks.filter((b) => b.type?.endsWith("_task"));
149
- // Recover each task's authored refKey. The tf label is snake_case (ei's
150
- // labeling rule), so it is LOSSY for caps/spaces — but the block's `name`
151
- // attribute carries the exact authored name, and for EDK-authored tasks
152
- // name == refKey. Adopt `name` as the refKey whenever the label provably
153
- // derives from it (sanitizeName(name) == label suffix); otherwise keep the
154
- // label-suffix refKey and surface `name` as the displayName (a platform-
155
- // authored task whose name doesn't map to its label).
156
- const refKeyByLabel = new Map();
157
- for (const b of taskBlocks) {
158
- if (b.label === undefined)
159
- continue;
160
- const suffix = b.label.startsWith(`${autoLabel}_`) ? b.label.slice(autoLabel.length + 1) : b.label;
161
- const taskName = str(b.attrs["name"]);
162
- refKeyByLabel.set(b.label, taskName !== undefined && sanitizeName(taskName) === suffix ? taskName : suffix);
163
- }
164
- const refCtx = {
165
- autoLabel,
166
- isTriggerType: (type) => type.endsWith("_trigger") && AUTOMATION_SUB_TYPE_BY_RESOURCE.has(type),
167
- refKeyByLabel,
168
- };
169
- const childrenOf = (parentType, parentLabel) => taskBlocks.filter((b) => {
170
- const p = b.attrs["parent"];
171
- return (isTfExpr(p) && p.$expr === "resource-attr" && p.type === parentType && p.label === parentLabel);
172
- });
173
- const tasks = [];
174
- let curType = triggerBlock.type;
175
- let curLabel = autoLabel;
176
- const seen = new Set();
177
- for (;;) {
178
- const next = childrenOf(curType, curLabel);
179
- if (next.length === 0)
180
- break;
181
- if (next.length > 1) {
182
- ctx.diagnostics.push(`${where}: task "${curLabel}" has multiple children (branch/operator), not carried yet; stopping chain`);
183
- }
184
- const block = next[0];
185
- const addr = `${block.type}.${block.label}`;
186
- if (seen.has(addr)) {
187
- ctx.diagnostics.push(`${where}: cyclic parent chain at ${addr}; stopping`);
188
- break;
189
- }
190
- seen.add(addr);
191
- const row = block.type !== undefined ? AUTOMATION_SUB_TYPE_BY_RESOURCE.get(block.type) : undefined;
192
- if (row === undefined || row.implemented !== true || FACTORY_BY_TYPE_KEY[row.typeKey] === undefined) {
193
- ctx.diagnostics.push(`${where}: task ${addr} of an unimplemented kind; skipped`);
194
- curType = block.type;
195
- curLabel = block.label;
196
- continue;
197
- }
198
- const refKey = refKeyByLabel.get(block.label ?? "") ?? (block.label ?? "");
199
- const displayName = str(block.attrs["name"]);
200
- const extracted = taskArgs(row.typeKey, block.attrs, refCtx);
201
- if ("unsupported" in extracted) {
202
- ctx.diagnostics.push(`${where}: task ${addr}: ${extracted.unsupported}; skipped`);
203
- curType = block.type;
204
- curLabel = block.label;
205
- continue;
206
- }
207
- const call = {
208
- factory: FACTORY_BY_TYPE_KEY[row.typeKey],
209
- refKey,
210
- args: extracted.args,
211
- ...(displayName !== undefined && displayName !== refKey ? { displayName } : {}),
212
- };
213
- tasks.push(call);
214
- curType = block.type;
215
- curLabel = block.label;
1007
+ export function automationOwnedAddresses(doc, automationLabel) {
1008
+ const owned = new Set([`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}`]);
1009
+ for (const block of doc.blocks) {
1010
+ if (block.kind === "resource" && block.type !== undefined && block.label !== undefined &&
1011
+ references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel)) {
1012
+ owned.add(`${block.type}.${block.label}`);
1013
+ }
1014
+ }
1015
+ let changed = true;
1016
+ while (changed) {
1017
+ changed = false;
1018
+ for (const block of doc.blocks) {
1019
+ if (block.kind !== "resource" || block.type === undefined || block.label === undefined)
1020
+ continue;
1021
+ const address = `${block.type}.${block.label}`;
1022
+ if (owned.has(address))
1023
+ continue;
1024
+ const parent = resourceRef(block.attrs.parent) ?? resourceRef(block.attrs.switch_task) ?? resourceRef(block.attrs.fork_join_task);
1025
+ if (parent !== undefined && owned.has(`${parent.type}.${parent.label}`)) {
1026
+ owned.add(address);
1027
+ changed = true;
1028
+ }
1029
+ }
1030
+ }
1031
+ return [...owned];
1032
+ }
1033
+ /** Extract one app-owned automation graph from an ei app export. */
1034
+ function automationFromTfDocument(doc, automationLabel, appRefName) {
1035
+ const automation = doc.blocks.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE && block.label === automationLabel);
1036
+ if (automation === undefined)
1037
+ throw new EntityTfError(`automation resource "${automationLabel}" not found`);
1038
+ assertAllowed(automation, new Set(["app_id", "name", "description", "triggers_other_automations", "depends_on"]));
1039
+ const app = resourceRef(automation.attrs.app_id);
1040
+ if (app === undefined || app.type !== "elementum_app" || app.path[0] !== "id")
1041
+ throw new EntityTfError(`${AUTOMATION_RESOURCE_TYPE}.${automationLabel}: app_id is not an app reference`);
1042
+ const triggers = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? "") && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
1043
+ const publish = doc.blocks.find((block) => block.kind === "resource" && block.type === WORKFLOW_PUBLISH_RESOURCE_TYPE && references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel));
1044
+ const unknownDirectChild = doc.blocks.find((block) => block.kind === "resource" &&
1045
+ references(block.attrs.automation, AUTOMATION_RESOURCE_TYPE, automationLabel) &&
1046
+ block.type !== WORKFLOW_PUBLISH_RESOURCE_TYPE &&
1047
+ !AUTOMATION_TRIGGER_TYPE_SET.has(block.type ?? ""));
1048
+ if (unknownDirectChild) {
1049
+ throw new EntityTfError(`unknown automation resource type "${unknownDirectChild.type}"`);
1050
+ }
1051
+ if (triggers.length !== 1)
1052
+ throw new EntityTfError(`automation "${automationLabel}" must have exactly one trigger; found ${triggers.length}`);
1053
+ const trigger = triggers[0];
1054
+ assertAllowed(trigger, TRIGGER_ATTRIBUTES);
1055
+ if (publish !== undefined)
1056
+ assertAllowed(publish, PUBLISH_ATTRIBUTES);
1057
+ const branches = doc.blocks.filter((block) => block.kind === "resource" && AUTOMATION_BRANCH_TYPE_SET.has(block.type ?? ""));
1058
+ const taskCandidates = doc.blocks.filter((block) => block.kind === "resource" && ALL_AUTOMATION_TASK_TYPE_SET.has(block.type ?? ""));
1059
+ const resourceBlocks = new Map(doc.blocks.filter((block) => block.kind === "resource" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1060
+ const owned = new Set([`${trigger.type}.${trigger.label}`]);
1061
+ let changed = true;
1062
+ while (changed) {
1063
+ changed = false;
1064
+ for (const branch of branches) {
1065
+ const owner = resourceRef(branch.attrs.switch_task ?? branch.attrs.fork_join_task);
1066
+ if (owner && owned.has(`${owner.type}.${owner.label}`) && !owned.has(`${branch.type}.${branch.label}`)) {
1067
+ owned.add(`${branch.type}.${branch.label}`);
1068
+ changed = true;
1069
+ }
1070
+ }
1071
+ for (const task of taskCandidates) {
1072
+ const parent = resourceRef(task.attrs.parent);
1073
+ if (parent && owned.has(`${parent.type}.${parent.label}`) && !owned.has(`${task.type}.${task.label}`)) {
1074
+ owned.add(`${task.type}.${task.label}`);
1075
+ changed = true;
1076
+ }
1077
+ }
216
1078
  }
217
- // Workflow outputs live on the publish block ([{name, value: refs expr}]).
218
- const publish = blocks.find((b) => b.type === WORKFLOW_PUBLISH_RESOURCE_TYPE);
219
- const workflowRevision = publish !== undefined ? str(publish.attrs["workflow_revision"]) : undefined;
220
- const outputs = [];
221
- const rawOutputs = publish !== undefined && Array.isArray(publish.attrs["outputs"]) ? publish.attrs["outputs"] : [];
222
- for (const o of rawOutputs) {
223
- const outName = str(o?.name);
224
- if (outName === undefined)
1079
+ const tasks = taskCandidates.filter((block) => owned.has(`${block.type}.${block.label}`));
1080
+ const ownedBranches = branches.filter((block) => owned.has(`${block.type}.${block.label}`));
1081
+ tasks.forEach((block) => assertAllowed(block, TASK_ATTRIBUTES));
1082
+ ownedBranches.forEach((block) => assertAllowed(block, BRANCH_ATTRIBUTES));
1083
+ const publishDependencies = Array.isArray(publish?.attrs.depends_on)
1084
+ ? publish.attrs.depends_on.map((value) => resourceRef(value)).filter((value) => value !== undefined)
1085
+ : [];
1086
+ for (const dependency of publishDependencies) {
1087
+ if (dependency.type.startsWith("elementum_") &&
1088
+ dependency.type !== trigger.type &&
1089
+ !ALL_AUTOMATION_TASK_TYPE_SET.has(dependency.type) &&
1090
+ !AUTOMATION_BRANCH_TYPE_SET.has(dependency.type) &&
1091
+ dependency.type !== WORKFLOW_PUBLISH_RESOURCE_TYPE) {
1092
+ throw new EntityTfError(`unknown automation resource type "${dependency.type}"`);
1093
+ }
1094
+ const address = `${dependency.type}.${dependency.label}`;
1095
+ if (!ALL_AUTOMATION_TASK_TYPE_SET.has(dependency.type) || owned.has(address))
225
1096
  continue;
226
- const converted = tfRefToAst((o.value ?? ""), refCtx);
227
- if ("unsupported" in converted) {
228
- ctx.diagnostics.push(`${where}: output "${outName}": ${converted.unsupported}; skipped`);
1097
+ const seen = new Set();
1098
+ let cursor = address;
1099
+ while (cursor !== undefined && !owned.has(cursor)) {
1100
+ if (seen.has(cursor))
1101
+ throw new EntityTfError(`cycle detected at ${cursor}`);
1102
+ seen.add(cursor);
1103
+ const block = resourceBlocks.get(cursor);
1104
+ if (block === undefined)
1105
+ throw new EntityTfError(`${cursor}: unresolved parent`);
1106
+ const parent = resourceRef(block.attrs.parent);
1107
+ if (parent === undefined)
1108
+ throw new EntityTfError(`${cursor}: missing parent`);
1109
+ cursor = `${parent.type}.${parent.label}`;
1110
+ }
1111
+ throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task ${address}`);
1112
+ }
1113
+ for (const task of tasks) {
1114
+ const parent = resourceRef(task.attrs.parent);
1115
+ if (parent === undefined || !owned.has(`${parent.type}.${parent.label}`))
1116
+ throw new EntityTfError(`${task.type}.${task.label}: unresolved parent`);
1117
+ if (parent.path.length > 0 && !(parent.type === "elementum_for_each_task" && parent.path.length === 1 && parent.path[0] === "inner")) {
1118
+ throw new EntityTfError(`${task.type}.${task.label}: unsupported parent path`);
1119
+ }
1120
+ }
1121
+ const appTfLabel = app.label;
1122
+ const taskByAddress = new Map(tasks.map((block) => [`${block.type}.${block.label}`, { block, refKey: taskRefKey(block, automationLabel, appTfLabel) }]));
1123
+ const resourceImportIds = new Map();
1124
+ for (const block of doc.blocks) {
1125
+ if (block.kind !== "import" || typeof block.attrs.id !== "string")
229
1126
  continue;
1127
+ const target = resourceRef(block.attrs.to);
1128
+ if (target === undefined)
1129
+ continue;
1130
+ const unresolvedId = block.attrs.id.split(/[:/]/).at(-1);
1131
+ if (unresolvedId !== undefined && unresolvedId !== "")
1132
+ resourceImportIds.set(`${target.type}.${target.label}`, unresolvedId);
1133
+ }
1134
+ const fieldById = new Map();
1135
+ for (const [address, id] of resourceImportIds) {
1136
+ const block = resourceBlocks.get(address);
1137
+ if (block?.type?.endsWith("_field") !== true || block.label === undefined)
1138
+ continue;
1139
+ fieldById.set(id, {
1140
+ key: scopedLabelToBagKey(appTfLabel, block.label ?? ""),
1141
+ name: typeof block.attrs.name === "string" ? block.attrs.name : block.label,
1142
+ });
1143
+ }
1144
+ const dataBlocks = new Map(doc.blocks.filter((block) => block.kind === "data" && block.type && block.label).map((block) => [`${block.type}.${block.label}`, block]));
1145
+ const stagesByKey = new Map();
1146
+ const stagesAttr = resourceBlocks.get(`elementum_app.${app.label}`)?.attrs["stages"];
1147
+ if (Array.isArray(stagesAttr)) {
1148
+ for (const item of stagesAttr) {
1149
+ if (isObject(item) && !isTfExpr(item) && typeof item.key === "string" && typeof item.name === "string")
1150
+ stagesByKey.set(item.key, item.name);
1151
+ }
1152
+ }
1153
+ const ctx = { appRefName, appTfLabel: app.label, trigger, taskByAddress, resourceBlocks, dataBlocks, resourceImportIds, fieldById, stagesByKey };
1154
+ const dependencyOrder = new Map();
1155
+ if (publish && Array.isArray(publish.attrs.depends_on))
1156
+ publish.attrs.depends_on.forEach((dep, index) => { const ref = resourceRef(dep); if (ref)
1157
+ dependencyOrder.set(`${ref.type}.${ref.label}`, index); });
1158
+ const childrenByParent = new Map();
1159
+ for (const task of tasks) {
1160
+ const parent = parentAddress(task);
1161
+ childrenByParent.set(parent, [...(childrenByParent.get(parent) ?? []), task]);
1162
+ }
1163
+ for (const list of childrenByParent.values())
1164
+ list.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1165
+ const visiting = new Set();
1166
+ const visited = new Set();
1167
+ const buildTasks = (parent) => (childrenByParent.get(parent) ?? []).flatMap((block) => {
1168
+ const address = `${block.type}.${block.label}`;
1169
+ if (visiting.has(address))
1170
+ throw new EntityTfError(`cycle detected at ${address}`);
1171
+ visiting.add(address);
1172
+ visited.add(address);
1173
+ const factory = TASK_FACTORIES[block.type];
1174
+ if (factory === undefined)
1175
+ throw new EntityTfError(`unknown task resource type "${block.type}"`);
1176
+ const refKey = taskByAddress.get(address).refKey;
1177
+ let children;
1178
+ if (factory === "forEach")
1179
+ children = [{ label: null, tasks: buildTasks(`${address}.inner`) }];
1180
+ if (factory === "switchTask" || factory === "forkJoin") {
1181
+ const branchAttr = factory === "switchTask" ? "switch_task" : "fork_join_task";
1182
+ const matching = ownedBranches.filter((branch) => references(branch.attrs[branchAttr], block.type, block.label));
1183
+ matching.sort((a, b) => (dependencyOrder.get(`${a.type}.${a.label}`) ?? Number.MAX_SAFE_INTEGER) - (dependencyOrder.get(`${b.type}.${b.label}`) ?? Number.MAX_SAFE_INTEGER) || a.label.localeCompare(b.label));
1184
+ children = matching.map((branch) => {
1185
+ const shape = factory === "switchTask" ? defaultSwitchShape(branch) : undefined;
1186
+ const isDefault = shape !== undefined;
1187
+ const rawLabel = typeof branch.attrs.label === "string" ? branch.attrs.label : undefined;
1188
+ return {
1189
+ label: isDefault ? null : rawLabel ?? null,
1190
+ // ei always writes SOME display label on the default case, but it's
1191
+ // not always the literal string "Default" (e.g. a manual rename to
1192
+ // "Default Path") - carry the real text so the printer/build round
1193
+ // trip can reproduce it instead of hardcoding "Default".
1194
+ ...(isDefault && rawLabel !== undefined ? { defaultLabel: rawLabel } : {}),
1195
+ // Carry the observed wire shape only when it's the older
1196
+ // filter-based one - the newer is_default shape is to-tf.ts's
1197
+ // unmarked default, so leaving this unset there keeps printed
1198
+ // output terse and matches a freshly-authored default branch.
1199
+ ...(shape === "explicitTrueFilter" ? { defaultFilterMode: shape } : {}),
1200
+ ...(!isDefault && branch.attrs.filter !== undefined ? { filter: decodeFilter(branch.attrs.filter, ctx) } : {}),
1201
+ tasks: buildTasks(`${branch.type}.${branch.label}`),
1202
+ };
1203
+ });
230
1204
  }
231
- outputs.push({ name: outName, value: converted.ast });
1205
+ const parent = resourceRef(block.attrs.parent);
1206
+ const parentTask = parent === undefined ? undefined : taskByAddress.get(`${parent.type}.${parent.label}`);
1207
+ const hclParent = parent?.type === trigger.type && parent?.label === trigger.label ? "trigger" : parentTask?.refKey;
1208
+ const call = { factory, refKey, args: taskArgs(block, factory, ctx), ...(children ? { children } : {}), ...(typeof block.attrs.name === "string" && block.attrs.name !== refKey ? { displayName: block.attrs.name } : {}), ...(hclParent !== undefined ? { hclParent } : {}) };
1209
+ visiting.delete(address);
1210
+ return [call, ...buildTasks(address)];
1211
+ });
1212
+ const topTasks = buildTasks(`${trigger.type}.${trigger.label}`);
1213
+ if (visited.size !== tasks.length)
1214
+ throw new EntityTfError(`automation "${automationLabel}" contains an orphaned task graph`);
1215
+ const outputBlocks = publish?.attrs.outputs;
1216
+ const outputs = Array.isArray(outputBlocks) ? outputBlocks.map((output) => {
1217
+ if (!isObject(output) || typeof output.name !== "string" || output.value === undefined)
1218
+ throw new EntityTfError("invalid workflow output");
1219
+ return { name: output.name, value: decodeValue(output.value, ctx) };
1220
+ }) : undefined;
1221
+ const exportedRevision = publish?.attrs.workflow_revision;
1222
+ if (exportedRevision !== undefined && typeof exportedRevision !== "string") {
1223
+ throw new EntityTfError(`${WORKFLOW_PUBLISH_RESOURCE_TYPE}.${automationLabel}: workflow_revision must be a string`);
232
1224
  }
1225
+ const ast = {
1226
+ ownerHandle: appRefName,
1227
+ name: typeof automation.attrs.name === "string" ? automation.attrs.name : "",
1228
+ workflowRevision: exportedRevision ?? "1.0.0",
1229
+ ...(typeof automation.attrs.description === "string" ? { description: automation.attrs.description } : {}),
1230
+ ...(typeof automation.attrs.triggers_other_automations === "boolean" ? { triggersOtherAutomations: automation.attrs.triggers_other_automations } : {}),
1231
+ status: publish ? "ACTIVE" : "DRAFT",
1232
+ trigger: triggerFromBlock(trigger, ctx),
1233
+ tasks: topTasks,
1234
+ ...(outputs && outputs.length > 0 ? { outputs } : {}),
1235
+ };
233
1236
  return {
234
- automation: {
235
- ownerHandle: ctx.ownerHandle,
236
- name,
237
- status: "DRAFT",
238
- ...(workflowRevision !== undefined ? { workflowRevision } : {}),
239
- trigger,
240
- tasks,
241
- ...(outputs.length > 0 ? { outputs } : {}),
242
- },
1237
+ refName: scopedLabelToBagKey(appTfLabel, automationLabel),
1238
+ tfLabel: automationLabel, ast, blocks: [automation, trigger, ...tasks, ...ownedBranches, ...(publish ? [publish] : [])]
243
1239
  };
244
1240
  }
245
- /** Recognizes the blocks that make up automation families (for the pull partition). */
246
- export function isAutomationFamilyType(type) {
247
- if (type === undefined)
248
- return false;
249
- return (type === AUTOMATION_RESOURCE_TYPE ||
250
- type === WORKFLOW_PUBLISH_RESOURCE_TYPE ||
251
- AUTOMATION_SUB_TYPE_BY_RESOURCE.has(type));
1241
+ export function automationFromTf(first, second, third) {
1242
+ if (Array.isArray(first)) {
1243
+ const ctx = second;
1244
+ const automationBlock = first.find((block) => block.kind === "resource" && block.type === AUTOMATION_RESOURCE_TYPE);
1245
+ if (automationBlock?.label === undefined) {
1246
+ return { skippedReason: "automation resource not found" };
1247
+ }
1248
+ try {
1249
+ return { automation: automationFromTfDocument({ blocks: [...first] }, automationBlock.label, ctx.ownerHandle).ast };
1250
+ }
1251
+ catch (err) {
1252
+ const message = err instanceof Error ? err.message : String(err);
1253
+ ctx.diagnostics.push(message);
1254
+ return { skippedReason: message };
1255
+ }
1256
+ }
1257
+ return automationFromTfDocument(first, second, third ?? "");
252
1258
  }