@elementumai/edk 0.10.1 → 0.10.3

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 (125) hide show
  1. package/README.md +7 -7
  2. package/dist-sdk/src/catalog/org.d.ts +7 -5
  3. package/dist-sdk/src/catalog/org.js +14 -9
  4. package/dist-sdk/src/catalog/token.js +4 -0
  5. package/dist-sdk/src/core/types/app.d.ts +22 -0
  6. package/dist-sdk/src/engine/build/context.d.ts +8 -0
  7. package/dist-sdk/src/engine/build/source-context.d.ts +3 -4
  8. package/dist-sdk/src/engine/coverage-gaps.d.ts +2 -0
  9. package/dist-sdk/src/engine/coverage-gaps.js +3 -0
  10. package/dist-sdk/src/engine/ei/state.d.ts +48 -0
  11. package/dist-sdk/src/engine/ei/state.js +91 -0
  12. package/dist-sdk/src/engine/pull/authored-address.d.ts +100 -0
  13. package/dist-sdk/src/engine/pull/authored-address.js +360 -0
  14. package/dist-sdk/src/engine/pull/context.d.ts +59 -0
  15. package/dist-sdk/src/engine/tf/expr.d.ts +7 -0
  16. package/dist-sdk/src/engine/tf/expr.js +62 -18
  17. package/dist-sdk/src/engine/tf/index.d.ts +1 -1
  18. package/dist-sdk/src/engine/tf/index.js +1 -1
  19. package/dist-sdk/src/engine/tf/labels.d.ts +10 -2
  20. package/dist-sdk/src/engine/tf/labels.js +15 -2
  21. package/dist-sdk/src/engine/tf/parse.js +19 -6
  22. package/dist-sdk/src/engine/workspace/backend.d.ts +34 -0
  23. package/dist-sdk/src/engine/workspace/backend.js +104 -0
  24. package/dist-sdk/src/engine/workspace/generated-file.d.ts +3 -0
  25. package/dist-sdk/src/engine/workspace/generated-file.js +6 -0
  26. package/dist-sdk/src/engine/workspace/loader.js +2 -2
  27. package/dist-sdk/src/entities/agent-tool/to-tf.js +1 -1
  28. package/dist-sdk/src/entities/app/build.d.ts +36 -4
  29. package/dist-sdk/src/entities/app/build.js +67 -4
  30. package/dist-sdk/src/entities/app/deserializer/normalize.d.ts +12 -0
  31. package/dist-sdk/src/entities/app/from-tf.js +13 -9
  32. package/dist-sdk/src/entities/app/module.js +3 -1
  33. package/dist-sdk/src/entities/app/stage-keys.d.ts +82 -0
  34. package/dist-sdk/src/entities/app/stage-keys.js +160 -0
  35. package/dist-sdk/src/entities/app/to-tf.js +21 -21
  36. package/dist-sdk/src/entities/approval-chain/from-tf.d.ts +9 -1
  37. package/dist-sdk/src/entities/approval-chain/from-tf.js +31 -3
  38. package/dist-sdk/src/entities/approval-chain/module.js +12 -4
  39. package/dist-sdk/src/entities/approval-chain/to-tf.d.ts +1 -0
  40. package/dist-sdk/src/entities/approval-chain/to-tf.js +6 -1
  41. package/dist-sdk/src/entities/automation/build.d.ts +2 -0
  42. package/dist-sdk/src/entities/automation/build.js +25 -17
  43. package/dist-sdk/src/entities/automation/deserializer/ast.d.ts +3 -0
  44. package/dist-sdk/src/entities/automation/deserializer/print-automation.d.ts +5 -3
  45. package/dist-sdk/src/entities/automation/deserializer/print-automation.js +127 -31
  46. package/dist-sdk/src/entities/automation/from-tf.d.ts +28 -6
  47. package/dist-sdk/src/entities/automation/from-tf.js +172 -27
  48. package/dist-sdk/src/entities/automation/module.js +123 -37
  49. package/dist-sdk/src/entities/automation/output-key-wire-name.d.ts +21 -0
  50. package/dist-sdk/src/entities/automation/output-key-wire-name.js +38 -0
  51. package/dist-sdk/src/entities/automation/to-tf.d.ts +3 -1
  52. package/dist-sdk/src/entities/automation/to-tf.js +191 -33
  53. package/dist-sdk/src/entities/automation/triggers.d.ts +2 -0
  54. package/dist-sdk/src/entities/automation/triggers.js +1 -0
  55. package/dist-sdk/src/entities/chart/from-tf.d.ts +6 -0
  56. package/dist-sdk/src/entities/chart/from-tf.js +9 -1
  57. package/dist-sdk/src/entities/dashboard/from-tf.js +51 -4
  58. package/dist-sdk/src/entities/dynamic-layout/from-tf.d.ts +3 -0
  59. package/dist-sdk/src/entities/dynamic-layout/from-tf.js +48 -4
  60. package/dist-sdk/src/entities/dynamic-layout/to-tf.d.ts +2 -0
  61. package/dist-sdk/src/entities/dynamic-layout/to-tf.js +7 -2
  62. package/dist-sdk/src/entities/element/build.js +1 -1
  63. package/dist-sdk/src/entities/element/from-tf.d.ts +12 -6
  64. package/dist-sdk/src/entities/element/from-tf.js +23 -7
  65. package/dist-sdk/src/entities/element/module.js +5 -3
  66. package/dist-sdk/src/entities/element/to-tf.d.ts +3 -2
  67. package/dist-sdk/src/entities/element/to-tf.js +36 -25
  68. package/dist-sdk/src/entities/field/allow-list.d.ts +18 -0
  69. package/dist-sdk/src/entities/field/allow-list.js +42 -0
  70. package/dist-sdk/src/entities/field/build.d.ts +38 -3
  71. package/dist-sdk/src/entities/field/build.js +7 -2
  72. package/dist-sdk/src/entities/field/from-tf.js +252 -76
  73. package/dist-sdk/src/entities/field/module.d.ts +6 -0
  74. package/dist-sdk/src/entities/field/module.js +24 -2
  75. package/dist-sdk/src/entities/field/options.d.ts +2 -0
  76. package/dist-sdk/src/entities/field/order.d.ts +25 -0
  77. package/dist-sdk/src/entities/field/order.js +74 -0
  78. package/dist-sdk/src/entities/field/to-tf.d.ts +6 -0
  79. package/dist-sdk/src/entities/field/to-tf.js +87 -0
  80. package/dist-sdk/src/entities/field/types.d.ts +5 -0
  81. package/dist-sdk/src/entities/field/types.js +8 -0
  82. package/dist-sdk/src/entities/relationship/build.d.ts +3 -3
  83. package/dist-sdk/src/entities/relationship/from-tf.js +4 -2
  84. package/dist-sdk/src/entities/relationship/to-tf.js +3 -1
  85. package/dist-sdk/src/entities/service-account/workspace-owner.d.ts +8 -3
  86. package/dist-sdk/src/entities/service-account/workspace-owner.js +12 -4
  87. package/dist-sdk/src/entities/shared/aspect-target-from-tf.d.ts +5 -0
  88. package/dist-sdk/src/entities/shared/aspect-target-from-tf.js +13 -0
  89. package/dist-sdk/src/entities/shared/filters/ast.d.ts +7 -0
  90. package/dist-sdk/src/entities/skill/deserializer/print-skill-v2.js +1 -1
  91. package/dist-sdk/src/entities/skill/to-tf.js +19 -14
  92. package/dist-sdk/src/entities/skill-tool/from-tf.d.ts +2 -0
  93. package/dist-sdk/src/entities/skill-tool/from-tf.js +3 -0
  94. package/dist-sdk/src/entities/skill-tool/to-tf.d.ts +6 -1
  95. package/dist-sdk/src/entities/skill-tool/to-tf.js +6 -1
  96. package/dist-sdk/src/entities/task/build.js +1 -1
  97. package/dist-sdk/src/entities/task/module.js +2 -1
  98. package/dist-sdk/src/entities/task/to-tf.js +4 -0
  99. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.d.ts +11 -0
  100. package/dist-sdk/src/entities/view/agent-view-layout-to-tf.js +13 -38
  101. package/dist-sdk/src/entities/view/custom-view-validate.d.ts +29 -0
  102. package/dist-sdk/src/entities/view/custom-view-validate.js +292 -0
  103. package/dist-sdk/src/entities/view/from-tf.d.ts +2 -0
  104. package/dist-sdk/src/entities/view/from-tf.js +40 -6
  105. package/dist-sdk/src/entities/view/module.js +4 -1
  106. package/dist-sdk/src/entities/view/to-tf.d.ts +6 -0
  107. package/dist-sdk/src/entities/view/to-tf.js +25 -9
  108. package/dist-sdk/src/entities/view/types.d.ts +6 -0
  109. package/dist-sdk/src/entities/view/types.js +6 -0
  110. package/dist-sdk/src/entities/visual-flow/from-tf.d.ts +2 -1
  111. package/dist-sdk/src/entities/visual-flow/from-tf.js +11 -2
  112. package/dist-sdk/src/entities/visual-flow/module.js +15 -5
  113. package/dist-sdk/src/entities/visual-flow/to-tf.d.ts +2 -0
  114. package/dist-sdk/src/entities/visual-flow/to-tf.js +1 -1
  115. package/dist-sdk/src/entities/widget/build.d.ts +8 -1
  116. package/dist-sdk/src/entities/widget/from-tf.js +12 -6
  117. package/dist-sdk/src/entities/widget/to-tf.d.ts +1 -0
  118. package/dist-sdk/src/entities/widget/to-tf.js +16 -0
  119. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.d.ts +8 -2
  120. package/dist-sdk/src/generated/ragnarok/ragnarok-spec.js +2 -2
  121. package/dist-sdk/src/graph/index.d.ts +9 -2
  122. package/dist-sdk/src/graph/index.js +4 -0
  123. package/dist-sdk/src/graph/modules.js +2 -1
  124. package/dist-sdk/src/graph/types.d.ts +72 -3
  125. package/package.json +2 -17
