@elementumai/edk 0.10.4 → 0.12.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 (171) hide show
  1. package/README.md +49 -13
  2. package/dist-sdk/src/catalog/token.js +2 -1
  3. package/dist-sdk/src/core/triggers/on-demand.d.ts +2 -0
  4. package/dist-sdk/src/core/triggers/on-demand.js +3 -0
  5. package/dist-sdk/src/core/wire/ref-serializer.js +26 -1
  6. package/dist-sdk/src/engine/build/context.d.ts +4 -0
  7. package/dist-sdk/src/engine/coverage-gaps.d.ts +7 -0
  8. package/dist-sdk/src/engine/coverage-gaps.js +12 -0
  9. package/dist-sdk/src/engine/ei/json-stream-reader.d.ts +43 -0
  10. package/dist-sdk/src/engine/ei/json-stream-reader.js +234 -0
  11. package/dist-sdk/src/engine/ei/run.d.ts +42 -1
  12. package/dist-sdk/src/engine/ei/run.js +201 -32
  13. package/dist-sdk/src/engine/ei/saved-plan.d.ts +16 -0
  14. package/dist-sdk/src/engine/ei/saved-plan.js +19 -0
  15. package/dist-sdk/src/engine/ei/state.d.ts +1 -1
  16. package/dist-sdk/src/engine/ei/state.js +17 -4
  17. package/dist-sdk/src/engine/progress.d.ts +3 -1
  18. package/dist-sdk/src/engine/progress.js +7 -3
  19. package/dist-sdk/src/engine/pull/authored-address.d.ts +15 -1
  20. package/dist-sdk/src/engine/pull/authored-address.js +180 -29
  21. package/dist-sdk/src/engine/pull/context.d.ts +37 -2
  22. package/dist-sdk/src/engine/pull/context.js +7 -4
  23. package/dist-sdk/src/engine/pull/ref-only.d.ts +18 -0
  24. package/dist-sdk/src/engine/pull/ref-only.js +52 -0
  25. package/dist-sdk/src/engine/tf/index.d.ts +2 -2
  26. package/dist-sdk/src/engine/tf/index.js +2 -2
  27. package/dist-sdk/src/engine/tf/labels.d.ts +22 -0
  28. package/dist-sdk/src/engine/tf/labels.js +50 -0
  29. package/dist-sdk/src/engine/tf/model.d.ts +2 -0
  30. package/dist-sdk/src/engine/tf/model.js +26 -0
  31. package/dist-sdk/src/engine/validation.d.ts +2 -0
  32. package/dist-sdk/src/entities/access-policy/from-tf.d.ts +18 -0
  33. package/dist-sdk/src/entities/access-policy/from-tf.js +58 -24
  34. package/dist-sdk/src/entities/access-policy/member-list.d.ts +32 -0
  35. package/dist-sdk/src/entities/access-policy/member-list.js +57 -0
  36. package/dist-sdk/src/entities/access-policy/module.js +10 -0
  37. package/dist-sdk/src/entities/access-policy/to-tf.d.ts +4 -3
  38. package/dist-sdk/src/entities/access-policy/to-tf.js +21 -12
  39. package/dist-sdk/src/entities/agent/build.js +7 -5
  40. package/dist-sdk/src/entities/agent/deserializer/print-agent-v2.js +2 -0
  41. package/dist-sdk/src/entities/agent/from-tf.js +13 -3
  42. package/dist-sdk/src/entities/agent/to-tf.js +11 -5
  43. package/dist-sdk/src/entities/agent/tools.d.ts +8 -0
  44. package/dist-sdk/src/entities/agent/tools.js +6 -2
  45. package/dist-sdk/src/entities/agent-tool/from-tf.d.ts +2 -0
  46. package/dist-sdk/src/entities/agent-tool/to-tf.d.ts +29 -0
  47. package/dist-sdk/src/entities/agent-tool/to-tf.js +56 -3
  48. package/dist-sdk/src/entities/agent-tool/types.d.ts +12 -8
  49. package/dist-sdk/src/entities/agent-tool/types.js +13 -9
  50. package/dist-sdk/src/entities/app/build.d.ts +12 -1
  51. package/dist-sdk/src/entities/app/build.js +80 -4
  52. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +5 -7
  53. package/dist-sdk/src/entities/app/from-tf.js +17 -12
  54. package/dist-sdk/src/entities/app/stage-keys.d.ts +18 -3
  55. package/dist-sdk/src/entities/app/stage-keys.js +40 -6
  56. package/dist-sdk/src/entities/app/to-tf.js +7 -4
  57. package/dist-sdk/src/entities/automation/build.d.ts +52 -31
  58. package/dist-sdk/src/entities/automation/build.js +59 -20
  59. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +7 -4
  60. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +39 -14
  61. package/dist-sdk/src/entities/automation/from-tf.d.ts +35 -2
  62. package/dist-sdk/src/entities/automation/from-tf.js +721 -93
  63. package/dist-sdk/src/entities/automation/index.d.ts +1 -1
  64. package/dist-sdk/src/entities/automation/module.d.ts +22 -2
  65. package/dist-sdk/src/entities/automation/module.js +244 -57
  66. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +22 -2
  67. package/dist-sdk/src/entities/automation/output-key-wire-name.js +54 -3
  68. package/dist-sdk/src/entities/automation/run-target.d.ts +61 -0
  69. package/dist-sdk/src/entities/automation/run-target.js +104 -0
  70. package/dist-sdk/src/entities/automation/script-code.d.ts +11 -1
  71. package/dist-sdk/src/entities/automation/script-code.js +106 -4
  72. package/dist-sdk/src/entities/automation/script-lint.d.ts +13 -0
  73. package/dist-sdk/src/entities/automation/script-lint.js +418 -0
  74. package/dist-sdk/src/entities/automation/task-output-labels.d.ts +17 -1
  75. package/dist-sdk/src/entities/automation/task-output-labels.js +58 -1
  76. package/dist-sdk/src/entities/automation/tasks.d.ts +67 -22
  77. package/dist-sdk/src/entities/automation/tasks.js +18 -4
  78. package/dist-sdk/src/entities/automation/to-tf.d.ts +1 -3
  79. package/dist-sdk/src/entities/automation/to-tf.js +354 -64
  80. package/dist-sdk/src/entities/automation/triggers.d.ts +63 -11
  81. package/dist-sdk/src/entities/automation/triggers.js +45 -5
  82. package/dist-sdk/src/entities/automation/types.d.ts +21 -0
  83. package/dist-sdk/src/entities/automation/types.js +26 -0
  84. package/dist-sdk/src/entities/chart/build.d.ts +9 -1
  85. package/dist-sdk/src/entities/chart/from-tf.d.ts +2 -2
  86. package/dist-sdk/src/entities/chart/from-tf.js +25 -1
  87. package/dist-sdk/src/entities/chart/index.d.ts +1 -1
  88. package/dist-sdk/src/entities/chart/printer.js +5 -2
  89. package/dist-sdk/src/entities/chart/to-tf.js +19 -1
  90. package/dist-sdk/src/entities/dashboard/from-tf.d.ts +11 -1
  91. package/dist-sdk/src/entities/dashboard/from-tf.js +57 -7
  92. package/dist-sdk/src/entities/dashboard/to-tf.js +13 -0
  93. package/dist-sdk/src/entities/dynamic-layout/build.d.ts +8 -2
  94. package/dist-sdk/src/entities/dynamic-layout/condition-keys.d.ts +48 -0
  95. package/dist-sdk/src/entities/dynamic-layout/condition-keys.js +261 -0
  96. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  97. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +66 -20
  98. package/dist-sdk/src/entities/dynamic-layout/module.js +2 -1
  99. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +4 -2
  100. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +341 -32
  101. package/dist-sdk/src/entities/element/build.d.ts +10 -0
  102. package/dist-sdk/src/entities/element/build.js +1 -0
  103. package/dist-sdk/src/entities/element/from-tf.js +14 -9
  104. package/dist-sdk/src/entities/element/to-tf.js +7 -4
  105. package/dist-sdk/src/entities/field/from-tf.d.ts +24 -0
  106. package/dist-sdk/src/entities/field/from-tf.js +79 -1
  107. package/dist-sdk/src/entities/field/module.js +14 -1
  108. package/dist-sdk/src/entities/field/to-tf.d.ts +38 -3
  109. package/dist-sdk/src/entities/field/to-tf.js +108 -34
  110. package/dist-sdk/src/entities/file-reader/module.js +3 -3
  111. package/dist-sdk/src/entities/file-reader/to-tf.js +3 -3
  112. package/dist-sdk/src/entities/file-reader/types.d.ts +4 -16
  113. package/dist-sdk/src/entities/file-reader/types.js +7 -0
  114. package/dist-sdk/src/entities/org/group.d.ts +1 -0
  115. package/dist-sdk/src/entities/org/group.js +2 -1
  116. package/dist-sdk/src/entities/org/role.js +5 -0
  117. package/dist-sdk/src/entities/record-create-form/from-tf.d.ts +8 -0
  118. package/dist-sdk/src/entities/record-create-form/from-tf.js +10 -2
  119. package/dist-sdk/src/entities/record-create-form/to-tf.d.ts +2 -1
  120. package/dist-sdk/src/entities/record-create-form/to-tf.js +14 -2
  121. package/dist-sdk/src/entities/relationship/from-tf.d.ts +8 -0
  122. package/dist-sdk/src/entities/relationship/from-tf.js +88 -10
  123. package/dist-sdk/src/entities/relationship/to-tf.d.ts +3 -2
  124. package/dist-sdk/src/entities/relationship/to-tf.js +79 -8
  125. package/dist-sdk/src/entities/role/from-tf.js +24 -7
  126. package/dist-sdk/src/entities/role/to-tf.js +25 -7
  127. package/dist-sdk/src/entities/service-account/from-tf.js +2 -1
  128. package/dist-sdk/src/entities/service-account/module.js +20 -0
  129. package/dist-sdk/src/entities/service-account/role-fidelity.d.ts +5 -5
  130. package/dist-sdk/src/entities/service-account/role-fidelity.js +21 -13
  131. package/dist-sdk/src/entities/service-account/to-tf.js +12 -4
  132. package/dist-sdk/src/entities/shared/filters/ast.d.ts +2 -0
  133. package/dist-sdk/src/entities/shared/filters/tf-codec.d.ts +1 -1
  134. package/dist-sdk/src/entities/shared/filters/tf-codec.js +12 -7
  135. package/dist-sdk/src/entities/shared/types/field-types.d.ts +6 -3
  136. package/dist-sdk/src/entities/shared/types/field-types.js +3 -1
  137. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.d.ts +5 -2
  138. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +8 -1
  139. package/dist-sdk/src/entities/skill/from-tf.js +10 -3
  140. package/dist-sdk/src/entities/skill/module.js +18 -0
  141. package/dist-sdk/src/entities/skill/to-tf.d.ts +8 -1
  142. package/dist-sdk/src/entities/skill/to-tf.js +23 -14
  143. package/dist-sdk/src/entities/skill/tools.d.ts +8 -0
  144. package/dist-sdk/src/entities/skill/tools.js +6 -2
  145. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  146. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +8 -0
  147. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -2
  148. package/dist-sdk/src/entities/task/to-tf.js +1 -0
  149. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.d.ts +8 -2
  150. package/dist-sdk/src/entities/view/agent-view-layout-from-tf.js +20 -10
  151. package/dist-sdk/src/entities/view/from-tf.d.ts +68 -4
  152. package/dist-sdk/src/entities/view/from-tf.js +394 -22
  153. package/dist-sdk/src/entities/view/module.js +20 -0
  154. package/dist-sdk/src/entities/view/portable.d.ts +11 -0
  155. package/dist-sdk/src/entities/view/portable.js +47 -0
  156. package/dist-sdk/src/entities/view/to-tf.d.ts +4 -1
  157. package/dist-sdk/src/entities/view/to-tf.js +25 -7
  158. package/dist-sdk/src/entities/view/types.js +1 -1
  159. package/dist-sdk/src/entities/widget/build.d.ts +4 -3
  160. package/dist-sdk/src/entities/widget/from-tf.d.ts +3 -0
  161. package/dist-sdk/src/entities/widget/from-tf.js +100 -3
  162. package/dist-sdk/src/entities/widget/to-tf.d.ts +16 -1
  163. package/dist-sdk/src/entities/widget/to-tf.js +77 -14
  164. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +30 -9
  165. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  166. package/dist-sdk/src/graph/field-resource-types.d.ts +2 -0
  167. package/dist-sdk/src/graph/field-resource-types.js +11 -0
  168. package/dist-sdk/src/graph/index.d.ts +41 -3
  169. package/dist-sdk/src/graph/index.js +24 -2
  170. package/dist-sdk/src/graph/types.d.ts +195 -5
  171. package/package.json +1 -1
