@elementumai/edk 0.11.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 (222) hide show
  1. package/README.md +40 -6
  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/triggers/on-demand.d.ts +2 -0
  13. package/dist-sdk/src/core/triggers/on-demand.js +3 -0
  14. package/dist-sdk/src/core/types/app.d.ts +6 -0
  15. package/dist-sdk/src/engine/build/context.d.ts +3 -0
  16. package/dist-sdk/src/engine/coverage-gaps.d.ts +5 -0
  17. package/dist-sdk/src/engine/coverage-gaps.js +9 -0
  18. package/dist-sdk/src/engine/ei/run.d.ts +20 -1
  19. package/dist-sdk/src/engine/ei/run.js +102 -14
  20. package/dist-sdk/src/engine/pull/authored-address.js +42 -6
  21. package/dist-sdk/src/engine/pull/authored-root.d.ts +88 -0
  22. package/dist-sdk/src/engine/pull/authored-root.js +306 -0
  23. package/dist-sdk/src/engine/pull/context.d.ts +10 -0
  24. package/dist-sdk/src/engine/pull/field-refs-registry.d.ts +114 -0
  25. package/dist-sdk/src/engine/pull/field-refs-registry.js +501 -0
  26. package/dist-sdk/src/engine/pull/org.d.ts +1 -0
  27. package/dist-sdk/src/engine/pull/org.js +2 -0
  28. package/dist-sdk/src/engine/pull/partition.d.ts +8 -0
  29. package/dist-sdk/src/engine/pull/partition.js +43 -0
  30. package/dist-sdk/src/engine/pull/pulled-roots.d.ts +89 -0
  31. package/dist-sdk/src/engine/pull/pulled-roots.js +203 -0
  32. package/dist-sdk/src/engine/pull/ref-only.d.ts +22 -0
  33. package/dist-sdk/src/engine/pull/ref-only.js +59 -1
  34. package/dist-sdk/src/engine/pull/source-resources.d.ts +39 -0
  35. package/dist-sdk/src/engine/pull/source-resources.js +110 -0
  36. package/dist-sdk/src/engine/pull/stream-root.d.ts +148 -0
  37. package/dist-sdk/src/engine/pull/stream-root.js +563 -0
  38. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.d.ts +47 -0
  39. package/dist-sdk/src/engine/workspace/reserved-catalog-keys.js +115 -0
  40. package/dist-sdk/src/entities/access-policy/build.d.ts +2 -1
  41. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +9 -1
  42. package/dist-sdk/src/entities/access-policy/from-tf.js +25 -4
  43. package/dist-sdk/src/entities/access-policy/module.js +5 -0
  44. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +19 -0
  45. package/dist-sdk/src/entities/access-policy/to-tf.js +65 -8
  46. package/dist-sdk/src/entities/agent/build.d.ts +52 -1
  47. package/dist-sdk/src/entities/agent/build.js +34 -0
  48. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +68 -0
  49. package/dist-sdk/src/entities/agent/from-tf.d.ts +34 -1
  50. package/dist-sdk/src/entities/agent/from-tf.js +262 -2
  51. package/dist-sdk/src/entities/agent/index.d.ts +1 -1
  52. package/dist-sdk/src/entities/agent/to-tf.d.ts +8 -10
  53. package/dist-sdk/src/entities/agent/to-tf.js +158 -14
  54. package/dist-sdk/src/entities/agent-tool/from-tf.js +6 -0
  55. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +2 -2
  56. package/dist-sdk/src/entities/agent-tool/to-tf.js +2 -2
  57. package/dist-sdk/src/entities/app/build.d.ts +34 -14
  58. package/dist-sdk/src/entities/app/build.js +93 -16
  59. package/dist-sdk/src/entities/app/from-tf.js +25 -11
  60. package/dist-sdk/src/entities/app/index.d.ts +1 -0
  61. package/dist-sdk/src/entities/app/index.js +1 -0
  62. package/dist-sdk/src/entities/app/module.js +1 -0
  63. package/dist-sdk/src/entities/app/stage-keys.d.ts +20 -5
  64. package/dist-sdk/src/entities/app/stage-keys.js +43 -9
  65. package/dist-sdk/src/entities/app/to-tf.js +2 -0
  66. package/dist-sdk/src/entities/approval-chain/build.d.ts +46 -11
  67. package/dist-sdk/src/entities/approval-chain/build.js +120 -8
  68. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +24 -2
  69. package/dist-sdk/src/entities/approval-chain/from-tf.js +148 -6
  70. package/dist-sdk/src/entities/approval-chain/index.d.ts +4 -1
  71. package/dist-sdk/src/entities/approval-chain/index.js +4 -1
  72. package/dist-sdk/src/entities/approval-chain/module.js +23 -5
  73. package/dist-sdk/src/entities/approval-chain/printer.d.ts +1 -1
  74. package/dist-sdk/src/entities/approval-chain/printer.js +91 -5
  75. package/dist-sdk/src/entities/approval-chain/steps-tf.d.ts +77 -0
  76. package/dist-sdk/src/entities/approval-chain/steps-tf.js +255 -0
  77. package/dist-sdk/src/entities/approval-chain/steps.d.ts +71 -0
  78. package/dist-sdk/src/entities/approval-chain/steps.js +83 -0
  79. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +16 -6
  80. package/dist-sdk/src/entities/approval-chain/to-tf.js +37 -4
  81. package/dist-sdk/src/entities/automation/build.d.ts +50 -24
  82. package/dist-sdk/src/entities/automation/build.js +86 -33
  83. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +52 -8
  84. package/dist-sdk/src/entities/automation/from-tf.d.ts +38 -6
  85. package/dist-sdk/src/entities/automation/from-tf.js +855 -157
  86. package/dist-sdk/src/entities/automation/index.d.ts +2 -1
  87. package/dist-sdk/src/entities/automation/index.js +1 -0
  88. package/dist-sdk/src/entities/automation/module.d.ts +4 -3
  89. package/dist-sdk/src/entities/automation/module.js +33 -12
  90. package/dist-sdk/src/entities/automation/refs-read.d.ts +19 -0
  91. package/dist-sdk/src/entities/automation/refs-read.js +48 -0
  92. package/dist-sdk/src/entities/automation/run-target.d.ts +2 -0
  93. package/dist-sdk/src/entities/automation/run-target.js +5 -0
  94. package/dist-sdk/src/entities/automation/script-code.d.ts +2 -1
  95. package/dist-sdk/src/entities/automation/script-code.js +82 -1
  96. package/dist-sdk/src/entities/automation/script-lint.d.ts +13 -0
  97. package/dist-sdk/src/entities/automation/script-lint.js +418 -0
  98. package/dist-sdk/src/entities/automation/slack-message-refs.d.ts +9 -0
  99. package/dist-sdk/src/entities/automation/slack-message-refs.js +75 -0
  100. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +12 -1
  101. package/dist-sdk/src/entities/automation/task-output-labels.js +32 -1
  102. package/dist-sdk/src/entities/automation/tasks.d.ts +76 -18
  103. package/dist-sdk/src/entities/automation/tasks.js +52 -15
  104. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -0
  105. package/dist-sdk/src/entities/automation/to-tf.js +585 -97
  106. package/dist-sdk/src/entities/automation/triggers.d.ts +48 -23
  107. package/dist-sdk/src/entities/automation/triggers.js +27 -12
  108. package/dist-sdk/src/entities/automation/unsafe-script-output.d.ts +50 -0
  109. package/dist-sdk/src/entities/automation/unsafe-script-output.js +92 -0
  110. package/dist-sdk/src/entities/chart/build.d.ts +18 -2
  111. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  112. package/dist-sdk/src/entities/chart/from-tf.js +28 -1
  113. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  114. package/dist-sdk/src/entities/chart/printer.js +5 -2
  115. package/dist-sdk/src/entities/chart/to-tf.js +38 -3
  116. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +3 -0
  117. package/dist-sdk/src/entities/dynamic-layout/condition-keys.d.ts +48 -0
  118. package/dist-sdk/src/entities/dynamic-layout/condition-keys.js +261 -0
  119. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +45 -6
  120. package/dist-sdk/src/entities/dynamic-layout/module.js +2 -1
  121. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +46 -12
  122. package/dist-sdk/src/entities/element/audit-field-guard.d.ts +9 -0
  123. package/dist-sdk/src/entities/element/audit-field-guard.js +88 -0
  124. package/dist-sdk/src/entities/element/build.js +2 -1
  125. package/dist-sdk/src/entities/element/from-tf.js +15 -2
  126. package/dist-sdk/src/entities/element/module.js +3 -0
  127. package/dist-sdk/src/entities/element/system-fields.d.ts +13 -0
  128. package/dist-sdk/src/entities/element/system-fields.js +23 -0
  129. package/dist-sdk/src/entities/element/to-tf.js +2 -0
  130. package/dist-sdk/src/entities/field/build.d.ts +9 -0
  131. package/dist-sdk/src/entities/field/from-tf.d.ts +29 -1
  132. package/dist-sdk/src/entities/field/from-tf.js +99 -6
  133. package/dist-sdk/src/entities/field/module.js +12 -2
  134. package/dist-sdk/src/entities/field/to-tf.d.ts +13 -3
  135. package/dist-sdk/src/entities/field/to-tf.js +90 -46
  136. package/dist-sdk/src/entities/org/category.js +1 -0
  137. package/dist-sdk/src/entities/org/index.d.ts +1 -0
  138. package/dist-sdk/src/entities/org/index.js +1 -0
  139. package/dist-sdk/src/entities/org/role.js +5 -0
  140. package/dist-sdk/src/entities/org/voice-auth.d.ts +5 -0
  141. package/dist-sdk/src/entities/org/voice-auth.js +33 -0
  142. package/dist-sdk/src/entities/organization/build.d.ts +3 -0
  143. package/dist-sdk/src/entities/organization/build.js +2 -0
  144. package/dist-sdk/src/entities/organization/index.d.ts +1 -0
  145. package/dist-sdk/src/entities/organization/index.js +1 -0
  146. package/dist-sdk/src/entities/organization/to-tf.d.ts +2 -0
  147. package/dist-sdk/src/entities/organization/to-tf.js +59 -1
  148. package/dist-sdk/src/entities/organization/voice-auth.d.ts +60 -0
  149. package/dist-sdk/src/entities/organization/voice-auth.js +60 -0
  150. package/dist-sdk/src/entities/phone-service/build.d.ts +9 -1
  151. package/dist-sdk/src/entities/phone-service/build.js +1 -0
  152. package/dist-sdk/src/entities/phone-service/deserializer/print-phone-service.js +3 -0
  153. package/dist-sdk/src/entities/phone-service/from-tf.d.ts +1 -0
  154. package/dist-sdk/src/entities/phone-service/from-tf.js +8 -1
  155. package/dist-sdk/src/entities/phone-service/to-tf.js +16 -0
  156. package/dist-sdk/src/entities/record-create-form/from-tf.js +2 -2
  157. package/dist-sdk/src/entities/relationship/from-tf.js +7 -2
  158. package/dist-sdk/src/entities/relationship/module.js +2 -2
  159. package/dist-sdk/src/entities/relationship/pair-check.d.ts +6 -2
  160. package/dist-sdk/src/entities/relationship/pair-check.js +105 -18
  161. package/dist-sdk/src/entities/relationship/to-tf.js +5 -2
  162. package/dist-sdk/src/entities/role/permission-levels.d.ts +7 -0
  163. package/dist-sdk/src/entities/role/permission-levels.js +78 -0
  164. package/dist-sdk/src/entities/role/to-tf.js +32 -2
  165. package/dist-sdk/src/entities/service-account/module.d.ts +2 -1
  166. package/dist-sdk/src/entities/service-account/module.js +9 -1
  167. package/dist-sdk/src/entities/service-account/resource-type.d.ts +2 -0
  168. package/dist-sdk/src/entities/service-account/resource-type.js +2 -0
  169. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +5 -5
  170. package/dist-sdk/src/entities/service-account/role-fidelity.js +21 -13
  171. package/dist-sdk/src/entities/service-account/role-membership-check.d.ts +20 -0
  172. package/dist-sdk/src/entities/service-account/role-membership-check.js +80 -0
  173. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +15 -0
  174. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +36 -0
  175. package/dist-sdk/src/entities/shared/filters/ast.d.ts +4 -0
  176. package/dist-sdk/src/entities/shared/filters/index.d.ts +85 -14
  177. package/dist-sdk/src/entities/shared/filters/index.js +18 -6
  178. package/dist-sdk/src/entities/shared/filters/option-lookups.d.ts +57 -0
  179. package/dist-sdk/src/entities/shared/filters/option-lookups.js +108 -0
  180. package/dist-sdk/src/entities/shared/filters/print.js +9 -5
  181. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +12 -7
  182. package/dist-sdk/src/entities/shared/filters/tf-codec.js +9 -5
  183. package/dist-sdk/src/entities/shared/raw-option-id.d.ts +30 -0
  184. package/dist-sdk/src/entities/shared/raw-option-id.js +41 -0
  185. package/dist-sdk/src/entities/shared/tool-field-ref.js +6 -2
  186. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -3
  187. package/dist-sdk/src/entities/shared/types/field-types.js +3 -1
  188. package/dist-sdk/src/entities/skill/input-coverage.js +5 -2
  189. package/dist-sdk/src/entities/skill/module.js +2 -0
  190. package/dist-sdk/src/entities/sla/build.d.ts +96 -0
  191. package/dist-sdk/src/entities/sla/build.js +124 -0
  192. package/dist-sdk/src/entities/sla/from-tf.d.ts +40 -0
  193. package/dist-sdk/src/entities/sla/from-tf.js +164 -0
  194. package/dist-sdk/src/entities/sla/index.d.ts +1 -0
  195. package/dist-sdk/src/entities/sla/index.js +1 -0
  196. package/dist-sdk/src/entities/sla/module.d.ts +4 -0
  197. package/dist-sdk/src/entities/sla/module.js +73 -0
  198. package/dist-sdk/src/entities/sla/printer.d.ts +2 -0
  199. package/dist-sdk/src/entities/sla/printer.js +84 -0
  200. package/dist-sdk/src/entities/sla/to-tf.d.ts +12 -0
  201. package/dist-sdk/src/entities/sla/to-tf.js +81 -0
  202. package/dist-sdk/src/entities/table/build.d.ts +7 -2
  203. package/dist-sdk/src/entities/table/build.js +22 -1
  204. package/dist-sdk/src/entities/table/deserializer/normalize.d.ts +4 -1
  205. package/dist-sdk/src/entities/table/from-tf.js +89 -14
  206. package/dist-sdk/src/entities/table/index.d.ts +1 -1
  207. package/dist-sdk/src/entities/table/to-tf.js +41 -2
  208. package/dist-sdk/src/entities/task/from-tf.js +2 -1
  209. package/dist-sdk/src/entities/task/to-tf.js +1 -0
  210. package/dist-sdk/src/entities/view/from-tf.d.ts +8 -4
  211. package/dist-sdk/src/entities/view/from-tf.js +10 -9
  212. package/dist-sdk/src/entities/view/module.js +5 -0
  213. package/dist-sdk/src/entities/widget/from-tf.js +15 -4
  214. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +51 -4
  215. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  216. package/dist-sdk/src/graph/index.d.ts +20 -2
  217. package/dist-sdk/src/graph/index.js +19 -0
  218. package/dist-sdk/src/graph/modules.js +11 -1
  219. package/dist-sdk/src/graph/resource-types.d.ts +47 -0
  220. package/dist-sdk/src/graph/resource-types.js +62 -0
  221. package/dist-sdk/src/graph/types.d.ts +116 -6
  222. package/package.json +6 -3