package/README.md CHANGED
@@ -814,16 +814,16 @@ local CLI path is:
814
814
  ```sh
815
815
  npm run local:setup
816
816
  npm run elementum -- --help
817
- npm run test:cli
818
817
  ```
819
818
 
820
819
  See [binary validation](docs/edk-binary.md) for release and
821
820
  compatibility-train checks.
822
821
 
823
- ## Contributor integration harness
822
+ ## Contributor integration tests
824
823
 
825
- The Preston High harness creates, mutates, renames, and deletes live resources.
826
- Use only a dedicated test organization and profile. The complete setup,
827
- required org identities, golden-workspace flow, command flags, and failure
828
- semantics live in the
829
- [Golden integration test](CONTRIBUTING.md#golden-integration-test).
824
+ The Preston High integration tests run only against a developer's local stack.
825
+ Each run lays the golden source down under run-unique names, checks that
826
+ pull → plan → apply → pull changes nothing, and deletes only what it created.
827
+ Setup, commands, and failure handling are in
828
+ [Preston High local integration tests](CONTRIBUTING.md#preston-high-local-integration-tests)
829
+ and the `preston-high-run` coding-agent skill.
@@ -8,7 +8,8 @@ export declare function writeOrgCatalogFromExtract(root: string, extract: OrgExt
8
8
  * untouched (it belongs to `pull org`). Called after a pull writes new
9
9
  * authoring (apps/agents) so `@catalog` resolves the fresh entries. While
10
10
  * git may still track the barrel, entries it lists are kept even when their
11
- * folder is not checked out (see {@link refreshCatalogBarrel}).
11
+ * folder is not checked out, except a case-only twin of a catalog on disk
12
+ * (see {@link refreshCatalogBarrel}).
12
13
  */
13
14
  export declare function writeCatalogBarrel(root: string): Promise<string>;
14
15
  export declare const ORG_BARREL_IGNORE_COMMENT = "# org catalog barrel \u2014 local derived state, written by elementum build/plan/apply and elementum generate";
@@ -39,10 +40,11 @@ export interface CatalogBarrelRefresh extends CatalogBarrelDrift {
39
40
  /**
40
41
  * Bring generated/catalog.ts in line with the catalogs on disk when it is
41
42
  * absent or lists a different set of entries, and make sure the org
42
- * .gitignore covers it. While git may still track the barrel, a missing
43
- * folder may just not be checked out, so entries are only added, never
44
- * dropped — otherwise a partial tree would commit the very truncation this
45
- * guards. Every barrel writer shares that rule.
43
+ * .gitignore covers it. While git tracks the barrel, or cannot say whether
44
+ * it does, a missing folder may just not be checked out, so those entries
45
+ * stay. A listed entry whose folder differs from an on-disk catalog only by
46
+ * case is dropped, because that folder loads and does not export the listed
47
+ * key. Every barrel writer shares that rule.
46
48
  */
47
49
  export declare function refreshCatalogBarrel(root: string): Promise<CatalogBarrelRefresh>;
48
50
  /** Element keys, reserving all app/element catalogs about to be written. */
@@ -42,7 +42,8 @@ export async function writeOrgCatalogFromExtract(root, extract) {
42
42
  * untouched (it belongs to `pull org`). Called after a pull writes new
43
43
  * authoring (apps/agents) so `@catalog` resolves the fresh entries. While
44
44
  * git may still track the barrel, entries it lists are kept even when their
45
- * folder is not checked out (see {@link refreshCatalogBarrel}).
45
+ * folder is not checked out, except a case-only twin of a catalog on disk
46
+ * (see {@link refreshCatalogBarrel}).
46
47
  */
47
48
  export async function writeCatalogBarrel(root) {
48
49
  await writeBarrel(root, await readBarrelState(root));
@@ -103,12 +104,15 @@ async function readBarrelState(root) {
103
104
  ...handles.tableHandles.map((h) => `tables/${h}`),
104
105
  ]);
105
106
  const listed = new Set(barrel === undefined ? [] : [...barrel.matchAll(BARREL_ENTRY_PATH)].map((m) => `${m[1]}/${m[2]}`));
107
+ const expectedFolded = new Set([...expected].map((e) => e.toLowerCase()));
108
+ const notExpected = [...listed].filter((e) => !expected.has(e));
106
109
  return {
107
110
  present: worktree !== undefined,
111
+ shadowed: notExpected.filter((e) => expectedFolded.has(e.toLowerCase())).sort(),
108
112
  git,
109
113
  handles,
110
114
  missing: [...expected].filter((e) => !listed.has(e)).sort(),
111
- stale: [...listed].filter((e) => !expected.has(e)).sort(),
115
+ stale: notExpected.filter((e) => !expectedFolded.has(e.toLowerCase())).sort(),
112
116
  };
113
117
  }
114
118
  function keptReason(state) {
@@ -145,23 +149,24 @@ async function writeBarrel(root, state) {
145
149
  * path so older barrel renderings compare the same.
146
150
  */
147
151
  export async function findCatalogBarrelDrift(root) {
148
- const { missing, stale } = await readBarrelState(root);
149
- return { missing, stale };
152
+ const { missing, stale, shadowed } = await readBarrelState(root);
153
+ return { missing, stale: [...stale, ...shadowed].sort() };
150
154
  }
151
155
  /**
152
156
  * Bring generated/catalog.ts in line with the catalogs on disk when it is
153
157
  * absent or lists a different set of entries, and make sure the org
154
- * .gitignore covers it. While git may still track the barrel, a missing
155
- * folder may just not be checked out, so entries are only added, never
156
- * dropped — otherwise a partial tree would commit the very truncation this
157
- * guards. Every barrel writer shares that rule.
158
+ * .gitignore covers it. While git tracks the barrel, or cannot say whether
159
+ * it does, a missing folder may just not be checked out, so those entries
160
+ * stay. A listed entry whose folder differs from an on-disk catalog only by
161
+ * case is dropped, because that folder loads and does not export the listed
162
+ * key. Every barrel writer shares that rule.
158
163
  */
159
164
  export async function refreshCatalogBarrel(root) {
160
165
  const state = await readBarrelState(root);
161
166
  const { missing, stale } = state;
162
167
  const reason = keptReason(state);
163
168
  const kept = { keptStale: reason !== undefined, ...(reason !== undefined && { keptReason: reason }) };
164
- if (state.present && missing.length === 0 && (stale.length === 0 || reason !== undefined)) {
169
+ if (state.present && missing.length === 0 && state.shadowed.length === 0 && (stale.length === 0 || reason !== undefined)) {
165
170
  await ensureBarrelIgnored(root);
166
171
  const entries = state.handles.appHandles.length + state.handles.elementHandles.length +
167
172
  state.handles.tableHandles.length + (reason === undefined ? 0 : stale.length);
@@ -64,6 +64,10 @@ export function slimToken(token) {
64
64
  // task build.
65
65
  if (token.__kind === "documentModel" && typeof token.readerType === "string")
66
66
  out.readerType = token.readerType;
67
+ // A platform-managed automation is looked up by display name when a widget
68
+ // runs it; `name` can be the refName.
69
+ if (token.__kind === "automation" && typeof token.displayName === "string")
70
+ out.displayName = token.displayName;
67
71
  // Procedure lookup must carry the exact ordered Snowflake signature so the
68
72
  // provider can distinguish a procedure from a same-name UDF and select one
69
73
  // exact overload. This is identity metadata, not a barrel bag.
@@ -309,10 +309,32 @@ export interface MultiPicklistAppField<Scope extends FieldScope = "unscoped"> ex
309
309
  /** USER fields (user references). `USER` and `USER_ID` are accepted aliases. */
310
310
  export interface UserAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
311
311
  readonly type: "USER" | "USER_ID";
312
+ /** Pick-list restriction (edk#1776): members of these groups. */
313
+ readonly allowedGroups?: readonly {
314
+ readonly __kind: "group";
315
+ readonly refName: string;
316
+ readonly name?: string;
317
+ }[];
318
+ /** Pick-list restriction (edk#1776): these users, by email. */
319
+ readonly allowedUsers?: readonly {
320
+ readonly __kind: "user";
321
+ readonly email: string;
322
+ }[];
323
+ /**
324
+ * Pick-list restriction (edk#1776): members of the group selected in this
325
+ * same-owner group field. `null` removes a live link.
326
+ */
327
+ readonly parentGroupField?: FieldRef<string, string, "GROUP" | "GROUP_ID"> | null;
312
328
  }
313
329
  /** GROUP fields (group references). `GROUP` and `GROUP_ID` are accepted aliases. */
314
330
  export interface GroupAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
315
331
  readonly type: "GROUP" | "GROUP_ID";
332
+ /** Pick-list restriction (edk#1776): only these groups. */
333
+ readonly allowedGroups?: readonly {
334
+ readonly __kind: "group";
335
+ readonly refName: string;
336
+ readonly name?: string;
337
+ }[];
316
338
  }
317
339
  /** ATTACHMENT fields. `mediaTypes` restricts uploads to the listed MIME types. */
318
340
  export interface AttachmentAppField<Scope extends FieldScope = "unscoped"> extends AspectFieldBase<Scope> {
@@ -92,6 +92,8 @@ export interface WorkspaceAspect {
92
92
  readonly streamRootEntity?: DeployableEntity;
93
93
  /** Source refNames of ACTIVE authored automations owned by this root. */
94
94
  readonly activeAutomationRefNames?: ReadonlySet<string>;
95
+ /** Source refNames of every authored automation owned by this root. */
96
+ readonly automationRefNames?: ReadonlySet<string>;
95
97
  /** Sole on-demand record parameter targeting this same owner, keyed by automation refName, for CURRENT_RECORD widget binding. */
96
98
  readonly onDemandRecordParamByAutomationRefName?: ReadonlyMap<string, string>;
97
99
  /** Terraform labels of datamines managed by a table in this workspace. */
@@ -131,6 +133,12 @@ export interface ToTfContext {
131
133
  * supply it.
132
134
  */
133
135
  readonly workspaceAspects?: ReadonlyMap<string, WorkspaceAspect>;
136
+ /**
137
+ * Apps authored in this workspace but left out of a scoped build
138
+ * (`includeRoots`), by refName. They are not siblings here, so a reference
139
+ * to one resolves through a data lookup.
140
+ */
141
+ readonly outOfScopeApps?: ReadonlyMap<string, ForeignRootIdentity>;
134
142
  /** App-local automations whose workflow_publish block is emitted in this build. */
135
143
  readonly activeAutomationRefNames?: ReadonlySet<string>;
136
144
  }
@@ -3,7 +3,7 @@
3
3
  * its own on-disk text" context for `elementum build`'s own-file-child loader.
4
4
  *
5
5
  * Entity-agnostic on purpose: `engine/` may not import from `entities/`
6
- * (`__tests__/engine/no-entity-types-in-engine.test.ts`), so this exists
6
+ * (the engine/entities boundary rule), so this exists
7
7
  * purely as plumbing — it knows nothing about automations or any other
8
8
  * entity kind. An entity module (e.g. `entities/automation/script-code.ts`)
9
9
  * that needs the file's real text — a `toString()` on a loaded function
@@ -18,9 +18,8 @@
18
18
  * (confirmed empirically — that version silently lost context there).
19
19
  * - A plain module-scoped variable has a SEPARATE failure mode: the same
20
20
  * module can be instantiated twice in one process whenever something
21
- * other than plain Node also loads it — Vitest's module runner is the
22
- * live example, since the workspace loader is externalized and the test
23
- * file's own imports are not. Writes through one copy are invisible to
21
+ * other than plain Node also loads it (e.g. a bundler's module runner
22
+ * that externalizes the workspace loader but not its caller). Writes through one copy are invisible to
24
23
  * reads through the other. `globalThis` is the one thing guaranteed
25
24
  * shared across however many separate module instances end up loaded in
26
25
  * the same process.
@@ -11,6 +11,8 @@
11
11
  * the config they mention is built and applied as authored:
12
12
  * - skill input-coverage lint (`skill "x" input coverage gap [input-schema-missing]: …`)
13
13
  * - the unbumped-automation revision reminder
14
+ * - the custom-view non-PanesBlock root hint (check.mjs `warn`; the layout is
15
+ * emitted exactly as authored, edk#1771)
14
16
  *
15
17
  * The ~600 emit sites push free-form `"<where>: <what>; dropped"` strings.
16
18
  * Rather than rewrite every site, they are classified here, where they leave
@@ -11,6 +11,8 @@
11
11
  * the config they mention is built and applied as authored:
12
12
  * - skill input-coverage lint (`skill "x" input coverage gap [input-schema-missing]: …`)
13
13
  * - the unbumped-automation revision reminder
14
+ * - the custom-view non-PanesBlock root hint (check.mjs `warn`; the layout is
15
+ * emitted exactly as authored, edk#1771)
14
16
  *
15
17
  * The ~600 emit sites push free-form `"<where>: <what>; dropped"` strings.
16
18
  * Rather than rewrite every site, they are classified here, where they leave
@@ -22,6 +24,7 @@ const ADVISORY_DIAGNOSTICS = [
22
24
  INPUT_COVERAGE,
23
25
  /^automation \S+: compiled steps changed since the last apply but its revision is still /,
24
26
  /^applied-automation-revisions\.json .*; until then no automation is checked for an edit without a revision bump$/,
27
+ /\.root: "[^"]*" is (?:untyped|a [A-Za-z0-9_]+); the root is usually a PanesBlock \(needed for record lists to open the details pane\)$/,
25
28
  ];
26
29
  export function isAdvisoryDiagnostic(message) {
27
30
  return ADVISORY_DIAGNOSTICS.some((pattern) => pattern.test(message));
@@ -0,0 +1,48 @@
1
+ import { type WorkspaceBackend } from "../workspace/backend.js";
2
+ export interface TerraformStateInstance {
3
+ readonly index_key?: string | number;
4
+ readonly attributes?: Record<string, unknown>;
5
+ }
6
+ export interface TerraformStateResource {
7
+ readonly mode?: string;
8
+ readonly type?: string;
9
+ readonly name?: string;
10
+ readonly module?: string;
11
+ readonly instances?: readonly TerraformStateInstance[];
12
+ }
13
+ export interface TerraformStateSnapshot {
14
+ readonly version?: number;
15
+ readonly terraform_version?: string;
16
+ readonly serial?: number;
17
+ readonly lineage?: string;
18
+ readonly resources?: readonly TerraformStateResource[];
19
+ readonly [key: string]: unknown;
20
+ }
21
+ export interface StateSnapshotOptions {
22
+ readonly orgRoot: string;
23
+ readonly tfDir: string;
24
+ readonly backend?: WorkspaceBackend;
25
+ /** Migration probes need to inspect the destination while local state still exists. */
26
+ readonly allowUnmigratedLocalState?: boolean;
27
+ readonly runtime?: StateSnapshotRuntime;
28
+ }
29
+ export interface StateSnapshotRuntime {
30
+ pull(tfDir: string): Promise<string>;
31
+ }
32
+ export declare class StateSnapshotError extends Error {
33
+ constructor(message: string);
34
+ }
35
+ export declare function isNoStateError(error: unknown): boolean;
36
+ /**
37
+ * Backends such as `pg` answer `state pull` on a never-written workspace with
38
+ * a successful, blank snapshot instead of "No state file was found!". Such a
39
+ * snapshot has never recorded anything and must count as absent state.
40
+ */
41
+ export declare function isEmptyStateSnapshot(snapshot: TerraformStateSnapshot): boolean;
42
+ export declare function parseStateSnapshot(raw: string, description: string): TerraformStateSnapshot;
43
+ /**
44
+ * Read the authoritative state without inventing a second state transport:
45
+ * compatibility mode reads its committed file, while declared backends use
46
+ * OpenTofu's own `state pull` through the credential-owning bridge.
47
+ */
48
+ export declare function readStateSnapshot(options: StateSnapshotOptions): Promise<TerraformStateSnapshot | undefined>;
@@ -0,0 +1,91 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { assertNoUnmigratedLocalState, requireWorkspaceBackend, } from "../workspace/backend.js";
4
+ import { EiRunError, runEiCapture } from "./run.js";
5
+ export class StateSnapshotError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "StateSnapshotError";
9
+ }
10
+ }
11
+ const DEFAULT_RUNTIME = {
12
+ pull: (tfDir) => runEiCapture(["state", "pull"], { cwd: tfDir, suppressStderr: true }),
13
+ };
14
+ export function isNoStateError(error) {
15
+ if (!(error instanceof EiRunError))
16
+ return false;
17
+ const text = error.stderr ?? error.message;
18
+ return (/No state file was found!?/i.test(text) ||
19
+ /State management commands require a state file/i.test(text) ||
20
+ /No stored state was found/i.test(text));
21
+ }
22
+ /**
23
+ * Backends such as `pg` answer `state pull` on a never-written workspace with
24
+ * a successful, blank snapshot instead of "No state file was found!". Such a
25
+ * snapshot has never recorded anything and must count as absent state.
26
+ */
27
+ export function isEmptyStateSnapshot(snapshot) {
28
+ const outputs = snapshot["outputs"];
29
+ return ((snapshot.serial === undefined || snapshot.serial === 0) &&
30
+ (snapshot.lineage === undefined || snapshot.lineage.trim() === "") &&
31
+ (snapshot.resources ?? []).length === 0 &&
32
+ (outputs === undefined ||
33
+ outputs === null ||
34
+ (typeof outputs === "object" && Object.keys(outputs).length === 0)));
35
+ }
36
+ export function parseStateSnapshot(raw, description) {
37
+ let parsed;
38
+ try {
39
+ // eslint-disable-next-line no-restricted-syntax -- OpenTofu state is machine-owned JSON, not an EDK entity.
40
+ parsed = JSON.parse(raw);
41
+ }
42
+ catch (error) {
43
+ throw new StateSnapshotError(`${description} is not valid OpenTofu state JSON: ${error.message}`);
44
+ }
45
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
46
+ throw new StateSnapshotError(`${description} must be a JSON object`);
47
+ }
48
+ return parsed;
49
+ }
50
+ /**
51
+ * Read the authoritative state without inventing a second state transport:
52
+ * compatibility mode reads its committed file, while declared backends use
53
+ * OpenTofu's own `state pull` through the credential-owning bridge.
54
+ */
55
+ export async function readStateSnapshot(options) {
56
+ const backend = options.backend ?? (await requireWorkspaceBackend(options.orgRoot, "state access"));
57
+ if (backend.mode === "local") {
58
+ const localStatePath = join(options.orgRoot, "terraform.tfstate");
59
+ try {
60
+ return parseStateSnapshot(await readFile(localStatePath, "utf8"), `local state at ${localStatePath}`);
61
+ }
62
+ catch (error) {
63
+ if (error.code === "ENOENT")
64
+ return undefined;
65
+ if (error instanceof StateSnapshotError)
66
+ throw error;
67
+ throw new StateSnapshotError(`could not read local state at ${localStatePath}: ${error.message}`);
68
+ }
69
+ }
70
+ if (!options.allowUnmigratedLocalState) {
71
+ try {
72
+ assertNoUnmigratedLocalState(backend, options.orgRoot);
73
+ }
74
+ catch (error) {
75
+ throw new StateSnapshotError(error.message);
76
+ }
77
+ }
78
+ let raw;
79
+ try {
80
+ raw = await (options.runtime ?? DEFAULT_RUNTIME).pull(options.tfDir);
81
+ }
82
+ catch (error) {
83
+ if (isNoStateError(error))
84
+ return undefined;
85
+ const detail = error instanceof EiRunError && error.stderr?.trim()
86
+ ? `${error.message}: ${error.stderr.trim()}`
87
+ : error.message;
88
+ throw new StateSnapshotError(`could not pull state from backend "${backend.type}" in ${options.tfDir}: ${detail}`);
89
+ }
90
+ return parseStateSnapshot(raw, `state pulled from backend "${backend.type}"`);
91
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Preserve the Terraform addresses already authored by a workspace when ei's
3
+ * export derives different labels from resource display names.
4
+ *
5
+ * Build derives labels from TypeScript bag keys, while export derives labels
6
+ * from display names. OpenTofu state is the authoritative binding from a
7
+ * platform identity to the address produced by the authored workspace.
8
+ */
9
+ import type { AdoptionAddressAlias } from "../../graph/index.js";
10
+ import type { TerraformStateResource } from "../ei/state.js";
11
+ import { type TfDocument } from "../tf/model.js";
12
+ /** The platform id an import id ends with (`<parent>/<id>` and `<a>:<id>` forms included). */
13
+ export declare function canonicalImportId(importId: string): string;
14
+ /**
15
+ * Index managed state by resource type and canonical platform identity.
16
+ *
17
+ * Type is part of the key because composite resources can expose two provider
18
+ * resource types backed by the same platform object and ID.
19
+ */
20
+ export declare function authoredAddressesById(resources: readonly TerraformStateResource[]): ReadonlyMap<string, string>;
21
+ /**
22
+ * Every managed type + canonical id state holds, including one bound at two
23
+ * addresses (which `authoredAddressesById` drops). An identity in this set is
24
+ * never treated as new to the workspace.
25
+ */
26
+ export declare function managedStateIdentities(resources: readonly TerraformStateResource[]): ReadonlySet<string>;
27
+ /** A field declared in authored TypeScript: `key: <ctor>Field({ ..., name: "Display" })`. */
28
+ export interface AuthoredSourceField {
29
+ readonly key: string;
30
+ /** The field constructor's base name (`number` for `numberField`). */
31
+ readonly ctor: string;
32
+ readonly name: string;
33
+ }
34
+ /**
35
+ * Field bag keys an authored app/element source declares, with the display
36
+ * name and constructor that identify the platform field on a stateless pull
37
+ * (#1579). Only the literal `name:` form is recognized; anything else is
38
+ * simply not matched and keeps its export label.
39
+ */
40
+ export declare function authoredSourceFields(source: string): readonly AuthoredSourceField[];
41
+ /** Maps an authoring constructor base name (`number`) to its provider resource type; supplied by entities. */
42
+ export type FieldResourceTypeForCtor = (ctor: string) => string | undefined;
43
+ export interface SourceKeyAddresses {
44
+ /** typed identity → authored address, for identities state does not bind. */
45
+ readonly byId: ReadonlyMap<string, string>;
46
+ /** Authored keys no export field matched (renamed, retyped or removed live). */
47
+ readonly unmatched: readonly AuthoredSourceField[];
48
+ }
49
+ /**
50
+ * Stateless fallback for {@link authoredAddressesById}: bind each exported
51
+ * field to the address its authored bag key builds, when exactly one authored
52
+ * field shares its resource type and display name. State stays authoritative:
53
+ * identities already in `stateById` are left alone.
54
+ */
55
+ export declare function authoredAddressesFromSource(doc: TfDocument, importIds: ReadonlyMap<string, string>, fields: readonly AuthoredSourceField[], stateById: ReadonlyMap<string, string>, resourceTypeForCtor: FieldResourceTypeForCtor): SourceKeyAddresses;
56
+ /**
57
+ * Unmatched authored fields whose key other hand-written files still
58
+ * reference as `.<key>`; those references break after the pull (#1579).
59
+ */
60
+ export declare function staleAuthoredFieldReferences(unmatched: readonly AuthoredSourceField[], otherSources: readonly string[]): readonly AuthoredSourceField[];
61
+ export interface AuthoredAddressAmbiguity {
62
+ readonly authoredTarget: string;
63
+ readonly from: readonly string[];
64
+ }
65
+ export interface AuthoredAddressConflict {
66
+ readonly from: string;
67
+ readonly authoredTarget: string;
68
+ readonly occupiedById: string;
69
+ }
70
+ /**
71
+ * Resolve export addresses to addresses already bound in authored state.
72
+ *
73
+ * A first-pull resource has no state binding and keeps its export address.
74
+ * Ambiguous many-to-one aliases are omitted rather than merging resources.
75
+ */
76
+ export declare function authoredAddressAliases(importIds: ReadonlyMap<string, string>, authoredById: ReadonlyMap<string, string>, inState?: ReadonlySet<string>): readonly AdoptionAddressAlias[];
77
+ /**
78
+ * Two export addresses claiming one authored target cannot be joined
79
+ * without guessing. Report them the same way occupancy conflicts are.
80
+ */
81
+ export declare function authoredAddressAmbiguities(importIds: ReadonlyMap<string, string>, authoredById: ReadonlyMap<string, string>, inState?: ReadonlySet<string>): readonly AuthoredAddressAmbiguity[];
82
+ /**
83
+ * Collapse authored (export → state) and extract (post-relabel → rebuild)
84
+ * aliases into a single export → final hop. Extract aliases name the
85
+ * already-relabelled address as `from`; adoption still keys import ids by
86
+ * the pre-relabel export address.
87
+ */
88
+ export declare function composeAdoptionAddressAliases(authoredAliases: readonly AdoptionAddressAlias[], extractAliases: readonly AdoptionAddressAlias[]): readonly AdoptionAddressAlias[];
89
+ /**
90
+ * State can be stale enough, or same-named labels can shift far enough, that
91
+ * an identity's authored address stays held by a different identity even
92
+ * after resolution. Such a rename is unsafe; report it while leaving both
93
+ * resources at their export addresses.
94
+ */
95
+ export declare function authoredAddressConflicts(importIds: ReadonlyMap<string, string>, authoredById: ReadonlyMap<string, string>, inState?: ReadonlySet<string>): readonly AuthoredAddressConflict[];
96
+ /**
97
+ * Relabel resource blocks and all managed references before extraction so
98
+ * printers recover the workspace's existing bag keys and own-file names.
99
+ */
100
+ export declare function relabelDocument<T extends TfDocument>(doc: T, aliases: readonly AdoptionAddressAlias[]): T;