@@ -24,6 +24,7 @@ import { homedir } from "node:os";
24
24
  import { constants as osConstants } from "node:os";
25
25
  import { delimiter, isAbsolute, join, resolve } from "node:path";
26
26
  import { applyProgressEvent, incrementProgress, progressStream, resumeProgress, suspendProgress, updateProgress, withProgressBatch, writeProgress, writeTechnicalLog, writeUserOutput, writeUserPayload } from "../progress.js";
27
+ import { SavedPlanReader } from "./saved-plan.js";
27
28
  import { createLogWriter, parseBridgeLogEvent, parsePartialReadEvent, parseProgressEvent } from "../logging.js";
28
29
  const runtimeLog = createLogWriter();
29
30
  /** Shell convention for signal death: 128 + signal number (130 = SIGINT). */
@@ -634,7 +635,7 @@ export function runEiWithStatus(args, opts) {
634
635
  };
635
636
  const userOutput = opts?.userOutput ?? (process.stdout.isTTY === true ? process.stdout : progressStream());
636
637
  const output = Promise.all([
637
- routeEiOutput(child.stdout, process.stdout, opts?.bridge === true ? (line) => {
638
+ routeEiOutput(child.stdout, userOutput, opts?.bridge === true ? (line) => {
638
639
  const event = parseProgressEvent(line);
639
640
  if (event !== undefined) {
640
641
  withProgressBatch(() => {
@@ -650,7 +651,7 @@ export function runEiWithStatus(args, opts) {
650
651
  return false;
651
652
  writeCapturedTechnicalLine(line);
652
653
  return true;
653
- } : consumeNonBridgeTofuLine, (text, destination) => writeUserOutput(text, opts?.bridge === true ? userOutput : destination)),
654
+ } : consumeNonBridgeTofuLine, (text) => writeUserOutput(text, userOutput)),
654
655
  routeEiOutput(child.stderr, process.stderr, opts?.bridge === true ? (line) => {
655
656
  const event = parseProgressEvent(line);
656
657
  if (event !== undefined) {
@@ -742,7 +743,24 @@ export function runOpenTofuWithStatus(args, opts) {
742
743
  });
743
744
  }
744
745
  /** Capture bounded, machine-consumed OpenTofu stdout while preserving stderr. */
745
- export function runOpenTofuCapture(args, opts) {
746
+ export async function runOpenTofuCapture(args, opts) {
747
+ const chunks = [];
748
+ let size = 0;
749
+ await runOpenTofuStreaming(args, opts, (chunk) => {
750
+ size += chunk.length;
751
+ if (size > CAPTURE_LIMIT_BYTES)
752
+ throw new EiRunError(`managed OpenTofu output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null);
753
+ chunks.push(chunk);
754
+ });
755
+ return Buffer.concat(chunks).toString("utf8");
756
+ }
757
+ /**
758
+ * Run OpenTofu with machine-consumed stdout handed to `onStdout` chunk by
759
+ * chunk, unbuffered; stderr is captured bounded as in {@link runOpenTofuCapture}.
760
+ * When `onStdout` throws, OpenTofu is stopped and the promise rejects with
761
+ * that error.
762
+ */
763
+ function runOpenTofuStreaming(args, opts, onStdout) {
746
764
  return new Promise((resolvePromise, reject) => {
747
765
  let child;
748
766
  try {
@@ -756,28 +774,38 @@ export function runOpenTofuCapture(args, opts) {
756
774
  reject(error);
757
775
  return;
758
776
  }
759
- const chunks = [];
760
777
  const stderrChunks = [];
761
- let size = 0;
778
+ let stderrSize = 0;
762
779
  let settled = false;
763
780
  const stopForwarding = forwardSignalsToChild(child);
764
- const collect = (destination, echo) => (chunk) => {
781
+ const abort = (error) => {
782
+ settled = true;
783
+ stopForwarding();
784
+ child.kill();
785
+ reject(error);
786
+ };
787
+ child.stdout?.on("data", (chunk) => {
765
788
  if (settled)
766
789
  return;
767
- size += chunk.length;
768
- if (size > CAPTURE_LIMIT_BYTES) {
769
- settled = true;
770
- stopForwarding();
771
- child.kill();
772
- reject(new EiRunError(`managed OpenTofu output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null));
790
+ try {
791
+ onStdout(chunk);
792
+ }
793
+ catch (error) {
794
+ abort(error);
795
+ }
796
+ });
797
+ child.stderr?.on("data", (chunk) => {
798
+ if (settled)
799
+ return;
800
+ stderrSize += chunk.length;
801
+ if (stderrSize > CAPTURE_LIMIT_BYTES) {
802
+ abort(new EiRunError(`managed OpenTofu output exceeded ${CAPTURE_LIMIT_BYTES} bytes`, null));
773
803
  return;
774
804
  }
775
- destination.push(chunk);
776
- if (echo)
805
+ stderrChunks.push(chunk);
806
+ if (opts?.suppressStderr !== true)
777
807
  progressStream().write(chunk);
778
- };
779
- child.stdout?.on("data", collect(chunks, false));
780
- child.stderr?.on("data", collect(stderrChunks, opts?.suppressStderr !== true));
808
+ });
781
809
  child.on("error", (error) => {
782
810
  stopForwarding();
783
811
  if (settled)
@@ -796,10 +824,48 @@ export function runOpenTofuCapture(args, opts) {
796
824
  reject(new EiRunError(`managed OpenTofu exited with code ${exit}`, exit, stderr));
797
825
  return;
798
826
  }
799
- resolvePromise(Buffer.concat(chunks).toString("utf8"));
827
+ resolvePromise();
800
828
  });
801
829
  });
802
830
  }
831
+ /** Most stderr lines kept when a failed `tofu show` printed no `Error:` block. */
832
+ const SHOW_STDERR_TAIL_LINES = 20;
833
+ /**
834
+ * `tofu show -json <planPath>` for an EDK check of a saved plan (edk#2057),
835
+ * read as it streams so a plan of any size fits (edk#1861): only
836
+ * `resource_changes` and `prior_state` are kept ({@link SavedPlanReader}).
837
+ * The capture keeps OpenTofu's stderr off the terminal, so a failure would
838
+ * otherwise reach the user as a bare exit code. Reject with the EDK step
839
+ * that read the plan and OpenTofu's own `Error:` diagnostics (or, when it
840
+ * printed none, the tail of its stderr) instead. Output that is not one
841
+ * complete JSON object rejects too. Callers still stop: a plan that cannot
842
+ * be read back is never applied unchecked.
843
+ */
844
+ export async function readSavedPlan(planPath, opts) {
845
+ const where = `${opts.step} failed: \`tofu show -json ${planPath}\` in ${opts.cwd}`;
846
+ const reader = new SavedPlanReader();
847
+ try {
848
+ await runOpenTofuStreaming(["show", "-json", planPath], { cwd: opts.cwd, suppressStderr: true, binary: opts.binary }, (chunk) => reader.write(chunk));
849
+ return reader.end();
850
+ }
851
+ catch (error) {
852
+ if (!(error instanceof EiRunError))
853
+ throw new EiRunError(`${where}: ${error.message}`, null);
854
+ const diagnostics = tofuErrorDiagnostics(undefined, error.stderr);
855
+ const detail = diagnostics.length > 0
856
+ ? capTofuDiagnostics(diagnostics).map((d) => (d.startsWith("… and ") ? d : `Error: ${d}`))
857
+ : stderrTail(error.stderr);
858
+ throw new EiRunError(`${where}: ${error.message}` +
859
+ (detail.length > 0 ? `\n${detail.join("\n")}` : " (OpenTofu wrote nothing to stderr)"), error.exitCode, error.stderr, error.stdout);
860
+ }
861
+ }
862
+ function stderrTail(stderr) {
863
+ const lines = (stderr ?? "")
864
+ .split("\n")
865
+ .map((line) => line.replace(ANSI_SEQUENCE, "").replace(/\r$/, "").trimEnd())
866
+ .filter((line) => line.trim() !== "");
867
+ return lines.slice(-SHOW_STDERR_TAIL_LINES).map((line) => line.length > TOFU_DIAGNOSTIC_MAX_CHARS ? `${line.slice(0, TOFU_DIAGNOSTIC_MAX_CHARS)}… (truncated)` : line);
868
+ }
803
869
  /**
804
870
  * Run `ei` capturing stdout (the machine-consumed stream); stderr is routed by
805
871
  * EDK to the diagnostics sink. Non-zero exit rejects — partial output must be
@@ -809,6 +875,10 @@ export function runOpenTofuCapture(args, opts) {
809
875
  * captured commands whose output is also the user's only progress signal
810
876
  * (adoption's `ei plan`). It never moves anything onto our stdout, so the
811
877
  * caller's single-JSON-summary contract holds.
878
+ *
879
+ * `onStdout` hands stdout to the caller chunk by chunk instead of buffering
880
+ * it, with no size cap (edk#2248), and the promise resolves to "". When it
881
+ * throws, `ei` is stopped and the promise rejects with that error.
812
882
  */
813
883
  export function runEiCapture(args, opts) {
814
884
  return new Promise((resolvePromise, reject) => {
@@ -858,6 +928,17 @@ export function runEiCapture(args, opts) {
858
928
  const onData = (destination, echoTo) => (chunk) => {
859
929
  if (settled)
860
930
  return;
931
+ if (opts?.onStdout !== undefined && destination === chunks) {
932
+ try {
933
+ opts.onStdout(chunk);
934
+ }
935
+ catch (error) {
936
+ settled = true;
937
+ child.kill();
938
+ reject(error);
939
+ }
940
+ return;
941
+ }
861
942
  size += chunk.length;
862
943
  if (size > CAPTURE_LIMIT_BYTES) {
863
944
  settled = true;
@@ -920,6 +1001,26 @@ export function runEiCapture(args, opts) {
920
1001
  });
921
1002
  });
922
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
+ }
923
1024
  /** Parse the stable subset of OpenTofu's line-delimited JSON UI used by adoption. */
924
1025
  export function parseTofuJsonEvent(line) {
925
1026
  try {
@@ -947,9 +1048,17 @@ export function parseTofuJsonEvent(line) {
947
1048
  const fields = diagnostic;
948
1049
  if (typeof fields.summary !== "string")
949
1050
  return { type: "other" };
950
- const detail = typeof fields.detail === "string" && fields.detail !== "" ? `: ${fields.detail}` : "";
1051
+ const detail = typeof fields.detail === "string" && fields.detail !== "" ? fields.detail : undefined;
951
1052
  const level = fields.severity === "error" ? "ERROR" : fields.severity === "warning" ? "WARN" : "INFO";
952
- 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
+ };
953
1062
  }
954
1063
  return { type: "other" };
955
1064
  }
@@ -1147,6 +1256,39 @@ const TOFU_SNIPPET_LINE = /^(?:\d+:|[\u251c\u2502\u2514]|\(and \d+ more\))/;
1147
1256
  /** `with var.x,` / `on main.tf line 4, in …:` lines; only dropped inside the leading location block. */
1148
1257
  const TOFU_WITH_LINE = /^with [^ ]+,$/;
1149
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
+ }
1150
1292
  /** Cap a diagnostic list to `max` entries, adding an "… and N more" line. */
1151
1293
  export function capTofuDiagnostics(diagnostics, max = TOFU_DIAGNOSTIC_MAX_ENTRIES) {
1152
1294
  if (diagnostics.length <= max)
@@ -1157,26 +1299,51 @@ export function capTofuDiagnostics(diagnostics, max = TOFU_DIAGNOSTIC_MAX_ENTRIE
1157
1299
  * Error diagnostics from a failed OpenTofu run: `diagnostic` events with
1158
1300
  * severity error from `-json` stdout, plus human `Error:` blocks from stderr.
1159
1301
  * Deduplicated, in order. Used to explain why `ei plan` failed instead of
1160
- * 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 …`.
1161
1305
  */
1162
1306
  export function tofuErrorDiagnostics(stdout, stderr) {
1163
1307
  const out = [];
1164
- const seen = new Set();
1165
- const add = (message) => {
1166
- let trimmed = message.replace(/\s+/g, " ").trim();
1167
- if (trimmed.length > TOFU_DIAGNOSTIC_MAX_CHARS)
1168
- trimmed = `${trimmed.slice(0, TOFU_DIAGNOSTIC_MAX_CHARS)}… (truncated)`;
1169
- 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))
1170
1326
  return;
1171
- seen.add(trimmed);
1172
- 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);
1173
1340
  };
1174
1341
  for (const line of (stdout ?? "").split("\n")) {
1175
1342
  if (line.trim() === "")
1176
1343
  continue;
1177
1344
  const event = parseTofuJsonEvent(line);
1178
1345
  if (event.type === "diagnostic" && event.level === "ERROR")
1179
- add(event.message);
1346
+ add(event.summary, event.detail, event.location);
1180
1347
  }
1181
1348
  const lines = (stderr ?? "").split("\n").map((l) => l.replace(ANSI_SEQUENCE, "").replace(/\r$/, ""));
1182
1349
  for (let i = 0; i < lines.length; i++) {
@@ -1187,7 +1354,8 @@ export function tofuErrorDiagnostics(stdout, stderr) {
1187
1354
  // text output is: Error line, blank, location + source snippet (+ optional
1188
1355
  // ├──/│ expression values), blank, explanation. Drop the location paragraph
1189
1356
  // and any snippet/value lines so only the explanation is kept; snippets can
1190
- // 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).
1191
1359
  const paragraphs = [[]];
1192
1360
  for (let j = i + 1; j < lines.length; j++) {
1193
1361
  const raw = lines[j];
@@ -1207,13 +1375,14 @@ export function tofuErrorDiagnostics(stdout, stderr) {
1207
1375
  // no line filter can recognise. Line filters remain a second layer for
1208
1376
  // snippet/value lines elsewhere.
1209
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;
1210
1379
  const detail = nonEmpty
1211
1380
  .filter((p, idx) => !(idx === 0 && isLocationBlock(p)))
1212
1381
  .map((p) => p.filter((l) => !TOFU_SNIPPET_LINE.test(l)))
1213
1382
  .filter((p) => p.length > 0)
1214
1383
  .map((p) => p.join(" "))
1215
1384
  .join(" ");
1216
- add(detail !== "" ? `${match[1]}: ${detail}` : match[1]);
1385
+ add(match[1], detail !== "" ? detail : undefined, location);
1217
1386
  }
1218
1387
  return out;
1219
1388
  }
@@ -0,0 +1,16 @@
1
+ import { JsonStreamReader } from "./json-stream-reader.js";
2
+ /**
3
+ * The parts of a saved plan's `tofu show -json` that EDK reads (edk#1861). The
4
+ * full document embeds the prior state, the planned values and the
5
+ * configuration of every resource. Only `resource_changes` and `prior_state`
6
+ * are kept, and each resource change and each prior-state resource is parsed
7
+ * on its own.
8
+ */
9
+ export interface SavedPlan {
10
+ readonly resource_changes?: unknown;
11
+ readonly prior_state?: unknown;
12
+ }
13
+ /** Feed `tofu show -json` stdout chunk by chunk with {@link write}, then call {@link end}. */
14
+ export declare class SavedPlanReader extends JsonStreamReader<SavedPlan> {
15
+ constructor();
16
+ }
@@ -0,0 +1,19 @@
1
+ import { JsonStreamReader } from "./json-stream-reader.js";
2
+ const SAVED_PLAN_OPTIONS = {
3
+ subject: "the saved plan's JSON",
4
+ keptRootKeys: new Set(["resource_changes", "prior_state"]),
5
+ walkedPaths: new Set([
6
+ "",
7
+ "resource_changes",
8
+ "prior_state",
9
+ "prior_state.values",
10
+ "prior_state.values.root_module",
11
+ "prior_state.values.root_module.resources",
12
+ ]),
13
+ };
14
+ /** Feed `tofu show -json` stdout chunk by chunk with {@link write}, then call {@link end}. */
15
+ export class SavedPlanReader extends JsonStreamReader {
16
+ constructor() {
17
+ super(SAVED_PLAN_OPTIONS);
18
+ }
19
+ }
@@ -27,7 +27,7 @@ export interface StateSnapshotOptions {
27
27
  readonly runtime?: StateSnapshotRuntime;
28
28
  }
29
29
  export interface StateSnapshotRuntime {
30
- pull(tfDir: string): Promise<string>;
30
+ pull(tfDir: string): Promise<TerraformStateSnapshot>;
31
31
  }
32
32
  export declare class StateSnapshotError extends Error {
33
33
  constructor(message: string);
@@ -1,6 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { assertNoUnmigratedLocalState, requireWorkspaceBackend, } from "../workspace/backend.js";
4
+ import { JsonStreamReader } from "./json-stream-reader.js";
4
5
  import { EiRunError, runEiCapture } from "./run.js";
5
6
  export class StateSnapshotError extends Error {
6
7
  constructor(message) {
@@ -8,8 +9,20 @@ export class StateSnapshotError extends Error {
8
9
  this.name = "StateSnapshotError";
9
10
  }
10
11
  }
12
+ /**
13
+ * `ei state pull` read as it streams, each resource parsed on its own, so a
14
+ * state of any size fits (edk#2248).
15
+ */
16
+ const STATE_READER_OPTIONS = {
17
+ subject: "the pulled state's JSON",
18
+ walkedPaths: new Set(["", "resources"]),
19
+ };
11
20
  const DEFAULT_RUNTIME = {
12
- pull: (tfDir) => runEiCapture(["state", "pull"], { cwd: tfDir, suppressStderr: true }),
21
+ pull: async (tfDir) => {
22
+ const reader = new JsonStreamReader(STATE_READER_OPTIONS);
23
+ await runEiCapture(["state", "pull"], { cwd: tfDir, suppressStderr: true, onStdout: (chunk) => reader.write(chunk) });
24
+ return reader.end();
25
+ },
13
26
  };
14
27
  export function isNoStateError(error) {
15
28
  if (!(error instanceof EiRunError))
@@ -75,9 +88,9 @@ export async function readStateSnapshot(options) {
75
88
  throw new StateSnapshotError(error.message);
76
89
  }
77
90
  }
78
- let raw;
91
+ let pulled;
79
92
  try {
80
- raw = await (options.runtime ?? DEFAULT_RUNTIME).pull(options.tfDir);
93
+ pulled = await (options.runtime ?? DEFAULT_RUNTIME).pull(options.tfDir);
81
94
  }
82
95
  catch (error) {
83
96
  if (isNoStateError(error))
@@ -87,5 +100,5 @@ export async function readStateSnapshot(options) {
87
100
  : error.message;
88
101
  throw new StateSnapshotError(`could not pull state from backend "${backend.type}" in ${options.tfDir}: ${detail}`);
89
102
  }
90
- return parseStateSnapshot(raw, `state pulled from backend "${backend.type}"`);
103
+ return pulled;
91
104
  }
@@ -43,7 +43,9 @@ export declare function writeUserOutput(text: string, destination?: NodeJS.Writa
43
43
  */
44
44
  export declare function writeUserPayload(text: string, destination?: NodeJS.WritableStream): void;
45
45
  /** Write a final user-facing operation status without contaminating pipes. */
46
- export declare function writeUserStatus(message: string, color: "green" | "red" | "yellow"): void;
46
+ export declare function writeUserStatus(message: string, color: "green" | "red" | "yellow", destination?: NodeJS.WriteStream): void;
47
+ /** Where a command whose piped stdout is one JSON summary (pull, clone) writes status text. */
48
+ export declare function summaryCommandStatusStream(): NodeJS.WriteStream;
47
49
  export interface LiveProgressOptions {
48
50
  readonly label: string;
49
51
  /** Omit when the number of steps is not knowable in advance. */
@@ -138,13 +138,17 @@ export function writeUserPayload(text, destination = process.stdout) {
138
138
  destination.write(text);
139
139
  }
140
140
  /** Write a final user-facing operation status without contaminating pipes. */
141
- export function writeUserStatus(message, color) {
141
+ export function writeUserStatus(message, color, destination = process.stdout) {
142
142
  if (machineReadableLogs)
143
143
  return;
144
- const rendered = process.stdout.isTTY === true && process.env["NO_COLOR"] === undefined
144
+ const rendered = destination.isTTY === true && process.env["NO_COLOR"] === undefined
145
145
  ? renderTextEffects(message, [{ start: 0, end: message.length, color, bold: true }])
146
146
  : message;
147
- writeUserOutput(`${rendered}\n`);
147
+ writeUserOutput(`${rendered}\n`, destination);
148
+ }
149
+ /** Where a command whose piped stdout is one JSON summary (pull, clone) writes status text. */
150
+ export function summaryCommandStatusStream() {
151
+ return process.stdout.isTTY === true ? process.stdout : progressStream();
148
152
  }
149
153
  const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
150
154
  let activeProgress;
@@ -11,6 +11,13 @@ import type { TerraformStateResource } from "../ei/state.js";
11
11
  import { type TfDocument } from "../tf/model.js";
12
12
  /** The platform id an import id ends with (`<parent>/<id>` and `<a>:<id>` forms included). */
13
13
  export declare function canonicalImportId(importId: string): string;
14
+ /** The key {@link authoredAddressesById} binds a resource type + platform id under. */
15
+ export declare function typedIdentity(type: string, id: string): string;
16
+ /** Inverse of {@link typedIdentity}. */
17
+ export declare function parseTypedIdentity(identity: string): {
18
+ readonly type: string;
19
+ readonly id: string;
20
+ };
14
21
  /**
15
22
  * Index managed state by resource type and canonical platform identity.
16
23
  *
@@ -58,10 +65,17 @@ export declare function authoredAddressesFromSource(doc: TfDocument, importIds:
58
65
  * reference as `.<key>`; those references break after the pull (#1579).
59
66
  */
60
67
  export declare function staleAuthoredFieldReferences(unmatched: readonly AuthoredSourceField[], otherSources: readonly string[]): readonly AuthoredSourceField[];
68
+ /**
69
+ * Several export addresses whose authored targets share one key slot: one
70
+ * identity bound at two export addresses, or two fields authored at one label.
71
+ * `from[i]` is authored at `authoredTargets[i]`.
72
+ */
61
73
  export interface AuthoredAddressAmbiguity {
62
- readonly authoredTarget: string;
74
+ readonly authoredTargets: readonly string[];
63
75
  readonly from: readonly string[];
64
76
  }
77
+ /** The pull warning for an {@link AuthoredAddressAmbiguity}. */
78
+ export declare function authoredAddressAmbiguityWarning(ambiguity: AuthoredAddressAmbiguity): string;
65
79
  export interface AuthoredAddressConflict {
66
80
  readonly from: string;
67
81
  readonly authoredTarget: string;