@@ -1001,6 +1001,26 @@ export function runEiCapture(args, opts) {
1001
1001
  });
1002
1002
  });
1003
1003
  }
1004
+ function jsonDiagnosticLocation(fields) {
1005
+ const range = typeof fields.range === "object" && fields.range !== null ? fields.range : undefined;
1006
+ const file = typeof range?.filename === "string" && range.filename !== "" ? range.filename : undefined;
1007
+ const start = typeof range?.start === "object" && range.start !== null ? range.start : undefined;
1008
+ const line = typeof start?.line === "number" && Number.isInteger(start.line) && start.line > 0 ? start.line : undefined;
1009
+ // OpenTofu sets `address` only for some diagnostics; `snippet.context` is
1010
+ // the enclosing block header (`resource "type" "name"`), never the code.
1011
+ const snippet = typeof fields.snippet === "object" && fields.snippet !== null ? fields.snippet : undefined;
1012
+ const address = typeof fields.address === "string" && fields.address !== ""
1013
+ ? fields.address
1014
+ : typeof snippet?.context === "string" ? blockAddress(snippet.context) : undefined;
1015
+ if (file === undefined && address === undefined)
1016
+ return undefined;
1017
+ return { ...(file !== undefined ? { file } : {}), ...(file !== undefined && line !== undefined ? { line } : {}), ...(address !== undefined ? { address } : {}) };
1018
+ }
1019
+ /** `automations.tf line 27, elementum_x.y`: the location as one parenthetical. */
1020
+ export function formatTofuDiagnosticLocation(location) {
1021
+ const where = location.file === undefined ? undefined : location.line === undefined ? location.file : `${location.file} line ${location.line}`;
1022
+ return [where, location.address].filter((part) => part !== undefined).join(", ");
1023
+ }
1004
1024
  /** Parse the stable subset of OpenTofu's line-delimited JSON UI used by adoption. */
