@elementumai/edk 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/README.md +2 -0
  2. package/dist-sdk/src/catalog/factories.d.ts +7 -1
  3. package/dist-sdk/src/catalog/factories.js +2 -0
  4. package/dist-sdk/src/catalog/index.d.ts +2 -2
  5. package/dist-sdk/src/catalog/index.js +1 -1
  6. package/dist-sdk/src/catalog/org.js +79 -34
  7. package/dist-sdk/src/catalog/token.js +5 -0
  8. package/dist-sdk/src/catalog/types.d.ts +7 -1
  9. package/dist-sdk/src/catalog/types.js +3 -0
  10. package/dist-sdk/src/core/system-fields.d.ts +1 -1
  11. package/dist-sdk/src/core/system-fields.js +1 -1
  12. package/dist-sdk/src/core/types/app.d.ts +6 -0
  13. package/dist-sdk/src/engine/build/context.d.ts +3 -0
  14. package/dist-sdk/src/engine/pull/authored-address.js +42 -6
  15. package/dist-sdk/src/engine/pull/authored-root.d.ts +88 -0
  16. package/dist-sdk/src/engine/pull/authored-root.js +306 -0
  17. package/dist-sdk/src/engine/pull/context.d.ts +10 -0
  18. package/dist-sdk/src/engine/pull/field-refs-registry.d.ts +114 -0
  19. package/dist-sdk/src/engine/pull/field-refs-registry.js +501 -0
  20. package/dist-sdk/src/engine/pull/org.d.ts +1 -0
  21. package/dist-sdk/src/engine/pull/org.js +2 -0
  22. package/dist-sdk/src/engine/pull/partition.d.ts +8 -0
  23. package/dist-sdk/src/engine/pull/partition.js +43 -0
  24. package/dist-sdk/src/engine/pull/pulled-roots.d.ts +89 -0
  25. package/dist-sdk/src/engine/pull/pulled-roots.js +203 -0
  26. package/dist-sdk/src/engine/pull/ref-only.d.ts +4 -0
  27. package/dist-sdk/src/engine/pull/ref-only.js +7 -1
  28. package/dist-sdk/src/engine/pull/source-resources.d.ts +39 -0
  29. package/dist-sdk/src/engine/pull/source-resources.js +110 -0
  30. package/dist-sdk/src/engine/pull/stream-root.d.ts +148 -0
  31. package/dist-sdk/src/engine/pull/stream-root.js +563 -0
  32. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.d.ts +47 -0
  33. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.js +115 -0
  34. package/dist-sdk/src/entities/access-policy/build.d.ts +2 -1
  35. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +7 -0
  36. package/dist-sdk/src/entities/access-policy/from-tf.js +18 -3
  37. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +19 -0
  38. package/dist-sdk/src/entities/access-policy/to-tf.js +65 -8
  39. package/dist-sdk/src/entities/agent/build.d.ts +52 -1
  40. package/dist-sdk/src/entities/agent/build.js +34 -0
  41. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +68 -0
  42. package/dist-sdk/src/entities/agent/from-tf.d.ts +34 -1
  43. package/dist-sdk/src/entities/agent/from-tf.js +262 -2
  44. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  45. package/dist-sdk/src/entities/agent/to-tf.d.ts +8 -10
  46. package/dist-sdk/src/entities/agent/to-tf.js +158 -14
  47. package/dist-sdk/src/entities/agent-tool/from-tf.js +6 -0
  48. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  49. package/dist-sdk/src/entities/agent-tool/to-tf.js +2 -2
  50. package/dist-sdk/src/entities/app/build.d.ts +33 -13
  51. package/dist-sdk/src/entities/app/build.js +14 -12
  52. package/dist-sdk/src/entities/app/from-tf.js +24 -9
  53. package/dist-sdk/src/entities/app/index.d.ts +1 -0
  54. package/dist-sdk/src/entities/app/index.js +1 -0
  55. package/dist-sdk/src/entities/app/module.js +1 -0
  56. package/dist-sdk/src/entities/app/stage-keys.d.ts +2 -2
  57. package/dist-sdk/src/entities/app/stage-keys.js +3 -3
  58. package/dist-sdk/src/entities/app/to-tf.js +1 -0
  59. package/dist-sdk/src/entities/approval-chain/build.d.ts +46 -11
  60. package/dist-sdk/src/entities/approval-chain/build.js +120 -8
  61. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +24 -2
  62. package/dist-sdk/src/entities/approval-chain/from-tf.js +148 -6
  63. package/dist-sdk/src/entities/approval-chain/index.d.ts +4 -1
  64. package/dist-sdk/src/entities/approval-chain/index.js +4 -1
  65. package/dist-sdk/src/entities/approval-chain/module.js +23 -5
  66. package/dist-sdk/src/entities/approval-chain/printer.d.ts +1 -1
  67. package/dist-sdk/src/entities/approval-chain/printer.js +91 -5
  68. package/dist-sdk/src/entities/approval-chain/steps-tf.d.ts +77 -0
  69. package/dist-sdk/src/entities/approval-chain/steps-tf.js +255 -0
  70. package/dist-sdk/src/entities/approval-chain/steps.d.ts +71 -0
  71. package/dist-sdk/src/entities/approval-chain/steps.js +83 -0
  72. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +16 -6
  73. package/dist-sdk/src/entities/approval-chain/to-tf.js +37 -4
  74. package/dist-sdk/src/entities/automation/build.js +70 -27
  75. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +20 -5
  76. package/dist-sdk/src/entities/automation/from-tf.d.ts +26 -5
  77. package/dist-sdk/src/entities/automation/from-tf.js +593 -101
  78. package/dist-sdk/src/entities/automation/index.d.ts +1 -0
  79. package/dist-sdk/src/entities/automation/index.js +1 -0
  80. package/dist-sdk/src/entities/automation/module.d.ts +4 -3
  81. package/dist-sdk/src/entities/automation/module.js +33 -12
  82. package/dist-sdk/src/entities/automation/refs-read.d.ts +19 -0
  83. package/dist-sdk/src/entities/automation/refs-read.js +48 -0
  84. package/dist-sdk/src/entities/automation/slack-message-refs.d.ts +9 -0
  85. package/dist-sdk/src/entities/automation/slack-message-refs.js +75 -0
  86. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +11 -0
  87. package/dist-sdk/src/entities/automation/task-output-labels.js +23 -0
  88. package/dist-sdk/src/entities/automation/tasks.d.ts +29 -4
  89. package/dist-sdk/src/entities/automation/tasks.js +34 -11
  90. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -0
  91. package/dist-sdk/src/entities/automation/to-tf.js +337 -77
  92. package/dist-sdk/src/entities/automation/triggers.d.ts +0 -8
  93. package/dist-sdk/src/entities/automation/triggers.js +26 -11
  94. package/dist-sdk/src/entities/automation/unsafe-script-output.d.ts +50 -0
  95. package/dist-sdk/src/entities/automation/unsafe-script-output.js +92 -0
  96. package/dist-sdk/src/entities/chart/build.d.ts +9 -1
  97. package/dist-sdk/src/entities/chart/from-tf.js +3 -0
  98. package/dist-sdk/src/entities/chart/to-tf.js +19 -2
  99. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +2 -0
  100. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +44 -5
  101. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +46 -12
  102. package/dist-sdk/src/entities/element/audit-field-guard.d.ts +9 -0
  103. package/dist-sdk/src/entities/element/audit-field-guard.js +88 -0
  104. package/dist-sdk/src/entities/element/build.js +2 -1
  105. package/dist-sdk/src/entities/element/from-tf.js +15 -2
  106. package/dist-sdk/src/entities/element/module.js +3 -0
  107. package/dist-sdk/src/entities/element/system-fields.d.ts +13 -0
  108. package/dist-sdk/src/entities/element/system-fields.js +23 -0
  109. package/dist-sdk/src/entities/element/to-tf.js +1 -0
  110. package/dist-sdk/src/entities/field/build.d.ts +9 -0
  111. package/dist-sdk/src/entities/field/from-tf.d.ts +29 -1
  112. package/dist-sdk/src/entities/field/from-tf.js +99 -6
  113. package/dist-sdk/src/entities/field/module.js +4 -0
  114. package/dist-sdk/src/entities/field/to-tf.d.ts +5 -1
  115. package/dist-sdk/src/entities/field/to-tf.js +33 -12
  116. package/dist-sdk/src/entities/org/category.js +1 -0
  117. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  118. package/dist-sdk/src/entities/org/index.js +1 -0
  119. package/dist-sdk/src/entities/org/voice-auth.d.ts +5 -0
  120. package/dist-sdk/src/entities/org/voice-auth.js +33 -0
  121. package/dist-sdk/src/entities/organization/build.d.ts +3 -0
  122. package/dist-sdk/src/entities/organization/build.js +2 -0
  123. package/dist-sdk/src/entities/organization/index.d.ts +1 -0
  124. package/dist-sdk/src/entities/organization/index.js +1 -0
  125. package/dist-sdk/src/entities/organization/to-tf.d.ts +2 -0
  126. package/dist-sdk/src/entities/organization/to-tf.js +59 -1
  127. package/dist-sdk/src/entities/organization/voice-auth.d.ts +60 -0
  128. package/dist-sdk/src/entities/organization/voice-auth.js +60 -0
  129. package/dist-sdk/src/entities/phone-service/build.d.ts +9 -1
  130. package/dist-sdk/src/entities/phone-service/build.js +1 -0
  131. package/dist-sdk/src/entities/phone-service/deserializer/print-phone-service.js +3 -0
  132. package/dist-sdk/src/entities/phone-service/from-tf.d.ts +1 -0
  133. package/dist-sdk/src/entities/phone-service/from-tf.js +8 -1
  134. package/dist-sdk/src/entities/phone-service/to-tf.js +16 -0
  135. package/dist-sdk/src/entities/record-create-form/from-tf.js +2 -2
  136. package/dist-sdk/src/entities/relationship/from-tf.js +7 -2
  137. package/dist-sdk/src/entities/relationship/module.js +2 -2
  138. package/dist-sdk/src/entities/relationship/pair-check.d.ts +6 -2
  139. package/dist-sdk/src/entities/relationship/pair-check.js +105 -18
  140. package/dist-sdk/src/entities/relationship/to-tf.js +5 -2
  141. package/dist-sdk/src/entities/role/permission-levels.d.ts +7 -0
  142. package/dist-sdk/src/entities/role/permission-levels.js +78 -0
  143. package/dist-sdk/src/entities/role/to-tf.js +32 -2
  144. package/dist-sdk/src/entities/service-account/module.d.ts +2 -1
  145. package/dist-sdk/src/entities/service-account/module.js +4 -1
  146. package/dist-sdk/src/entities/service-account/resource-type.d.ts +2 -0
  147. package/dist-sdk/src/entities/service-account/resource-type.js +2 -0
  148. package/dist-sdk/src/entities/service-account/role-membership-check.d.ts +20 -0
  149. package/dist-sdk/src/entities/service-account/role-membership-check.js +80 -0
  150. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +15 -0
  151. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +36 -0
  152. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  153. package/dist-sdk/src/entities/shared/filters/index.d.ts +85 -14
  154. package/dist-sdk/src/entities/shared/filters/index.js +18 -6
  155. package/dist-sdk/src/entities/shared/filters/option-lookups.d.ts +57 -0
  156. package/dist-sdk/src/entities/shared/filters/option-lookups.js +108 -0
  157. package/dist-sdk/src/entities/shared/filters/print.js +9 -5
  158. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +12 -7
  159. package/dist-sdk/src/entities/shared/filters/tf-codec.js +9 -5
  160. package/dist-sdk/src/entities/shared/raw-option-id.d.ts +30 -0
  161. package/dist-sdk/src/entities/shared/raw-option-id.js +41 -0
  162. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -2
  163. package/dist-sdk/src/entities/skill/input-coverage.js +5 -2
  164. package/dist-sdk/src/entities/sla/build.d.ts +96 -0
  165. package/dist-sdk/src/entities/sla/build.js +124 -0
  166. package/dist-sdk/src/entities/sla/from-tf.d.ts +40 -0
  167. package/dist-sdk/src/entities/sla/from-tf.js +164 -0
  168. package/dist-sdk/src/entities/sla/index.d.ts +1 -0
  169. package/dist-sdk/src/entities/sla/index.js +1 -0
  170. package/dist-sdk/src/entities/sla/module.d.ts +4 -0
  171. package/dist-sdk/src/entities/sla/module.js +73 -0
  172. package/dist-sdk/src/entities/sla/printer.d.ts +2 -0
  173. package/dist-sdk/src/entities/sla/printer.js +84 -0
  174. package/dist-sdk/src/entities/sla/to-tf.d.ts +12 -0
  175. package/dist-sdk/src/entities/sla/to-tf.js +81 -0
  176. package/dist-sdk/src/entities/table/build.d.ts +7 -2
  177. package/dist-sdk/src/entities/table/build.js +22 -1
  178. package/dist-sdk/src/entities/table/deserializer/normalize.d.ts +4 -1
  179. package/dist-sdk/src/entities/table/from-tf.js +89 -14
  180. package/dist-sdk/src/entities/table/index.d.ts +1 -1
  181. package/dist-sdk/src/entities/table/to-tf.js +41 -2
  182. package/dist-sdk/src/entities/task/from-tf.js +2 -1
  183. package/dist-sdk/src/entities/view/from-tf.js +7 -4
  184. package/dist-sdk/src/entities/widget/from-tf.js +13 -2
  185. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +49 -4
  186. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  187. package/dist-sdk/src/graph/index.d.ts +5 -0
  188. package/dist-sdk/src/graph/index.js +7 -0
  189. package/dist-sdk/src/graph/modules.js +11 -1
  190. package/dist-sdk/src/graph/resource-types.d.ts +47 -0
  191. package/dist-sdk/src/graph/resource-types.js +62 -0
  192. package/dist-sdk/src/graph/types.d.ts +78 -6
  193. package/package.json +6 -3
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Pull path identity: reuse an existing authored stream-root directory
3
+ * when the live namespace (or extracted refName) names the same app/element
4
+ * as an on-disk tree whose directory/refName casing differs.
5
+ *
6
+ * `elementum new app` mints `apps/<refName>/` from the display name
7
+ * (`eDKCloudBuilder`) while `namespace` is an independent lowercase
8
+ * platform address (`edkcloudbuilder`). Extract derives refName from the
9
+ * export label (usually the namespace), so a naive write to
10
+ * `apps/<extractedRefName>/` creates a parallel tree — or, on a
11
+ * case-insensitive volume, a case-only path change that marker/sweep
12
+ * can delete.
13
+ */
14
+ import { existsSync, readdirSync, readFileSync, rmSync } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { catalogFolders, computeElementKeys, isGeneratedOnlyFolder, isReservedCatalogKey, isShadowedCatalogKey, orgHasTableCatalogs, reservedRefNameError, } from "../workspace/reserved-catalog-keys.js";
17
+ /** `app({` / `element({` / `task({` plus the legacy `defineApp`/`defineElement` printers. */
18
+ const ROOT_DEFINE_RE = /\b(?:app|element|task|defineApp|defineElement)\(\s*\{/;
19
+ /** `namespace: "lit"` / `namespace: 'lit'`, or `namespace: IDENT` resolved through a same-file const. */
20
+ const NAMESPACE_RE = /\bnamespace:\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z_$][\w$]*)\b)/;
21
+ function sameFileConstString(source, ident) {
22
+ const escaped = ident.replace(/\$/g, "\\$");
23
+ const re = new RegExp(`\\bconst\\s+${escaped}\\s*(?::\\s*string\\s*)?=\\s*(?:"([^"]+)"|'([^']+)')\\s*(?:as\\s+const\\s*)?(?:[;\\n]|$)`);
24
+ const match = re.exec(source);
25
+ return match === null ? undefined : (match[1] ?? match[2]);
26
+ }
27
+ export function readAuthoredRootNamespace(source) {
28
+ const defineMatch = ROOT_DEFINE_RE.exec(source);
29
+ const searchFrom = defineMatch !== null ? defineMatch.index + defineMatch[0].length : 0;
30
+ const match = NAMESPACE_RE.exec(source.slice(searchFrom));
31
+ if (match === null)
32
+ return undefined;
33
+ const literal = match[1] ?? match[2];
34
+ if (literal !== undefined)
35
+ return literal;
36
+ // `namespace: NS` with `const NS = "..."` in the same file (#1583).
37
+ return sameFileConstString(source, match[3]);
38
+ }
39
+ export function listAuthoredRoots(orgRoot, bag) {
40
+ let names;
41
+ try {
42
+ names = readdirSync(join(orgRoot, bag), { withFileTypes: true })
43
+ .filter((entry) => entry.isDirectory())
44
+ .map((entry) => entry.name);
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ const out = [];
50
+ for (const refName of names) {
51
+ const file = join(orgRoot, bag, refName, `${refName}.ts`);
52
+ if (!existsSync(file))
53
+ continue;
54
+ let namespace;
55
+ try {
56
+ namespace = readAuthoredRootNamespace(readFileSync(file, "utf8"));
57
+ }
58
+ catch {
59
+ namespace = undefined;
60
+ }
61
+ out.push(namespace === undefined ? { refName } : { refName, namespace });
62
+ }
63
+ return out;
64
+ }
65
+ /**
66
+ * Last-write-wins namespace → refName index (same contract as the previous
67
+ * `readNamespaceMap` scan). Duplicate namespaces stay visible to
68
+ * {@link resolveAuthoredRootRefName} via {@link listAuthoredRoots}.
69
+ */
70
+ export function authoredNamespaceMap(orgRoot, bag) {
71
+ const map = new Map();
72
+ for (const root of listAuthoredRoots(orgRoot, bag)) {
73
+ if (root.namespace !== undefined)
74
+ map.set(root.namespace, root.refName);
75
+ }
76
+ return map;
77
+ }
78
+ /** Case-insensitive map lookup; exact key wins, otherwise a unique fold match. */
79
+ export function lookupNamespaceMap(map, namespace) {
80
+ const exact = map.get(namespace);
81
+ if (exact !== undefined)
82
+ return exact;
83
+ const lower = namespace.toLowerCase();
84
+ const hits = [...new Set([...map.entries()].filter(([key]) => key.toLowerCase() === lower).map(([, ref]) => ref))];
85
+ return hits.length === 1 ? hits[0] : undefined;
86
+ }
87
+ function pickPreferredRef(hits, extractedRefName) {
88
+ if (hits.length === 0)
89
+ return undefined;
90
+ if (hits.length === 1)
91
+ return hits[0].refName;
92
+ // After a prior pull that created a parallel export-cased tree, keep the
93
+ // authored directory whose name is not the extract-derived key.
94
+ const authored = hits.filter((hit) => hit.refName !== extractedRefName);
95
+ if (authored.length === 1)
96
+ return authored[0].refName;
97
+ return hits.find((hit) => hit.refName === extractedRefName)?.refName;
98
+ }
99
+ /**
100
+ * Existing authored stream-root whose identity matches `liveNamespace`, or
101
+ * `undefined` when pull should create/use the extract-derived path.
102
+ */
103
+ export function findAuthoredRootRefName(options) {
104
+ const { orgRoot, bag, liveNamespace, extractedRefName } = options;
105
+ const live = liveNamespace.toLowerCase();
106
+ const roots = listAuthoredRoots(orgRoot, bag);
107
+ const namespaceHits = roots.filter((root) => root.namespace !== undefined && root.namespace.toLowerCase() === live);
108
+ const fromNamespace = pickPreferredRef(namespaceHits, extractedRefName);
109
+ if (fromNamespace !== undefined)
110
+ return refuseShadowed(orgRoot, bag, fromNamespace, liveNamespace);
111
+ if (namespaceHits.length > 1) {
112
+ // Writing yet another tree would add a third duplicate elementum_app address.
113
+ throw new Error(`${bag}: namespace "${liveNamespace}" is declared by more than one directory ` +
114
+ `(${namespaceHits.map((hit) => `${bag}/${hit.refName}`).join(", ")}); ` +
115
+ "remove the duplicate before pulling");
116
+ }
117
+ // Directory fallback only against the live namespace, and only when the
118
+ // file has no parseable namespace. Matching the extracted refName would
119
+ // steal an unrelated `apps/tickets` tree for a `tickets.namespace` export.
120
+ const nameHits = roots.filter((root) => (root.namespace === undefined && root.refName.toLowerCase() === live));
121
+ const fromName = pickPreferredRef(nameHits, extractedRefName);
122
+ return fromName === undefined ? undefined : refuseShadowed(orgRoot, bag, fromName, liveNamespace);
123
+ }
124
+ /**
125
+ * An authored tree whose ref name the `@catalog` barrel shadows can't be
126
+ * referenced, so pull stops before writing over it and says how to move it
127
+ * (edk#2839).
128
+ */
129
+ function refuseShadowed(orgRoot, bag, refName, liveNamespace) {
130
+ if (bag === "tasks" || !rootIsShadowed(orgRoot, refName))
131
+ return refName;
132
+ throw reservedRefNameError(bag, refName, reservedRootFolder(orgRoot, bag, refName, liveNamespace, refName));
133
+ }
134
+ /**
135
+ * Pull keeps an app or element in `<bag>/<refName>/` only when that folder
136
+ * name isn't an org entry (edk#2839; `tables` only while a table catalog is
137
+ * emitted). Pulled source names a root by its folder (`catalog.<refName>`
138
+ * in agents, automations and fields), not by the barrel key, so an element
139
+ * the barrel exposes as `catalog.groups2` beside `apps/groups/` would still
140
+ * be printed as `catalog.groups`, the org entry. It moves to
141
+ * reservedRootFolder instead (`groups3`), where folder and key agree.
142
+ * `tablesEmitted` defaults to whether a table catalog is on disk.
143
+ */
144
+ export function rootIsShadowed(orgRoot, refName, tablesEmitted = orgHasTableCatalogs(orgRoot)) {
145
+ return isShadowedCatalogKey(refName, tablesEmitted);
146
+ }
147
+ /**
148
+ * Choose the on-disk stream-root refName to write/adopt. Prefers an existing
149
+ * authored tree whose `namespace:` matches the live namespace
150
+ * (case-insensitive). Falls back to a case-insensitive directory name match
151
+ * against the live namespace when the file has no parseable namespace.
152
+ * Otherwise returns the extracted refName (first pull), or
153
+ * {@link reservedRootFolder} (`users2`, …) when that is a reserved `@catalog`
154
+ * key (`users`, `groups`, …).
155
+ */
156
+ export function resolveAuthoredRootRefName(options) {
157
+ const { orgRoot, bag, liveNamespace, extractedRefName } = options;
158
+ const authored = findAuthoredRootRefName(options);
159
+ if (authored !== undefined)
160
+ return authored;
161
+ if (bag === "tasks" || !isReservedCatalogKey(extractedRefName))
162
+ return extractedRefName;
163
+ // First pull of a reserved @catalog key (`users`, edk#2839). A dependency
164
+ // stub already there that the barrel doesn't shadow (`tables` with no
165
+ // table catalog) is filled in place, as the stub path keeps it. Otherwise
166
+ // the root moves to reservedRootFolder; once it is written, the caller's
167
+ // retireShadowedStub removes a shadowed stub left at the old name.
168
+ const existing = join(orgRoot, bag, extractedRefName);
169
+ if (existsSync(existing) && isGeneratedOnlyFolder(existing) && !rootIsShadowed(orgRoot, extractedRefName)) {
170
+ return extractedRefName;
171
+ }
172
+ const vacated = existsSync(existing) && isGeneratedOnlyFolder(existing) ? extractedRefName : undefined;
173
+ return reservedRootFolder(orgRoot, bag, extractedRefName, liveNamespace, vacated);
174
+ }
175
+ /**
176
+ * The folder for an app or element whose export ref name is a reserved
177
+ * `@catalog` key (`users` → `users2`, edk#2839). A `<base>N` folder in `bag`
178
+ * that already holds `liveNamespace` is reused (the lowest such N), so a
179
+ * re-pull keeps its folder. Otherwise the first `<base>N` (N ≥ 2) that no app
180
+ * or element folder uses and that isn't already another element's catalog
181
+ * key (`vacated` names the folder this root is leaving, whose key it takes):
182
+ * apps and elements share one key space, so a name taken there would shift a
183
+ * key (`elements/users2/` beside `apps/users2/` is `catalog.users22`).
184
+ */
185
+ export function reservedRootFolder(orgRoot, bag, base, liveNamespace, vacated) {
186
+ if (liveNamespace !== undefined) {
187
+ const numbered = new RegExp(`^${base}(\\d+)$`);
188
+ const held = (existsSync(join(orgRoot, bag)) ? readdirSync(join(orgRoot, bag)) : [])
189
+ .map((name) => ({ name, n: Number(numbered.exec(name)?.[1] ?? NaN) }))
190
+ .filter(({ name, n }) => n >= 2 && folderDeclaresNamespace(orgRoot, bag, name, liveNamespace))
191
+ .sort((x, y) => x.n - y.n);
192
+ if (held.length > 0)
193
+ return held[0].name;
194
+ }
195
+ // `vacated` is the folder this root is moving out of (a stub pull retires,
196
+ // or the folder a hint says to rename): its key goes with it, so it isn't
197
+ // counted. elements/groups/ beside apps/groups/ keeps catalog.groups2.
198
+ const apps = catalogFolders(orgRoot, "apps");
199
+ const elements = catalogFolders(orgRoot, "elements").filter((name) => bag !== "elements" || name !== vacated);
200
+ const elementKeys = new Set(computeElementKeys(apps, elements).values());
201
+ for (let i = 2;; i++) {
202
+ const candidate = `${base}${i}`;
203
+ if (existsSync(join(orgRoot, "apps", candidate)) || existsSync(join(orgRoot, "elements", candidate)))
204
+ continue;
205
+ if (elementKeys.has(candidate))
206
+ continue;
207
+ return candidate;
208
+ }
209
+ }
210
+ const CATALOG_NAMESPACE_RE = /\bnamespace:\s*"([^"]*)"/;
211
+ /** `<bag>/<refName>/` declares `liveNamespace`: in its source, or (a stub) in its generated catalog. */
212
+ function folderDeclaresNamespace(orgRoot, bag, refName, liveNamespace) {
213
+ const live = liveNamespace.toLowerCase();
214
+ const source = join(orgRoot, bag, refName, `${refName}.ts`);
215
+ try {
216
+ if (existsSync(source))
217
+ return readAuthoredRootNamespace(readFileSync(source, "utf8"))?.toLowerCase() === live;
218
+ const catalog = join(orgRoot, bag, refName, "generated", "catalog.ts");
219
+ if (existsSync(catalog))
220
+ return CATALOG_NAMESPACE_RE.exec(readFileSync(catalog, "utf8"))?.[1]?.toLowerCase() === live;
221
+ }
222
+ catch {
223
+ return false;
224
+ }
225
+ return false;
226
+ }
227
+ /**
228
+ * After pull wrote a root that moved off a reserved key (`users` →
229
+ * `users2`), remove the dependency stub an older pull left at
230
+ * `<bag>/<extractedRefName>/` (only `generated/`) when the barrel shadows
231
+ * it, so the workspace holds one tree for the namespace. Call it only once
232
+ * the new root is on disk. Source there is never touched. Returns whether it
233
+ * removed one.
234
+ */
235
+ export function retireShadowedStub(orgRoot, bag, extractedRefName, refName) {
236
+ if (refName === extractedRefName || bag === "tasks")
237
+ return false;
238
+ if (!rootIsShadowed(orgRoot, extractedRefName))
239
+ return false;
240
+ const dir = join(orgRoot, bag, extractedRefName);
241
+ if (!existsSync(dir) || !isGeneratedOnlyFolder(dir))
242
+ return false;
243
+ rmSync(dir, { recursive: true, force: true });
244
+ return true;
245
+ }
246
+ /**
247
+ * The log line for a pull that writes `<bag>/<refName>/` instead of the
248
+ * export's ref name: an existing authored tree, or a new folder because the
249
+ * export's name is a reserved `@catalog` key (edk#2839).
250
+ */
251
+ export function authoredRootChoiceMessage(orgRoot, bag, refName, extractedRefName, namespace) {
252
+ if (existsSync(join(orgRoot, bag, refName, `${refName}.ts`))) {
253
+ return `reusing authored ${bag}/${refName}/ for namespace ${JSON.stringify(namespace)} (export ref ${extractedRefName})`;
254
+ }
255
+ return `writing ${bag}/${refName}/ (catalog.${refName}) for namespace ${JSON.stringify(namespace)}: catalog.${extractedRefName} is reserved for an org catalog entry (edk#2839)`;
256
+ }
257
+ // `appRefName` is how a same-app service-account principal (access policy,
258
+ // role) names its owning app; left on the export label, build cannot resolve
259
+ // it against the authored catalog and drops the principal.
260
+ const REBIND_IDENTITY_KEYS = new Set(["refName", "parent", "appHandle", "ownerHandle", "appRefName"]);
261
+ /**
262
+ * Rewrite a pulled stream-root so printers emit the authored directory
263
+ * casing (`const eDKCloudBuilder`, `parent: "eDKCloudBuilder"`) instead of
264
+ * the extract-derived export label. Never touches `namespace` — that stays
265
+ * the live platform address.
266
+ */
267
+ export function rebindAuthoredRootRefName(root, authoredRefName) {
268
+ if (root.refName === authoredRefName)
269
+ return root;
270
+ return rebindRefNameDeep(root, root.refName, authoredRefName);
271
+ }
272
+ /**
273
+ * Rewrite extract-time owner handles on an own-file child (automation,
274
+ * agent, …) so printers emit `catalog.eDKCloudBuilder.fields…` instead of
275
+ * the export-label key (`catalog.edkcloudbuilder.fields…`).
276
+ */
277
+ export function rebindAuthoredOwnerRefs(value, extractedOwnerRefName, authoredOwnerRefName) {
278
+ if (extractedOwnerRefName === authoredOwnerRefName)
279
+ return value;
280
+ return rebindRefNameDeep(value, extractedOwnerRefName, authoredOwnerRefName);
281
+ }
282
+ function rebindRefNameDeep(value, from, to, key) {
283
+ if (typeof value === "string") {
284
+ return key !== undefined && REBIND_IDENTITY_KEYS.has(key) && value === from ? to : value;
285
+ }
286
+ if (Array.isArray(value))
287
+ return value.map((item) => rebindRefNameDeep(item, from, to));
288
+ if (value === null || typeof value !== "object")
289
+ return value;
290
+ const rec = value;
291
+ const out = {};
292
+ for (const [childKey, child] of Object.entries(rec)) {
293
+ if (childKey === "namespace") {
294
+ out[childKey] = child;
295
+ continue;
296
+ }
297
+ if ((childKey === "key" || childKey === "name")
298
+ && child === from
299
+ && (rec["kind"] === "app" || rec["kind"] === "element")) {
300
+ out[childKey] = to;
301
+ continue;
302
+ }
303
+ out[childKey] = rebindRefNameDeep(child, from, to, childKey);
304
+ }
305
+ return out;
306
+ }
@@ -110,6 +110,10 @@ export interface FromTfContext {
110
110
  readonly fieldKey: string;
111
111
  readonly fieldName?: string;
112
112
  readonly fieldType?: string;
113
+ /** Static option labels from the ref-only catalog. Absent for a record-sourced Dropdown. */
114
+ readonly options?: readonly string[];
115
+ /** The platform Stage system field, from its canonical `STAGE` tag. */
116
+ readonly systemStage?: true;
113
117
  }>;
