@intentius/behold 0.30.1 → 0.31.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 (129) hide show
  1. package/AGENTS.md +475 -16
  2. package/README.md +25 -19
  3. package/demos.json +14 -9
  4. package/dist/cli.js +54900 -26771
  5. package/example-carve/README.md +19 -23
  6. package/example-carve/app/package.json +1 -1
  7. package/example-carve/app/src/carved.ts +3 -3
  8. package/example-carve/carve-report.json +1 -1
  9. package/example-carve/{legacy-tf → tf-root}/terraform.tfstate +1 -1
  10. package/example-choudoufu-estate/README.md +7 -0
  11. package/example-choudoufu-estate/chant.workspace.json +1 -1
  12. package/example-choudoufu-estate/scripts/choudoufu-down.sh +2 -1
  13. package/example-choudoufu-estate/scripts/choudoufu-up.sh +10 -3
  14. package/example-terraform-estate/README.md +32 -5
  15. package/example-terraform-estate/chant.workspace.json +1 -1
  16. package/example-terraform-estate/recorded/adoption/platform.json +72 -0
  17. package/example-terraform-estate/recorded/adoption/prod.json +224 -0
  18. package/example-terralith/README.md +1 -1
  19. package/example-three-cloud/README.md +111 -18
  20. package/example-three-cloud/aws/Pulumi.yaml +15 -0
  21. package/example-three-cloud/aws/index.ts +174 -0
  22. package/example-three-cloud/aws/package-lock.json +2725 -0
  23. package/example-three-cloud/aws/package.json +14 -0
  24. package/example-three-cloud/aws/tsconfig.json +17 -0
  25. package/example-three-cloud/azure/main.tf +48 -0
  26. package/example-three-cloud/azure/site.tf +104 -0
  27. package/example-three-cloud/chant.config.json +9 -0
  28. package/example-three-cloud/chant.workspace.json +30 -4
  29. package/example-three-cloud/dns/chant.config.ts +26 -1
  30. package/example-three-cloud/dns/src/records.component.ts +32 -6
  31. package/example-three-cloud/package-lock.json +48 -27
  32. package/example-three-cloud/package.json +8 -6
  33. package/example-three-cloud/scripts/emulators-up.sh +28 -1
  34. package/example-three-cloud/scripts/front-door.ts +679 -86
  35. package/package.json +13 -6
  36. package/web/adopt-pulumi.js +114 -0
  37. package/web/adopt-pulumi.test.js +28 -0
  38. package/web/adopt.js +203 -0
  39. package/web/adopt.test.js +27 -0
  40. package/web/app.js +614 -19
  41. package/web/carve-steps.js +1 -1
  42. package/web/carve-steps.test.js +2 -2
  43. package/web/change-set-overlay.js +12 -5
  44. package/web/change-set-overlay.test.js +22 -0
  45. package/web/drift-stream.js +241 -0
  46. package/web/drift-stream.test.js +146 -0
  47. package/web/edge-weight.d.ts +1 -1
  48. package/web/edge-weight.js +5 -1
  49. package/web/edge-weight.test.js +19 -0
  50. package/web/embed.js +2 -2
  51. package/web/event-help-modal.js +18 -12
  52. package/web/event-help-modal.test.js +28 -1
  53. package/web/graph-query.js +180 -0
  54. package/web/graph-query.test.js +49 -0
  55. package/web/graph.html +107 -0
  56. package/web/index-diff.js +109 -0
  57. package/web/index-diff.test.js +39 -0
  58. package/web/index.html +55 -0
  59. package/web/kiosk-ask-layout.js +85 -0
  60. package/web/kiosk-ask-layout.test.js +83 -0
  61. package/web/kiosk-ask-tips.js +477 -0
  62. package/web/kiosk-ask-tips.test.js +372 -0
  63. package/web/kiosk-ask.js +774 -0
  64. package/web/kiosk-ask.test.js +593 -0
  65. package/web/kiosk-banner.js +108 -0
  66. package/web/kiosk-banner.test.js +72 -0
  67. package/web/kiosk-center-cards.test.js +110 -0
  68. package/web/kiosk-estate-scene.js +267 -0
  69. package/web/kiosk-estate-scene.test.js +21 -0
  70. package/web/kiosk-event-help.js +4 -1
  71. package/web/kiosk-graph-pane.js +63 -0
  72. package/web/kiosk-graph-pane.test.js +105 -0
  73. package/web/kiosk-light-frame.js +197 -0
  74. package/web/kiosk-light.js +547 -0
  75. package/web/kiosk-light.test.js +297 -0
  76. package/web/kiosk-member-kind.test.js +140 -0
  77. package/web/kiosk-metrics.js +7 -4
  78. package/web/kiosk-modal-sticky.test.js +2 -1
  79. package/web/kiosk-popover.js +4 -1
  80. package/web/kiosk-refit.test.js +81 -0
  81. package/web/kiosk-reset.js +49 -0
  82. package/web/kiosk-reset.test.js +11 -0
  83. package/web/kiosk-shot.js +40 -2
  84. package/web/kiosk-shot.test.js +23 -1
  85. package/web/kiosk-side.js +296 -0
  86. package/web/kiosk-side.test.js +249 -0
  87. package/web/kiosk-vendor.js +85 -7
  88. package/web/kiosk-vendor.test.js +9 -9
  89. package/web/kiosk-watch.js +20 -4
  90. package/web/kiosk-watch.test.js +15 -1
  91. package/web/kiosk.html +153 -1
  92. package/web/kiosk.js +252 -27
  93. package/web/kiosk.test.js +25 -1
  94. package/web/member-kind.js +31 -0
  95. package/web/small-stage.test.js +4 -0
  96. package/web/template-apps.js +245 -0
  97. package/web/template-apps.test.js +252 -0
  98. package/web/templates.js +285 -0
  99. package/web/templates.test.js +155 -0
  100. package/web/terragucci-change.js +30 -13
  101. package/web/terragucci-lifecycle.js +112 -62
  102. package/web/terragucci-lifecycle.test.js +29 -1
  103. package/web/terragucci-timeline.js +39 -2
  104. package/web/terragucci-timeline.test.js +42 -1
  105. package/web/tool-mark.js +4 -4
  106. package/web/tool-mark.test.js +1 -1
  107. package/web/vendors/atmos.svg +1 -0
  108. package/web/vendors/chant.svg +1 -0
  109. package/web/vendors/choudoufu.svg +1 -0
  110. package/web/vendors/terragrunt.svg +9 -0
  111. package/web/vendors/terragucci.svg +1 -0
  112. package/example-three-cloud/aws/chant.config.ts +0 -8
  113. package/example-three-cloud/aws/site.component.ts +0 -13
  114. package/example-three-cloud/aws/src/site.ts +0 -27
  115. package/example-three-cloud/azure/chant.config.ts +0 -1
  116. package/example-three-cloud/azure/src/site.component.ts +0 -13
  117. package/example-three-cloud/azure/src/site.ts +0 -18
  118. package/web/vendors/choudoufu-128.png +0 -0
  119. package/web/vendors/choudoufu-64.png +0 -0
  120. /package/example-carve/{legacy-tf → tf-root}/cdn.tf +0 -0
  121. /package/example-carve/{legacy-tf → tf-root}/compute.tf +0 -0
  122. /package/example-carve/{legacy-tf → tf-root}/floci-override.tf.disabled +0 -0
  123. /package/example-carve/{legacy-tf → tf-root}/modules/cdn/main.tf +0 -0
  124. /package/example-carve/{legacy-tf → tf-root}/naming.tf +0 -0
  125. /package/example-carve/{legacy-tf → tf-root}/network.tf +0 -0
  126. /package/example-carve/{legacy-tf → tf-root}/observability.tf +0 -0
  127. /package/example-carve/{legacy-tf → tf-root}/outputs.tf +0 -0
  128. /package/example-carve/{legacy-tf → tf-root}/storage.tf +0 -0
  129. /package/example-carve/{legacy-tf → tf-root}/versions.tf +0 -0