1005
1025
  export function parseTofuJsonEvent(line) {
1006
1026
  try {
@@ -1028,9 +1048,17 @@ export function parseTofuJsonEvent(line) {
1028
1048
  const fields = diagnostic;
1029
1049
  if (typeof fields.summary !== "string")
1030
1050
  return { type: "other" };
1031
- const detail = typeof fields.detail === "string" && fields.detail !== "" ? `: ${fields.detail}` : "";
1051
+ const detail = typeof fields.detail === "string" && fields.detail !== "" ? fields.detail : undefined;
1032
1052
  const level = fields.severity === "error" ? "ERROR" : fields.severity === "warning" ? "WARN" : "INFO";
1033
- return { type: "diagnostic", level, message: fields.summary + detail };
1053
+ const location = jsonDiagnosticLocation(fields);
1054
+ return {
1055
+ type: "diagnostic",
1056
+ level,
1057
+ message: detail !== undefined ? `${fields.summary}: ${detail}` : fields.summary,
1058
+ summary: fields.summary,
1059
+ ...(detail !== undefined ? { detail } : {}),
1060
+ ...(location !== undefined ? { location } : {}),
1061
+ };
1034
1062
  }
1035
1063
  return { type: "other" };
1036
1064
  }
@@ -1228,6 +1256,39 @@ const TOFU_SNIPPET_LINE = /^(?:\d+:|[\u251c\u2502\u2514]|\(and \d+ more\))/;
1228
1256
  /** `with var.x,` / `on main.tf line 4, in …:` lines; only dropped inside the leading location block. */
1229
1257
  const TOFU_WITH_LINE = /^with [^ ]+,$/;
1230
1258
  const TOFU_LOCATION_LINE = /^on .+ line \d+(?:, in .+)?:$/;
1259
+ /** The parts of a location line: file, line and the optional `in <block>`. */
1260
+ const TOFU_LOCATION_PARTS = /^on (.+) line (\d+)(?:, in (.+))?:$/;
1261
+ /** `resource "type" "name"` / `data "type" "name"`: a block header. */
1262
+ const TOFU_BLOCK_ADDRESS = /^(resource|data) "([^"]+)" "([^"]+)"$/;
1263
+ /** Any other top-level block header: `output "x"`, `module "m"`, `locals`. */
1264
+ const TOFU_BLOCK_HEADER = /^[a-z_]+(?: "[^"]+")?$/;
1265
+ /** The address a block header names: `type.name`, `data.type.name`, or the header as written. */
1266
+ function blockAddress(header) {
1267
+ const block = TOFU_BLOCK_ADDRESS.exec(header);
1268
+ if (block !== null)
1269
+ return block[1] === "data" ? `data.${block[2]}.${block[3]}` : `${block[2]}.${block[3]}`;
1270
+ return TOFU_BLOCK_HEADER.test(header) ? header : undefined;
1271
+ }
1272
+ /**
1273
+ * The location a human `Error:` block's leading paragraph names. The `with`
1274
+ * line carries the instance address; without one, a `resource`/`data` block
1275
+ * header gives the block address, and any other block (`output "x"`, `locals`)
1276
+ * is kept as written. Snippet and value lines are never read here.
1277
+ */
1278
+ function humanDiagnosticLocation(paragraph) {
1279
+ // Only the header lines: `with <address>,` then `on <file> line N, in …:`.
1280
+ const header = paragraph.slice(0, 2);
1281
+ const withLine = header.find((l) => TOFU_WITH_LINE.test(l));
1282
+ const withAddress = withLine?.slice("with ".length, -1);
1283
+ const parts = header.map((l) => TOFU_LOCATION_PARTS.exec(l)).find((m) => m !== null);
1284
+ const address = withAddress ?? (parts?.[3] !== undefined ? blockAddress(parts[3]) : undefined);
1285
+ if (parts === undefined && address === undefined)
1286
+ return undefined;
1287
+ return {
1288
+ ...(parts !== undefined ? { file: parts[1], line: Number(parts[2]) } : {}),
1289
+ ...(address !== undefined ? { address } : {}),
1290
+ };
1291
+ }
1231
1292
  /** Cap a diagnostic list to `max` entries, adding an "… and N more" line. */
1232
1293
  export function capTofuDiagnostics(diagnostics, max = TOFU_DIAGNOSTIC_MAX_ENTRIES) {
1233
1294
  if (diagnostics.length <= max)
@@ -1238,26 +1299,51 @@ export function capTofuDiagnostics(diagnostics, max = TOFU_DIAGNOSTIC_MAX_ENTRIE
1238
1299
  * Error diagnostics from a failed OpenTofu run: `diagnostic` events with
1239
1300
  * severity error from `-json` stdout, plus human `Error:` blocks from stderr.
1240
1301
  * Deduplicated, in order. Used to explain why `ei plan` failed instead of
1241
- * discarding its output (edk#1402).
1302
+ * discarding its output (edk#1402). Each names the file, line and resource
1303
+ * address OpenTofu reported, right after the summary (edk#2295):
1304
+ * `Invalid index (automations.tf line 27, elementum_x.y): The given key …`.
1242
1305
  */
1243
1306
  export function tofuErrorDiagnostics(stdout, stderr) {
1244
1307
  const out = [];
1245
- const seen = new Set();
1246
- const add = (message) => {
1247
- let trimmed = message.replace(/\s+/g, " ").trim();
1248
- if (trimmed.length > TOFU_DIAGNOSTIC_MAX_CHARS)
1249
- trimmed = `${trimmed.slice(0, TOFU_DIAGNOSTIC_MAX_CHARS)}… (truncated)`;
1250
- if (trimmed === "" || seen.has(trimmed))
1308
+ // The same error can come from JSON and from stderr: keep it once, and let
1309
+ // the copy that names a location replace one that doesn't. The same error
1310
+ // on two resources stays two entries.
1311
+ const texts = new Set();
1312
+ const byKey = new Map();
1313
+ const clean = (text) => text.replace(/\s+/g, " ").trim();
1314
+ const add = (summary, detail, location) => {
1315
+ const cleanSummary = clean(summary);
1316
+ const cleanDetail = detail === undefined ? "" : clean(detail);
1317
+ const key = cleanDetail !== "" ? `${cleanSummary}: ${cleanDetail}` : cleanSummary;
1318
+ if (key === "")
1319
+ return;
1320
+ const where = location === undefined ? "" : clean(formatTofuDiagnosticLocation(location));
1321
+ const head = where !== "" ? `${cleanSummary} (${where})` : cleanSummary;
1322
+ let text = cleanDetail !== "" ? `${head}: ${cleanDetail}` : head;
1323
+ if (text.length > TOFU_DIAGNOSTIC_MAX_CHARS)
1324
+ text = `${text.slice(0, TOFU_DIAGNOSTIC_MAX_CHARS)}… (truncated)`;
1325
+ if (texts.has(text))
1251
1326
  return;
1252
- seen.add(trimmed);
1253
- out.push(trimmed);
1327
+ const same = byKey.get(key) ?? [];
1328
+ if (where === "" && same.length > 0)
1329
+ return;
1330
+ const unlocated = where !== "" ? same.find((entry) => !entry.located) : undefined;
1331
+ texts.add(text);
1332
+ if (unlocated !== undefined) {
1333
+ out[unlocated.index] = text;
1334
+ unlocated.located = true;
1335
+ return;
1336
+ }
1337
+ same.push({ index: out.length, located: where !== "" });
1338
+ byKey.set(key, same);
1339
+ out.push(text);
1254
1340
  };
1255
1341
  for (const line of (stdout ?? "").split("\n")) {
1256
1342
  if (line.trim() === "")
1257
1343
  continue;
1258
1344
  const event = parseTofuJsonEvent(line);
1259
1345
  if (event.type === "diagnostic" && event.level === "ERROR")
1260
- add(event.message);
1346
+ add(event.summary, event.detail, event.location);
1261
1347
  }
1262
1348
  const lines = (stderr ?? "").split("\n").map((l) => l.replace(ANSI_SEQUENCE, "").replace(/\r$/, ""));
1263
1349
  for (let i = 0; i < lines.length; i++) {
@@ -1268,7 +1354,8 @@ export function tofuErrorDiagnostics(stdout, stderr) {
1268
1354
  // text output is: Error line, blank, location + source snippet (+ optional
1269
1355
  // ├──/│ expression values), blank, explanation. Drop the location paragraph
1270
1356
  // and any snippet/value lines so only the explanation is kept; snippets can
1271
- // carry config literals and non-sensitive variable values.
1357
+ // carry config literals and non-sensitive variable values. The location
1358
+ // paragraph's file, line and address are kept (edk#2295).
1272
1359
  const paragraphs = [[]];
1273
1360
  for (let j = i + 1; j < lines.length; j++) {
1274
1361
  const raw = lines[j];
@@ -1288,13 +1375,14 @@ export function tofuErrorDiagnostics(stdout, stderr) {
1288
1375
  // no line filter can recognise. Line filters remain a second layer for
1289
1376
  // snippet/value lines elsewhere.
1290
1377
  const isLocationBlock = (p) => TOFU_WITH_LINE.test(p[0]) || TOFU_LOCATION_LINE.test(p[0]);
1378
+ const location = nonEmpty.length > 0 && isLocationBlock(nonEmpty[0]) ? humanDiagnosticLocation(nonEmpty[0]) : undefined;
1291
1379
  const detail = nonEmpty
1292
1380
  .filter((p, idx) => !(idx === 0 && isLocationBlock(p)))
1293
1381
  .map((p) => p.filter((l) => !TOFU_SNIPPET_LINE.test(l)))
1294
1382
  .filter((p) => p.length > 0)
1295
1383
  .map((p) => p.join(" "))
1296
1384
  .join(" ");
1297
- add(detail !== "" ? `${match[1]}: ${detail}` : match[1]);
1385
+ add(match[1], detail !== "" ? detail : undefined, location);
1298
1386
  }
1299
1387
  return out;
1300
1388
  }
@@ -181,6 +181,7 @@ export function authoredAddressAmbiguityWarning(ambiguity) {
181
181
  * join throws rather than print one key twice.
182
182
  */
183
183
  function resolveAuthoredAddresses(importIds, authoredById, inState) {
184
+ assertEachObjectOnce(importIds);
184
185
  const exportAtSlot = new Map();
185
186
  for (const address of importIds.keys()) {
186
187
  const slot = labelSlot(address);
@@ -190,7 +191,11 @@ function resolveAuthoredAddresses(importIds, authoredById, inState) {
190
191
  else
191
192
  held.push(address);
192
193
  }
193
- const occupantsOf = (slot, except) => (exportAtSlot.get(slot) ?? []).filter((address) => address !== except);
194
+ // Export address → the authored address this pull moved it to.
195
+ const accepted = new Map();
196
+ // The export addresses still at a label. One this pull already moved has
197
+ // left it, so it holds nothing there (#2181).
198
+ const occupantsOf = (slot, except) => (exportAtSlot.get(slot) ?? []).filter((address) => address !== except && !accepted.has(address));
194
199
  const claimsBySlot = new Map();
195
200
  for (const [from, id] of importIds) {
196
201
  const type = addressType(from);
@@ -224,7 +229,6 @@ function resolveAuthoredAddresses(importIds, authoredById, inState) {
224
229
  // Authored labels of identities this export still has. One whose identity
225
230
  // is absent from the export was deleted live and does not hold its label.
226
231
  const liveAuthoredSlots = new Set([...authoredById].filter(([identity]) => exportIdentities.has(identity)).map(([, address]) => labelSlot(address)));
227
- const accepted = new Map();
228
232
  const acceptedSlots = new Set();
229
233
  const aliases = [];
230
234
  const accept = (from, to) => {
@@ -277,16 +281,16 @@ function resolveAuthoredAddresses(importIds, authoredById, inState) {
277
281
  for (let progressed = true; progressed && pending.size > 0;) {
278
282
  progressed = false;
279
283
  for (const [from, to] of pending) {
280
- const sourceId = importIds.get(from);
281
284
  const occupants = occupantsOf(labelSlot(to), from);
282
- const free = occupants.every((address) => canonicalImportId(importIds.get(address)) === canonicalImportId(sourceId));
283
- const vacated = occupants.length > 0 && occupants.every((address) => accepted.has(address));
285
+ // A label is free only when nothing sits on it. An occupant this pull
286
+ // already moved is not listed (#2181).
287
+ const free = occupants.length === 0;
284
288
  const occupant = occupants.length === 1 ? occupants[0] : undefined;
285
289
  const occupantIdentity = occupant === undefined ? undefined : typedIdentity(addressType(occupant), importIds.get(occupant));
286
290
  const occupantNew = occupantIdentity !== undefined && inState !== undefined && !inState.has(occupantIdentity) && !authoredById.has(occupantIdentity);
287
291
  const rotation = occupant !== undefined && pending.has(occupant) ? rotationFrom(from) : undefined;
288
292
  const occupantLabel = occupantNew ? freeLabelAfterChain(from) : undefined;
289
- if (free || vacated) {
293
+ if (free) {
290
294
  accept(from, to);
291
295
  pending.delete(from);
292
296
  }
@@ -335,6 +339,38 @@ function withLabelOf(address, labelSource) {
335
339
  function isFieldSlot(slot) {
336
340
  return slot.startsWith("\u0000field.");
337
341
  }
342
+ /**
343
+ * The export printed one platform object at two addresses. Renaming can't
344
+ * separate one object, so say what happened instead of asking for a rename
345
+ * (#2182).
346
+ */
347
+ function oneObjectTwiceError(addresses, id) {
348
+ return new Error(`pull stopped: the export holds one platform object twice, as ${addresses.join(" and ")} (both platform id ${id}). ` +
349
+ "They are the same object, so renaming can't separate them, and pulling both would bind it at two addresses. " +
350
+ "This is an export problem; report it with this message.");
351
+ }
352
+ /**
353
+ * Stop before any move when the export prints one platform object at two
354
+ * addresses (#2182): two blocks of one type with the same platform id, or two
355
+ * field blocks with the same platform id across field types (one field has
356
+ * one type, so its id at two field types is still one field). Moving or
357
+ * keeping either block would bind that object at two addresses. Other types
358
+ * may share a platform id on purpose (a composite resource exposes two
359
+ * provider types backed by one object), so only these two cases stop.
360
+ */
361
+ function assertEachObjectOnce(importIds) {
362
+ const seen = new Map();
363
+ for (const [address, importId] of importIds) {
364
+ const type = addressType(address);
365
+ if (type === undefined)
366
+ continue;
367
+ const key = FIELD_RESOURCE_TYPE_SET.has(type) ? `\u0000field\u0000${canonicalImportId(importId)}` : typedIdentity(type, importId);
368
+ const first = seen.get(key);
369
+ if (first !== undefined)
370
+ throw oneObjectTwiceError([first, address], canonicalImportId(importId));
371
+ seen.set(key, address);
372
+ }
373
+ }
338
374
  /**
339
375
  * Two fields at one label would print one bag key twice, and the build would
340
376
  * keep only the second, planning to replace the other's live field (#1859).
@@ -0,0 +1,88 @@
1
+ export type AuthoredRootBag = "apps" | "elements" | "tasks";
2
+ export interface AuthoredRoot {
3
+ readonly refName: string;
4
+ readonly namespace?: string;
5
+ }
6
+ export declare function readAuthoredRootNamespace(source: string): string | undefined;
7
+ export declare function listAuthoredRoots(orgRoot: string, bag: AuthoredRootBag): readonly AuthoredRoot[];
8
+ /**
9
+ * Last-write-wins namespace → refName index (same contract as the previous
10
+ * `readNamespaceMap` scan). Duplicate namespaces stay visible to
11
+ * {@link resolveAuthoredRootRefName} via {@link listAuthoredRoots}.
12
+ */
13
+ export declare function authoredNamespaceMap(orgRoot: string, bag: AuthoredRootBag): Map<string, string>;
14
+ /** Case-insensitive map lookup; exact key wins, otherwise a unique fold match. */
15
+ export declare function lookupNamespaceMap(map: ReadonlyMap<string, string>, namespace: string): string | undefined;
16
+ export interface ResolveAuthoredRootRefNameOptions {
17
+ readonly orgRoot: string;
18
+ readonly bag: AuthoredRootBag;
19
+ readonly liveNamespace: string;
20
+ readonly extractedRefName: string;
21
+ }
22
+ /**
23
+ * Existing authored stream-root whose identity matches `liveNamespace`, or
24
+ * `undefined` when pull should create/use the extract-derived path.
25
+ */
26
+ export declare function findAuthoredRootRefName(options: ResolveAuthoredRootRefNameOptions): string | undefined;
27
+ /**
28
+ * Pull keeps an app or element in `<bag>/<refName>/` only when that folder
29
+ * name isn't an org entry (edk#2839; `tables` only while a table catalog is
30
+ * emitted). Pulled source names a root by its folder (`catalog.<refName>`
31
+ * in agents, automations and fields), not by the barrel key, so an element
32
+ * the barrel exposes as `catalog.groups2` beside `apps/groups/` would still
33
+ * be printed as `catalog.groups`, the org entry. It moves to
34
+ * reservedRootFolder instead (`groups3`), where folder and key agree.
35
+ * `tablesEmitted` defaults to whether a table catalog is on disk.
36
+ */
37
+ export declare function rootIsShadowed(orgRoot: string, refName: string, tablesEmitted?: boolean): boolean;
38
+ /**
39
+ * Choose the on-disk stream-root refName to write/adopt. Prefers an existing
40
+ * authored tree whose `namespace:` matches the live namespace
41
+ * (case-insensitive). Falls back to a case-insensitive directory name match
42
+ * against the live namespace when the file has no parseable namespace.
43
+ * Otherwise returns the extracted refName (first pull), or
44
+ * {@link reservedRootFolder} (`users2`, …) when that is a reserved `@catalog`
45
+ * key (`users`, `groups`, …).
46
+ */
47
+ export declare function resolveAuthoredRootRefName(options: ResolveAuthoredRootRefNameOptions): string;
48
+ /**
49
+ * The folder for an app or element whose export ref name is a reserved
50
+ * `@catalog` key (`users` → `users2`, edk#2839). A `<base>N` folder in `bag`
51
+ * that already holds `liveNamespace` is reused (the lowest such N), so a
52
+ * re-pull keeps its folder. Otherwise the first `<base>N` (N ≥ 2) that no app
53
+ * or element folder uses and that isn't already another element's catalog
54
+ * key (`vacated` names the folder this root is leaving, whose key it takes):
55
+ * apps and elements share one key space, so a name taken there would shift a
56
+ * key (`elements/users2/` beside `apps/users2/` is `catalog.users22`).
57
+ */
58
+ export declare function reservedRootFolder(orgRoot: string, bag: "apps" | "elements", base: string, liveNamespace?: string, vacated?: string): string;
59
+ /**
60
+ * After pull wrote a root that moved off a reserved key (`users` →
61
+ * `users2`), remove the dependency stub an older pull left at
62
+ * `<bag>/<extractedRefName>/` (only `generated/`) when the barrel shadows
63
+ * it, so the workspace holds one tree for the namespace. Call it only once
64
+ * the new root is on disk. Source there is never touched. Returns whether it
65
+ * removed one.
66
+ */
67
+ export declare function retireShadowedStub(orgRoot: string, bag: AuthoredRootBag, extractedRefName: string, refName: string): boolean;
68
+ /**
69
+ * The log line for a pull that writes `<bag>/<refName>/` instead of the
70
+ * export's ref name: an existing authored tree, or a new folder because the
71
+ * export's name is a reserved `@catalog` key (edk#2839).
72
+ */
73
+ export declare function authoredRootChoiceMessage(orgRoot: string, bag: AuthoredRootBag, refName: string, extractedRefName: string, namespace: string): string;
74
+ /**
75
+ * Rewrite a pulled stream-root so printers emit the authored directory
76
+ * casing (`const eDKCloudBuilder`, `parent: "eDKCloudBuilder"`) instead of
77
+ * the extract-derived export label. Never touches `namespace` — that stays
78
+ * the live platform address.
79
+ */
80
+ export declare function rebindAuthoredRootRefName<T extends {
81
+ readonly refName: string;
82
+ }>(root: T, authoredRefName: string): T;
83
+ /**
84
+ * Rewrite extract-time owner handles on an own-file child (automation,
85
+ * agent, …) so printers emit `catalog.eDKCloudBuilder.fields…` instead of
86
+ * the export-label key (`catalog.edkcloudbuilder.fields…`).
87
+ */
88
+ export declare function rebindAuthoredOwnerRefs<T>(value: T, extractedOwnerRefName: string, authoredOwnerRefName: string): T;
@@ -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
+ }