114
118
  /** Lower-cased field display name -> typed field key for each on-disk app/element catalog. */
115
119
  readonly fieldNamesByOwnerRefName?: ReadonlyMap<string, ReadonlyMap<string, string>>;
@@ -142,6 +146,12 @@ export interface FromTfContext {
142
146
  * stays silent. Undefined: no listed id, so only an empty id warns.
143
147
  */
144
148
  readonly omittedAutomationsById?: ReadonlyMap<string, OmittedAutomationIdentity>;
149
+ /**
150
+ * Ids of the access policies the export matched to the one the platform
151
+ * adds for an app's creator (platform-creator-policies.json, edk#2156).
152
+ * Pull notes them in source and changes nothing else.
153
+ */
154
+ readonly platformCreatorPolicyIds?: ReadonlySet<string>;
145
155
  /**
146
156
  * Foreign app/element display names this stream saw referenced (currently:
147
157
  * a RELATION field's `related_object_id` as a `data.elementum_app`/
@@ -0,0 +1,114 @@
1
+ import { type AdoptionAddressAlias } from "../../graph/index.js";
2
+ import { type ChildResourceScope } from "../tf/labels.js";
3
+ import type { TerraformStateResource } from "../ei/state.js";
4
+ import type { StreamRootExtract } from "./stream-root.js";
5
+ export interface FieldRefIdentity {
6
+ readonly ownerRefName: string;
7
+ readonly fieldKey: string;
8
+ readonly fieldName?: string;
9
+ /** The field's public authoring type (e.g. "USER", "GROUP") — see AppField's `type` discriminant. */
10
+ readonly fieldType?: string;
11
+ }
12
+ /**
13
+ * Each static Dropdown and Multi-Select field's current options, keyed by the
14
+ * field's resource label in state: option id → label (#2568). An option id is
15
+ * read as an option only of the field that lists it.
16
+ */
17
+ export type PicklistOptionsByField = Map<string, ReadonlyMap<string, string>>;
18
+ export interface PulledFieldRefsContext {
19
+ readonly fieldRefsById: Map<string, FieldRefIdentity>;
20
+ readonly picklistOptionsByField: PicklistOptionsByField;
21
+ readonly fieldNamesByOwnerRefName: Map<string, ReadonlyMap<string, string>>;
22
+ }
23
+ /**
24
+ * Minimal stream-root shape for collecting field import ids — printers cast
25
+ * NormalizedApp at the CLI boundary; engine must not import entities/.
26
+ */
27
+ export interface FieldRefOwnerRoot {
28
+ readonly refName: string;
29
+ /** Live export/tf label (app/element namespace). Import addresses use this, not tsLabelToTfLabel(authored refName). */
30
+ readonly namespace?: string;
31
+ readonly fields: readonly {
32
+ readonly key: string;
33
+ readonly field: {
34
+ readonly name?: unknown;
35
+ readonly type?: unknown;
36
+ };
37
+ }[];
38
+ }
39
+ /**
40
+ * The current options of every static Dropdown/Multi-Select field in OpenTofu
41
+ * state, by field (#2568). The platform exports scalar Dropdown assignments
42
+ * through an options-by-label expression, but exports Multi-Select assignments
43
+ * and some filter values as raw option UUIDs. State is the only authoritative
44
+ * place shared by both shapes that holds each option's id, label and field.
45
+ */
46
+ export declare function picklistOptionsByFieldFromState(resources: readonly {
47
+ readonly mode?: unknown;
48
+ readonly type?: unknown;
49
+ readonly name?: unknown;
50
+ readonly instances?: readonly {
51
+ readonly attributes?: unknown;
52
+ }[];
53
+ }[]): PicklistOptionsByField;
54
+ /** State-backed values for each static field's `<field>_options_by_label` local. */
55
+ export declare function picklistOptionLocalValuesFromState(resources: readonly {
56
+ readonly mode?: unknown;
57
+ readonly type?: unknown;
58
+ readonly name?: unknown;
59
+ readonly instances?: readonly {
60
+ readonly attributes?: unknown;
61
+ }[];
62
+ }[]): Map<string, string>;
63
+ /**
64
+ * Repair persisted field identities before extraction when state proves that
65
+ * an export label is an alias for the workspace's authored label.
66
+ *
67
+ * Some export payloads carry raw field UUIDs rather than resource references.
68
+ * Relabelling the parsed document cannot change those values, so their
69
+ * registry entries must move to the same authored bag key as well.
70
+ */
71
+ export declare function preserveAuthoredFieldRefKeys(fieldRefsById: Map<string, FieldRefIdentity>, importIds: ReadonlyMap<string, string>, aliases: readonly AdoptionAddressAlias[]): void;
72
+ /** display name (lower) → bag key, built from persisted/bootstrap field identities. */
73
+ export declare function buildFieldNamesByOwnerRefName(fieldRefsById: ReadonlyMap<string, FieldRefIdentity>): Map<string, ReadonlyMap<string, string>>;
74
+ /**
75
+ * The option ids build can name offline (#1733). `idsByLocal` maps each
76
+ * managed Dropdown, Multi-Select and app status field's
77
+ * `<label>_options_by_label` local to its label → id pairs, read from a local
78
+ * root `terraform.tfstate`. `labelById` holds every id → label that state and
79
+ * earlier pulls recorded, for fields state does not cover. Both are empty for
80
+ * an org that was never applied with local state or pulled.
81
+ */
82
+ export interface OptionIdIndex {
83
+ readonly idsByLocal: ReadonlyMap<string, ReadonlyMap<string, string>>;
84
+ readonly labelById: ReadonlyMap<string, string>;
85
+ }
86
+ export declare function readOptionIdIndex(orgRoot: string): Promise<OptionIdIndex>;
87
+ /** Authored field identities persisted by earlier pulls. Reads the manifest only. */
88
+ export declare function readManifestFieldRefs(orgRoot: string): Promise<ReadonlyMap<string, FieldRefIdentity>>;
89
+ /**
90
+ * Hydrate the in-memory registry for a pull run.
91
+ *
92
+ * `stateResources` is the pull's `readStateSnapshot` read, so a declared
93
+ * backend is seen too; without it only a local root `terraform.tfstate` is.
94
+ * The manifest key is authored and wins, except a key that is only the
95
+ * display-name slug a ref-only lookup guessed: there the managed state key
96
+ * wins (#1431), and the correction is persisted.
97
+ */
98
+ export declare function loadPulledFieldRefsContext(orgRoot: string, stateResources?: readonly TerraformStateResource[]): Promise<PulledFieldRefsContext>;
99
+ /** Back-compat alias — most callers only need the field-id map. */
100
+ export declare function loadFieldRefsRegistry(orgRoot: string): Promise<Map<string, FieldRefIdentity>>;
101
+ /** The registry file's own entries (no state-derived refs), as a pull found them before it changed any (edk#2628). */
102
+ export declare function readFieldRefsRegistryEntries(orgRoot: string): Promise<ReadonlyMap<string, FieldRefIdentity>>;
103
+ /**
104
+ * Put one root's registry entries back to `entries` (taken by {@link readFieldRefsRegistryEntries} before the
105
+ * pull), leaving every other root's entries as they are. A failed pull that restores the root's source calls
106
+ * this, so a later pull does not print refs to fields the restored source doesn't have (edk#2628).
107
+ */
108
+ export declare function restoreOwnerFieldRefs(orgRoot: string, ownerRefName: string, entries: ReadonlyMap<string, FieldRefIdentity>): Promise<void>;
109
+ /** Persist new entries — best-effort, never blocks the pull. */
110
+ export declare function mergeFieldRefsRegistry(orgRoot: string, additions: ReadonlyMap<string, FieldRefIdentity>, picklistAdditions?: ReadonlyMap<string, string>): Promise<void>;
111
+ /** Collect field-id identities from one stream-root extract's import blocks. */
112
+ export declare function collectFieldRefEntriesFromExtract(root: FieldRefOwnerRoot, extract: StreamRootExtract, scope: ChildResourceScope): Map<string, FieldRefIdentity>;
113
+ /** Merge extract-derived field ids into the pull ctx and persist for later runs. */
114
+ export declare function rememberPulledFieldIdentities(orgRoot: string, target: Map<string, FieldRefIdentity>, root: FieldRefOwnerRoot, extract: StreamRootExtract, scope: ChildResourceScope): Promise<void>;