@@ -0,0 +1,547 @@
1
+ // behold#937: what a demo step's `ask` does to the graph. Pure logic here (what to
2
+ // light, how many depend on it, each state's file and look, the unknown slot and
3
+ // when it fills); web/kiosk-light-frame.js draws it in the graph frame, and
4
+ // startKioskLight wires the pane's events (behold#936) to both.
5
+ //
6
+ // The contract with the pane (behold#936):
7
+ // behold:ask-hold a step began: the graph holds still (nothing changes on its own) until a turn replies.
8
+ // behold:ask-start detail { ask, step, scenario } before the reply types; we set
9
+ // window.beholdAskTokens = { dependents } so the reply can fill it.
10
+ // behold:ask-light same detail, as the reply starts to print; we light the graph.
11
+ // behold:ask-done same detail, after the reply; lit here only if ask-light did not already light this beat.
12
+ // behold:ask-status a step that carries only a status (no prompt), as its busy line shows: lit like ask-light.
13
+ // behold:ask-clear a new step with no ask; the lighting goes.
14
+ //
15
+ // Everything is read from what the kiosk already holds: /api/terragucci (the
16
+ // reports joined onto the cards: `cards`, `roots`, `unmatched`, `pull_request`)
17
+ // and the run view (`progress`: `states`, `reads`). Nothing here fetches.
18
+
19
+ /**
20
+ * Whether a run is one composed apply across estates, not waves: any of the docs (the terragucci read, its pull request,
21
+ * a run's metrics, the run view) carries `compose.estate` or `compose.roots`, an estate scene, or a composed wave.
22
+ * Text for such a run never counts or names waves.
23
+ */
24
+ export function composedRun(...docs) {
25
+ const one = (d) => {
26
+ if (!d || typeof d !== "object") return false;
27
+ const c = d.compose;
28
+ if (c && (c.estate === true || (Array.isArray(c.roots) && c.roots.length))) return true;
29
+ if (d.estateScene && Array.isArray(d.estateScene.roots) && d.estateScene.roots.length) return true;
30
+ if (Array.isArray(d.states) && d.states.some((w) => w && w.composed)) return true;
31
+ return !!(d.pull_request && one(d.pull_request)) || !!(d.run && d.run !== d && one(d.run));
32
+ };
33
+ return docs.some(one);
34
+ }
35
+
36
+ export const COMPOSED_WORDS = "applied together in one apply";
37
+ /** behold#969: a chant composed run's re-plan that the first approval covered (chant#4419): said on the stack it re-planned. */
38
+ export const COVERED_WORDS = "one approval covered the re-plan";
39
+
40
+ /** An address with its instance keys dropped: `aws_x.y["a"]` is `aws_x.y`. */
41
+ export const bare = (address) => String(address || "").replace(/\[(?:"(?:[^"\\]|\\.)*"|[^\]])*\]/g, "");
42
+
43
+ /** The key a step names a resource by: `<root>/<address>`. */
44
+ export const lightKey = (root, address) => `${root}/${address}`;
45
+
46
+ /** A resource's name and type, for a card that leads with its name: `terraform_data.subnet` is `subnet` over `terraform_data`. */
47
+ export function cardTitle(address) {
48
+ const tokens = bare(address).split(".");
49
+ let i = 0;
50
+ while (tokens[i] === "module" && i + 1 < tokens.length) i += 2;
51
+ if (tokens[i] === "data") i += 1;
52
+ const type = tokens[i] || "";
53
+ const name = tokens.slice(i + 1).join(".");
54
+ const inst = (String(address).match(/(\[[^\]]*\])$/) || [])[1] || "";
55
+ return name ? { name: name + inst, type } : { name: bare(address) + inst, type: "" };
56
+ }
57
+
58
+ /** The block a card id names after its `<member>/<root>/` prefix, as an address. */
59
+ function addressOfBlock(block) {
60
+ return String(block).split("/").join(".");
61
+ }
62
+
63
+ /**
64
+ * The roots a step can light: the checkout's, then every estate the composed run names that the checkout does not list
65
+ * (the scene carries those). Each is `{ member, name, path }`.
66
+ */
67
+ export function rootsOf(answer) {
68
+ const base = answer && Array.isArray(answer.roots) ? answer.roots : [];
69
+ const scene = answer && answer.estateScene && Array.isArray(answer.estateScene.roots) ? answer.estateScene.roots : [];
70
+ const extra = scene.filter((r) => r && !base.some((b) => b.path === r.path));
71
+ return [...base, ...extra];
72
+ }
73
+
74
+ /**
75
+ * The plan as the kiosk's terragucci read holds it: the changed resources by
76
+ * `<root>/<address>` (with the card each is, when the checkout has one), the
77
+ * reads edges between roots, and the blast radius' resource reaches.
78
+ */
79
+ export function planOf(answer, progress = null) {
80
+ const out = { roots: [], resources: new Map(), edges: [], reaches: new Map(), reads: [] };
81
+ if (!answer || answer.error || !Array.isArray(answer.roots)) return out;
82
+ out.roots = rootsOf(answer).map((r) => ({ path: r.path, member: r.member, name: r.name }));
83
+ const rootAt = (id) => {
84
+ let best = null;
85
+ for (const r of answer.roots) {
86
+ const prefix = `${r.member}/${r.name}/`;
87
+ if (String(id).startsWith(prefix) && (!best || prefix.length > best.prefix.length)) best = { prefix, root: r };
88
+ }
89
+ return best;
90
+ };
91
+ const add = (root, address, extra) => {
92
+ const key = lightKey(root, address);
93
+ const had = out.resources.get(key);
94
+ if (had) {
95
+ if (extra.cardId && !had.cardId) had.cardId = extra.cardId;
96
+ if (extra.values && extra.values.length && !had.values.length) had.values = extra.values;
97
+ return;
98
+ }
99
+ out.resources.set(key, { key, root, address, ...cardTitle(address), cardId: null, action: null, values: [], ...extra });
100
+ };
101
+ // behold#940: a composed choudoufu run's resources, as its reports state them (an estate keeps no state file, and the graph's cards are as of the base).
102
+ const scene = answer.estateScene && Array.isArray(answer.estateScene.roots) ? answer.estateScene.roots : [];
103
+ for (const r of scene) {
104
+ for (const res of r.resources || []) add(r.path, res.address, { cardId: `${r.member}/${r.name}/${res.address}`, action: res.action || null, values: Array.isArray(res.values) ? res.values : [] });
105
+ }
106
+ for (const [id, marks] of Object.entries(answer.cards || {})) {
107
+ const at = rootAt(id);
108
+ if (!at) continue;
109
+ const mark = (marks || []).find((m) => m.verdict === "wave") || (marks || []).find((m) => m.verdict === "plan");
110
+ if (!mark) continue;
111
+ const addresses = mark.addresses && mark.addresses.length ? mark.addresses : [addressOfBlock(id.slice(at.prefix.length))];
112
+ for (const address of addresses) {
113
+ const values = (mark.values || []).filter((v) => !v.address || v.address === address);
114
+ add(at.root.path, address, { cardId: id, action: mark.action || null, values });
115
+ }
116
+ }
117
+ for (const c of (answer.unmatched && answer.unmatched.changes) || []) {
118
+ if (c.verdict === "drift") continue;
119
+ add(c.root, c.address, { action: c.action || null });
120
+ }
121
+ const pr = answer.pull_request;
122
+ const seen = new Set();
123
+ const edge = (from, to) => {
124
+ const k = `${from}\u0000${to}`;
125
+ if (from && to && from !== to && !seen.has(k)) {
126
+ seen.add(k);
127
+ out.edges.push({ from, to }); // from the upstream to the root that reads it
128
+ }
129
+ };
130
+ if (pr) {
131
+ for (const r of pr.reads || []) {
132
+ edge(r.upstream, r.root);
133
+ out.reads.push(r);
134
+ }
135
+ for (const [root, ups] of Object.entries(pr.upstreams || {})) for (const u of ups || []) edge(u, root);
136
+ for (const res of (pr.blast && pr.blast.resources) || []) out.reaches.set(lightKey(res.root, res.address), res.reaches || []);
137
+ } else if (answer.estateScene && Array.isArray(answer.estateScene.reads)) {
138
+ // behold#1012: a composed run drawn from its tf-apply report alone carries the reads on its scene. Root to root:
139
+ // the report maps no output to the resource that produced it, so they stay box-to-box.
140
+ for (const r of answer.estateScene.reads) {
141
+ edge(r.upstream, r.root);
142
+ out.reads.push(r);
143
+ }
144
+ }
145
+ if (progress && Array.isArray(progress.reads)) for (const r of progress.reads) for (const u of r.reads || []) edge(u, r.root);
146
+ // A composed run's members come in the order it applies them. When no read names an order, each reads the one before.
147
+ if (!out.edges.length) {
148
+ const members = pr && Array.isArray(pr.waves) ? (pr.waves.map((w) => w.composed && w.composed.members).find((m) => Array.isArray(m) && m.length > 1) || []) : [];
149
+ for (let i = 1; i < members.length; i++) edge(members[i - 1].root, members[i].root);
150
+ }
151
+ return out;
152
+ }
153
+
154
+ const TAG_PATHS = new Set(["tags", "tags_all"]);
155
+
156
+ /**
157
+ * Whether a changed resource of a downstream root is one that depends on what the root reads: a resource the apply
158
+ * creates or replaces, or one whose changed attributes are more than its tags. A tag-only update (the estate's own
159
+ * bookkeeping, unknown at plan) depends on nothing upstream.
160
+ */
161
+ export function dependsOnUpstream(res) {
162
+ if (res.action !== "update") return true;
163
+ const values = Array.isArray(res.values) ? res.values : [];
164
+ return !values.length || values.some((v) => !TAG_PATHS.has(v.path));
165
+ }
166
+
167
+ /**
168
+ * Which resources a step lights. `ask.light` names seeds as `<root>/<address>`
169
+ * (an unmatched one is skipped, never an error); `ask.paths` adds what is
170
+ * downstream: every changed resource of a root that reads a lit root, through
171
+ * the reads and dependency edges, and what the blast radius says refers to a
172
+ * seed inside its root. Null when the step lights nothing.
173
+ */
174
+ export function selectLight(plan, ask) {
175
+ if (!ask || typeof ask !== "object") return null;
176
+ const wanted = Array.isArray(ask.light) ? ask.light.filter((x) => typeof x === "string") : [];
177
+ if (!wanted.length) return null;
178
+ const seeds = [];
179
+ const skipped = [];
180
+ for (const w of wanted) {
181
+ const hit = plan.resources.has(w) ? w : [...plan.resources.keys()].find((k) => bare(k) === bare(w));
182
+ if (hit) {
183
+ if (!seeds.includes(hit)) seeds.push(hit);
184
+ } else skipped.push(w);
185
+ }
186
+ if (!seeds.length) return null;
187
+ const downstream = new Set();
188
+ if (ask.paths === true && seeds.length) {
189
+ for (const s of seeds) for (const r of plan.reaches.get(s) || []) {
190
+ const k = lightKey(r.root, r.address);
191
+ if (plan.resources.has(k)) downstream.add(k);
192
+ }
193
+ // The roots that read a seed's root, and the roots that read those.
194
+ const queue = [...new Set(seeds.map((s) => plan.resources.get(s).root))];
195
+ const roots = new Set(queue);
196
+ while (queue.length) {
197
+ const up = queue.shift();
198
+ for (const e of plan.edges) if (e.from === up && !roots.has(e.to)) {
199
+ roots.add(e.to);
200
+ queue.push(e.to);
201
+ }
202
+ }
203
+ for (const r of plan.resources.values()) if (roots.has(r.root) && !seeds.includes(r.key) && !seeds.some((s) => plan.resources.get(s).root === r.root) && dependsOnUpstream(r)) downstream.add(r.key);
204
+ }
205
+ const lit = [...seeds, ...[...downstream].filter((k) => !seeds.includes(k))];
206
+ const cards = lit.map((k) => plan.resources.get(k).cardId).filter(Boolean);
207
+ const rootsLit = [...new Set(lit.map((k) => plan.resources.get(k).root))];
208
+ return { seeds, lit, dependents: lit.length - seeds.length, cardIds: cards, roots: rootsLit, skipped };
209
+ }
210
+
211
+ /** `{dependents}` for the pane's reply: the number of nodes the step's `paths` lights, beyond the ones it names. */
212
+ export function dependentsOf(answer, progress, ask) {
213
+ if (!ask || ask.paths !== true) return null;
214
+ const sel = selectLight(planOf(answer, progress), ask);
215
+ return sel ? sel.dependents : 0;
216
+ }
217
+
218
+ // ---------------------------------------------------------------------------
219
+ // The states: a file name each, a written mark, and one of three looks.
220
+ // ---------------------------------------------------------------------------
221
+
222
+ const lastSegment = (path) => String(path || "").split("/").filter(Boolean).pop() || String(path || "");
223
+
224
+ /** A root's state file name: its backend's key from the run view, else the root's path with `.tfstate`. */
225
+ export function stateFile(root, progress) {
226
+ const r = progress && Array.isArray(progress.reads) ? progress.reads.find((x) => x.root === root) : null;
227
+ if (r && typeof r.stateKey === "string" && r.stateKey) return { file: r.stateKey, from: "run" };
228
+ return { file: `${lastSegment(root)}.tfstate`, from: "path" };
229
+ }
230
+
231
+ /** A composed member's, or a plain wave root's, apply outcome from the run view. */
232
+ export function applyOf(root, progress) {
233
+ const states = progress && Array.isArray(progress.states) ? progress.states : [];
234
+ for (const w of states) {
235
+ const m = w.composed && Array.isArray(w.composed.members) ? w.composed.members.find((x) => x.root === root) : null;
236
+ if (m) return { apply: m.apply || null, state: m.state || null, wave: w.number, waveState: w.state, ...(m.covered ? { covered: m.covered } : {}) };
237
+ }
238
+ for (const w of states) {
239
+ if (!Array.isArray(w.roots) || !w.roots.includes(root)) continue;
240
+ const changed = !Array.isArray(w.changed) || w.changed.includes(root);
241
+ if (w.state === "applied") return { apply: changed ? "applied" : "no-changes", state: changed ? "written" : "unchanged", wave: w.number, waveState: w.state };
242
+ if (w.state === "failed") return { apply: "partial", state: "written", wave: w.number, waveState: w.state };
243
+ if (w.state === "refused" || w.state === "blocked" || w.state === "not-started") return { apply: "not-started", state: "unchanged", wave: w.number, waveState: w.state };
244
+ return { apply: null, state: null, wave: w.number, waveState: w.state };
245
+ }
246
+ return null;
247
+ }
248
+
249
+ /**
250
+ * The run view, or in its place what the apply reports of its commit say. A pipeline that writes reports and no run
251
+ * view (choudoufu's Terragrunt and Atmos examples, whose workflows write chant-report's tf-plan and tf-apply only)
252
+ * leaves the read of the act's merge commit `present: false`, and its cards would say "known after apply" past the
253
+ * apply. Each root whose apply report is of that commit is then one apply's part, applied or failed as the report says,
254
+ * and the view is marked `reported`. A run view that is there, or a report of another commit, changes nothing.
255
+ */
256
+ export function reportedRunView(progress, answer) {
257
+ if (!progress || progress.error || !progress.run || progress.run.present !== false) return progress;
258
+ const commit = typeof progress.run.commit === "string" ? progress.run.commit : "";
259
+ if (commit.length < 7 || !answer || answer.error || !Array.isArray(answer.roots)) return progress;
260
+ const same = (c) => typeof c === "string" && c.length >= 7 && (c.startsWith(commit) || commit.startsWith(c));
261
+ const states = [];
262
+ for (const r of answer.roots) {
263
+ const a = r && r.apply;
264
+ if (!a || a.approval === "waiting" || !a.run || !same(a.run.commit)) continue;
265
+ if (a.status === "failed") states.push({ number: 1, state: "failed", roots: [r.path], reported: true });
266
+ else if (a.applied) states.push({ number: 1, state: "applied", roots: [r.path], changed: a.changes > 0 ? [r.path] : [], reported: true });
267
+ }
268
+ if (!states.length) return progress;
269
+ return { ...progress, run: { ...progress.run, present: true, reported: true }, states: [...(Array.isArray(progress.states) ? progress.states : []), ...states] };
270
+ }
271
+
272
+ /**
273
+ * The words on a root's badge in ask mode: no wave (a viewer has no use for one), and the step's own word. Follows the
274
+ * run view's outcome for the root when it has one, so the badge and the state label under the box agree.
275
+ * `st` is the root's state from rootStates; null when it has nothing to say.
276
+ */
277
+ export function badgeWords(st, root, progress) {
278
+ if (!st) return null;
279
+ if (st.state === "unchanged" || st.state === "outside") return st.words.replace(/^wave \d+ \u00b7 /, "");
280
+ const together = /composed/.test(st.words) ? " together" : "";
281
+ const a = applyOf(root, progress);
282
+ const apply = a && a.apply ? a.apply : st.state === "applied" ? "applied" : st.state === "failed" ? "partial" : st.state === "applying" ? "applying" : null;
283
+ if (apply === "applied" || apply === "no-changes") return `applied${together}`;
284
+ if (apply === "partial" || apply === "failed") return "partly applied";
285
+ if (apply === "not-started") return "not applied";
286
+ if (apply === "applying") return `applying${together}`;
287
+ return `planned${together}`;
288
+ }
289
+
290
+ export const LOOK_WORDS = { applied: "applied", partial: "partly applied", "not-applied": "not applied" };
291
+ const LOOK_OF = { applied: "applied", "no-changes": "applied", partial: "partial", failed: "partial", "not-started": "not-applied" };
292
+
293
+ /** Each root's state: `{ file, from, written, look }`. `look` is applied, partial, not-applied, or null while nothing is decided. */
294
+ export function stateMarks(answer, progress) {
295
+ const roots = answer && Array.isArray(answer.roots) ? rootsOf(answer).map((r) => r.path) : progress && Array.isArray(progress.reads) ? progress.reads.map((r) => r.root) : [];
296
+ // behold#940: an estate of choudoufu's has no state file: it holds records, one per resource, written as each applies.
297
+ // The reports' binaries say so too, and still do when a pin holds the scene back (a pull request being planned):
298
+ // the scene alone would call the same estates state files for that while.
299
+ const scene = !!(answer && answer.estateScene && Array.isArray(answer.estateScene.roots) && answer.estateScene.roots.length);
300
+ const binaries = (answer && answer.binaries) || {};
301
+ const out = {};
302
+ for (const root of roots) {
303
+ const a = applyOf(root, progress);
304
+ const estate = scene || binaries[root] === "choudoufu";
305
+ const file = estate ? { file: lastSegment(root), from: "estate", estate: true } : stateFile(root, progress);
306
+ out[root] = { ...file, written: !!a && a.state === "written", look: a && a.apply ? LOOK_OF[a.apply] || null : null, covered: !!(a && a.covered) };
307
+ }
308
+ return out;
309
+ }
310
+
311
+ /**
312
+ * The words of a state's label: its file, its look, and that it was written. An estate has no file to name, and its
313
+ * name is already its box's title: its label says only the look and the records written, and is empty (no label is
314
+ * drawn) until there is one of them to say. A label of the name alone read as a second copy of the box.
315
+ */
316
+ export function stateWords(m) {
317
+ return [m.estate ? null : `state ${m.file}`, m.look ? LOOK_WORDS[m.look] : null, m.written ? (m.estate ? "records written" : "written") : null, m.covered ? COVERED_WORDS : null].filter(Boolean).join(" \u00b7 ");
318
+ }
319
+
320
+ // ---------------------------------------------------------------------------
321
+ // The unknown value: a marked empty slot, and when it fills.
322
+ // ---------------------------------------------------------------------------
323
+
324
+ /**
325
+ * The resource whose creation makes a card's unknown input known: the blast
326
+ * radius' reach into it through an output, else a created resource of the root
327
+ * it reads, else itself (an output that is its own).
328
+ */
329
+ export function producerOf(plan, res) {
330
+ for (const [seed, reaches] of plan.reaches) {
331
+ if ((reaches || []).some((r) => r.root === res.root && r.address === res.address && r.through)) {
332
+ const p = plan.resources.get(seed);
333
+ if (p && p.key !== res.key) return p;
334
+ }
335
+ }
336
+ for (const r of plan.reads) {
337
+ if (r.root !== res.root || !(r.unknown && r.unknown.length)) continue;
338
+ const created = [...plan.resources.values()].filter((x) => x.root === r.upstream && x.action === "create");
339
+ const owner = created.find((x) => x.values.some((v) => v.unknown)) || created[0];
340
+ if (owner) return owner;
341
+ }
342
+ return res;
343
+ }
344
+
345
+ /** Every unknown attribute of the planned resources: `{ key, cardId, path, producer, text }`. */
346
+ export function unknownSlots(plan) {
347
+ const slots = [];
348
+ for (const res of plan.resources.values()) {
349
+ for (const v of res.values) {
350
+ if (!v.unknown) continue;
351
+ const producer = producerOf(plan, res);
352
+ slots.push({ key: res.key, cardId: res.cardId, root: res.root, address: res.address, path: v.path, producer: producer.key, producerRoot: producer.root, text: `not known until ${producer.name} exists` });
353
+ }
354
+ }
355
+ return slots;
356
+ }
357
+
358
+ /** The most attribute lines a card shows in ask mode. */
359
+ export const MAX_CARD_LINES = 2;
360
+
361
+ const isEmptyValue = (v) => v === undefined || v === null || v === "" || (Array.isArray(v) && !v.length);
362
+ const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
363
+
364
+ /**
365
+ * The attribute lines a card shows in ask mode, at most MAX_CARD_LINES for each card id: the attributes that were
366
+ * unknown at plan and read another estate's value (the ones the root's reads name, `subnet_id`, `vpc_id`, and any
367
+ * attribute an `ask.light` address names as `<root>/<address>.<attribute>`), then the attributes whose known value
368
+ * changed. Every other attribute is left out. Each line is `{ key, cardId, root, address, path, kind, producer,
369
+ * producerRoot, producerName, before, after }` with kind `unknown` or `changed`.
370
+ */
371
+ export function cardLines(plan, light = []) {
372
+ const lit = new Set((Array.isArray(light) ? light : []).filter((w) => typeof w === "string"));
373
+ const named = new Map();
374
+ for (const w of Array.isArray(light) ? light : []) {
375
+ if (typeof w !== "string") continue;
376
+ for (const res of plan.resources.values()) if (w.startsWith(`${res.key}.`) || w.startsWith(`${bare(res.key)}.`)) {
377
+ const tail = w.slice(w.indexOf(res.key) === 0 ? res.key.length + 1 : bare(res.key).length + 1);
378
+ if (!named.has(res.key)) named.set(res.key, new Set());
379
+ named.get(res.key).add(tail);
380
+ }
381
+ }
382
+ const lines = [];
383
+ for (const res of plan.resources.values()) {
384
+ if (!res.cardId) continue;
385
+ const readNames = new Set(plan.reads.filter((r) => r.root === res.root).flatMap((r) => r.unknown || []));
386
+ const asked = named.get(res.key) || new Set();
387
+ const reads = res.values.filter((v) => v.unknown && v.path !== "id" && (!("before" in v) || isEmptyValue(v.before)) && (readNames.has(v.path) || asked.has(v.path) || v.path === "subnet_id" || v.path === "vpc_id"));
388
+ const rank = (v) => (asked.has(v.path) ? 0 : readNames.has(v.path) ? 1 : v.path === "subnet_id" ? 2 : 3);
389
+ reads.sort((a, b) => rank(a) - rank(b));
390
+ // Rule 5: never a false or empty default (a created resource's `assign_ipv6_address_on_creation: false`): the before is a real value.
391
+ const changed = res.values.filter((v) => !v.unknown && v.path !== "id" && "before" in v && "after" in v && !isEmptyValue(v.before) && JSON.stringify(v.before) !== JSON.stringify(v.after));
392
+ // A report that names the property an update touches but states neither value (chant's change-set entries: property
393
+ // names only) still shows the line, as "Value: updated".
394
+ const touched = res.action === "update" ? res.values.filter((v) => !v.unknown && v.path !== "id" && !("before" in v) && !("after" in v)) : [];
395
+ const producer = reads.length ? producerOf(plan, res) : res;
396
+ // A lit resource, or a created one with nothing else to show, is never a blank card: it shows its id.
397
+ const isLit = lit.has(res.key) || lit.has(bare(res.key));
398
+ // Rule 1: a lit resource, or any created one whose id is unknown at plan, leads with its id.
399
+ const idKnown = res.values.some((v) => v.path === "id" && !v.unknown && "after" in v && !isEmptyValue(v.after));
400
+ const idUnknownAtPlan = res.action === "create" && !idKnown;
401
+ const idLine = !idKnown && (isLit || idUnknownAtPlan) ? [[{ path: "id", unknown: true }, "unknown", res]] : [];
402
+ const row = (v, kind, prod) => ({ key: res.key, cardId: res.cardId, root: res.root, address: res.address, path: v.path, kind, producer: prod.key, producerRoot: prod.root, producerName: prod.name, before: v.before, after: v.after });
403
+ for (const v of [...idLine, ...reads.map((x) => [x, "unknown"]), ...changed.map((x) => [x, "changed"]), ...touched.map((x) => [x, "changed"])].slice(0, MAX_CARD_LINES)) lines.push(row(v[0], v[1], v[2] || producer));
404
+ }
405
+ return lines;
406
+ }
407
+
408
+ /**
409
+ * A card line's look and words: unknown reads "known after apply" (amber, dashed); applied reads the real value (green),
410
+ * or the producer it was filled from when the apply report gives no value; a changed value reads `before -> after`.
411
+ * `{ state: "unknown" | "applied" | "changed", text }`.
412
+ */
413
+ export function lineState(line, answer, progress) {
414
+ if (line.kind === "unknown") {
415
+ const st = slotState({ key: line.key, cardId: line.cardId, path: line.path, producer: line.producer, producerRoot: line.producerRoot }, answer, progress);
416
+ if (!st.filled) return { state: "unknown", text: `${line.path}: known after apply` };
417
+ const path = st.path || line.path;
418
+ // "filled from" only when the apply report states no value. A resource that is its own producer was simply created.
419
+ if (st.value !== undefined) return { state: "applied", text: `${path}: ${show(st.value)}` };
420
+ return { state: "applied", text: line.producer === line.key ? `${line.path}: created` : `${line.path}: filled from ${line.producerName}` };
421
+ }
422
+ const a = applyOf(line.root, progress);
423
+ const done = !!a && (a.apply === "applied" || a.apply === "no-changes");
424
+ const stated = "before" in line && "after" in line && (line.before !== undefined || line.after !== undefined);
425
+ return { state: done ? "applied" : "changed", text: stated ? `${line.path}: ${show(line.before)} -> ${show(line.after)}` : `${line.path}: updated` };
426
+ }
427
+
428
+ /**
429
+ * Whether a slot has been filled, and with what. Filled once the producer's root
430
+ * has applied (the run view's member or wave). Its value is shown only when an
431
+ * apply-time report states one (`answer.applied`, what the root's newest applied
432
+ * wave wrote); run.json states none, so otherwise the slot is filled with no value.
433
+ */
434
+ export function slotState(slot, answer, progress) {
435
+ const a = applyOf(slot.producerRoot, progress);
436
+ const filled = !!a && (a.apply === "applied" || a.apply === "no-changes");
437
+ const wrote = slot.cardId && answer && answer.applied ? answer.applied[slot.cardId] : null;
438
+ const known = filled && wrote ? (wrote.values || []).filter((x) => !x.unknown && "after" in x) : [];
439
+ let v = known.find((x) => x.path === slot.path);
440
+ // behold#940: a resource that is its own producer (the subnet) shows what it exported when the exact attribute is not stated: its id, else its first value.
441
+ let path = slot.path;
442
+ if (!v && slot.producer === slot.key && slot.path !== "id") {
443
+ v = known.find((x) => x.path === "id") || known[0];
444
+ if (v) path = v.path;
445
+ }
446
+ return v ? { filled, value: v.after, ...(path !== slot.path ? { path } : {}) } : { filled };
447
+ }
448
+
449
+ // ---------------------------------------------------------------------------
450
+ // Wiring.
451
+ // ---------------------------------------------------------------------------
452
+
453
+ /** The message the frame takes: what to light, whether to ghost the second approval, and a token that changes with each beat (so the pulse plays once). */
454
+ export function lightMessage(sel, ask, token) {
455
+ return {
456
+ type: "behold:light",
457
+ labels: true, // the frame labels each state with its file once any step has had an ask
458
+ ids: sel ? sel.cardIds : [],
459
+ roots: sel ? sel.roots : [],
460
+ lit: !!sel,
461
+ ghost: !!(ask && ask.ghost === true),
462
+ light: ask && Array.isArray(ask.light) ? ask.light.filter((x) => typeof x === "string") : [],
463
+ token,
464
+ };
465
+ }
466
+
467
+ /** How long after a beat's reply to look again for the reads a step lights, while they are not in. */
468
+ export const RETRY_MS = [400, 800, 1600, 3200];
469
+
470
+ /**
471
+ * Listen for the pane's events and tell the frame. `post` sends a message to the
472
+ * frame; `getAnswer` and `getProgress` give the kiosk's current reads.
473
+ * Returns a stop function.
474
+ */
475
+ export function startKioskLight({ post, getAnswer, getProgress, win = typeof window !== "undefined" ? window : null }) {
476
+ if (!win) return () => {};
477
+ let last = null;
478
+ let n = 0;
479
+ const send = (m) => {
480
+ last = m;
481
+ post(m);
482
+ };
483
+ const askOf = (e) => (e && e.detail && e.detail.ask && typeof e.detail.ask === "object" ? e.detail.ask : null);
484
+ // Every step holds the graph the moment it begins, so a status-only step cannot let progress through before its busy line has shown.
485
+ const onHold = () => post({ type: "behold:hold" });
486
+ const onStart = (e) => {
487
+ const ask = askOf(e);
488
+ const d = ask ? dependentsOf(getAnswer(), getProgress(), ask) : null;
489
+ win.beholdAskTokens = d === null ? {} : { dependents: d };
490
+ // The graph holds still until this step's reply is done (or its status shows): progress is queued meanwhile.
491
+ post({ type: "behold:hold" });
492
+ };
493
+ // behold#940: the lit state is drawn the moment the reply starts (it used to wait for the reply to be done). When the reads the step lights are not in yet
494
+ // (the kiosk's own poll is behind the frame's), it asks again soon, never waiting for a poll's turn.
495
+ let litAsk = null;
496
+ const onLight = (e) => {
497
+ const ask = askOf(e);
498
+ litAsk = ask;
499
+ const wants = !!(ask && Array.isArray(ask.light) && ask.light.length);
500
+ const attempt = (k) => {
501
+ const sel = ask ? selectLight(planOf(getAnswer(), getProgress()), ask) : null;
502
+ n += 1;
503
+ const mine = n;
504
+ send(lightMessage(sel, ask, mine));
505
+ if (!sel && wants && k < RETRY_MS.length && typeof win.setTimeout === "function") {
506
+ win.setTimeout(() => {
507
+ if (n === mine) attempt(k + 1);
508
+ }, RETRY_MS[k]);
509
+ }
510
+ };
511
+ attempt(0);
512
+ };
513
+ // The reply has printed: already lit as it started, unless that word never came.
514
+ const onDone = (e) => {
515
+ const ask = askOf(e);
516
+ if (ask && ask === litAsk) return;
517
+ onLight(e);
518
+ };
519
+ // A step that carries only a status has no reply to wait for: it lights as soon as the pane says so.
520
+ const onStatus = (e) => onLight(e);
521
+ const onClear = () => {
522
+ n += 1;
523
+ litAsk = null;
524
+ win.beholdAskTokens = {};
525
+ send(lightMessage(null, null, n));
526
+ };
527
+ // A frame that reloaded asks nothing; it is told again when it says it has drawn.
528
+ const onMessage = (e) => {
529
+ if (last && e && e.data && e.data.type === "behold:drawn") post(last);
530
+ };
531
+ win.addEventListener("behold:ask-hold", onHold);
532
+ win.addEventListener("behold:ask-start", onStart);
533
+ win.addEventListener("behold:ask-light", onLight);
534
+ win.addEventListener("behold:ask-done", onDone);
535
+ win.addEventListener("behold:ask-status", onStatus);
536
+ win.addEventListener("behold:ask-clear", onClear);
537
+ win.addEventListener("message", onMessage);
538
+ return () => {
539
+ win.removeEventListener("behold:ask-hold", onHold);
540
+ win.removeEventListener("behold:ask-start", onStart);
541
+ win.removeEventListener("behold:ask-light", onLight);
542
+ win.removeEventListener("behold:ask-done", onDone);
543
+ win.removeEventListener("behold:ask-status", onStatus);
544
+ win.removeEventListener("behold:ask-clear", onClear);
545
+ win.removeEventListener("message", onMessage);
546
+ };
547
+ }