@huaweidevtools/aishell-dsh-deploy 0.0.19 → 0.0.21

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.
package/lib/index.js CHANGED
@@ -7,11 +7,10 @@ import { fileURLToPath } from "node:url";
7
7
  import { dshHome } from "@huaweidevtools/aishell-dsh-credentials-store/paths";
8
8
  import { spawn } from "node:child_process";
9
9
  import { homedir, tmpdir } from "node:os";
10
- import { readStoredPair } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
10
+ import { clearCredentials, readStoredPair } from "@huaweidevtools/aishell-dsh-credentials-store/accounts";
11
11
  import { verifyCredentials } from "@huaweidevtools/aishell-dsh-credentials-store/verify";
12
12
  import { createHash, createHmac } from "node:crypto";
13
13
  import { createRequire } from "node:module";
14
- import { D2 } from "@terrastruct/d2";
15
14
  import { JSONPath } from "jsonpath-plus";
16
15
  import AdmZip from "adm-zip";
17
16
 
@@ -1692,7 +1691,7 @@ function withAnchoredPaths(args, ctx) {
1692
1691
  * written by earlier releases carry it — so it is kept even though there is no
1693
1692
  * server.
1694
1693
  */
1695
- const SERVER_VERSION = "aishell-deploy 0.0.19";
1694
+ const SERVER_VERSION = "aishell-deploy 0.0.21";
1696
1695
 
1697
1696
  //#endregion
1698
1697
  //#region src/deployment-state.ts
@@ -2020,6 +2019,7 @@ async function loadAccount() {
2020
2019
  const result = await verifyCredentials(credentials, { region: "global" });
2021
2020
  if (!result.ok) {
2022
2021
  if (result.status === 0 || result.status >= 500) throw new Error(`${result.message} The stored credentials were not rejected — retry.`);
2022
+ source?.onRejected?.();
2023
2023
  return void 0;
2024
2024
  }
2025
2025
  cachedAccount = {
@@ -3923,7 +3923,7 @@ async function handlePrice(deployment) {
3923
3923
  period: "month",
3924
3924
  hours: HOURS_PER_MONTH,
3925
3925
  priced_at: pricedAt,
3926
- regions: [...new Set(quotes.map((quote$1) => quote$1.region))].sort(),
3926
+ regions: [...new Set(quotes.map((quote) => quote.region))].sort(),
3927
3927
  tf_hash: await computeTfHash(deployment),
3928
3928
  plan_file: PLAN_FILE,
3929
3929
  nothing_billable: nothingBillable,
@@ -4336,14 +4336,14 @@ function statesNothingBillable(quoted, unpriced) {
4336
4336
  * total, which is `null` when there is none to compute.
4337
4337
  */
4338
4338
  function quoteTotal(quotes) {
4339
- const currencies = [...new Set(quotes.map((quote$1) => quote$1.currency))].sort();
4339
+ const currencies = [...new Set(quotes.map((quote) => quote.currency))].sort();
4340
4340
  if (quotes.length === 0 || currencies.length > 1) return {
4341
4341
  currencies,
4342
4342
  total: null
4343
4343
  };
4344
4344
  return {
4345
4345
  currencies,
4346
- total: round(quotes.reduce((sum, quote$1) => sum + quote$1.monthly, 0))
4346
+ total: round(quotes.reduce((sum, quote) => sum + quote.monthly, 0))
4347
4347
  };
4348
4348
  }
4349
4349
  /**
@@ -5800,30 +5800,611 @@ function edgesOf(blocks, topology) {
5800
5800
  }
5801
5801
 
5802
5802
  //#endregion
5803
- //#region src/existing-topology.ts
5804
- /** Facts worth showing on a box, by the attribute name that holds them. */
5805
- const LABEL_ATTRIBUTES = [
5806
- "name",
5807
- "cidr",
5808
- "publicIpAddress",
5809
- "ipAddress",
5810
- "vip_address",
5811
- "flavor",
5812
- "flavorCode",
5813
- "spec",
5814
- "nodeFlavor",
5815
- "clusterFlavor",
5816
- "size",
5817
- "engineName",
5818
- "engineVersion",
5819
- "status",
5820
- "instanceStatus",
5821
- "clusterStatus",
5822
- "provisioning_status",
5823
- "availability_zone",
5824
- "az"
5803
+ //#region src/layout.ts
5804
+ /**
5805
+ * Horizontal space one character of a label takes.
5806
+ *
5807
+ * Measured against the font the diagram is drawn with: the renderer emits
5808
+ * `font-size: 16` with a sans-serif face, whose average advance is a little
5809
+ * over half an em. 9.6 is 0.6em, which is slightly generous — a box that is a
5810
+ * few pixels too wide reads as padding, and one that is too narrow truncates a
5811
+ * name.
5812
+ */
5813
+ const CHAR_WIDTH = 9.6;
5814
+ /** Line height for a label at that size. */
5815
+ const LINE_HEIGHT = 22;
5816
+ /** Line height for a detail line, which is drawn a size smaller. */
5817
+ const DETAIL_LINE_HEIGHT = 17;
5818
+ /**
5819
+ * The text a box carries, with its count in brackets.
5820
+ *
5821
+ * `sg-postgresql [1]` rather than a separate figure: the count qualifies the
5822
+ * name, and putting it there keeps the box one line of identity instead of two
5823
+ * blocks a reader has to associate.
5824
+ *
5825
+ * @param label - the box's own label.
5826
+ * @param figure - the count, when there is one.
5827
+ * @returns the label with the count appended.
5828
+ */
5829
+ function labelWithFigure(label, figure) {
5830
+ return figure === void 0 ? label : `${label} [${figure}]`;
5831
+ }
5832
+ /**
5833
+ * The height of a container's title band, including its detail lines.
5834
+ *
5835
+ * A container's own label sits at the top of the band and each detail line
5836
+ * under it, so the band has to be tall enough for both — plus the gap that
5837
+ * keeps the last line clear of the first row of children.
5838
+ *
5839
+ * `measure` sizes the box with this and `place` positions the children with it.
5840
+ * Those two must be the same number: a band sized for the label alone puts the
5841
+ * first row of children where the detail lines are drawn, and the lines land on
5842
+ * top of the child boxes.
5843
+ *
5844
+ * @param detail - the container's detail lines.
5845
+ * @returns the band height in pixels.
5846
+ */
5847
+ function bandHeight(detail) {
5848
+ return detail.length === 0 ? TITLE_BAND : TITLE_BAND + detail.length * DETAIL_LINE_HEIGHT + SIBLING_GAP / 2;
5849
+ }
5850
+ /**
5851
+ * The width the widest detail line needs.
5852
+ *
5853
+ * @param detail - the lines under a container's label.
5854
+ * @returns the width in pixels, 0 when there are none.
5855
+ */
5856
+ function textWidthOf(detail) {
5857
+ return detail.length === 0 ? 0 : Math.max(...detail.map((line) => textWidth(line)));
5858
+ }
5859
+ /** Space between a container's border and its contents. */
5860
+ const PADDING$1 = 16;
5861
+ /** Space between sibling boxes. */
5862
+ const SIBLING_GAP = 20;
5863
+ /**
5864
+ * The band at a container's top that holds its own label.
5865
+ *
5866
+ * 34, not the 26 that would fit a 13px line exactly: the label's baseline sits
5867
+ * 24 below the top edge, so text occupies roughly 18–30 and leaves 4px above
5868
+ * and 4px below. A band sized to the type exactly reads as pressed against the
5869
+ * frame, which is the thing this margin exists to prevent.
5870
+ */
5871
+ const TITLE_BAND = 34;
5872
+ /** The narrowest a leaf box is allowed to be, so a short name is not a sliver. */
5873
+ const MIN_LEAF_WIDTH = 120;
5874
+ /**
5875
+ * The width a label needs.
5876
+ *
5877
+ * @param label - the text on the box.
5878
+ * @returns its width in pixels.
5879
+ */
5880
+ function textWidth(label) {
5881
+ return label.length * CHAR_WIDTH;
5882
+ }
5883
+ /**
5884
+ * The extent of a set of boxes packed into a given number of columns.
5885
+ *
5886
+ * @param sizes - the child extents.
5887
+ * @param columns - how many share a row.
5888
+ * @returns the packed width and height.
5889
+ */
5890
+ function pack(sizes, columns) {
5891
+ const rows = Math.ceil(sizes.length / columns);
5892
+ let width = 0;
5893
+ let height = 0;
5894
+ for (let row = 0; row < rows; row++) {
5895
+ const slice = sizes.slice(row * columns, (row + 1) * columns);
5896
+ width = Math.max(width, slice.reduce((sum, size) => sum + size.width, 0) + SIBLING_GAP * (slice.length - 1));
5897
+ height += Math.max(...slice.map((size) => size.height)) + (row < rows - 1 ? SIBLING_GAP : 0);
5898
+ }
5899
+ return {
5900
+ width,
5901
+ height
5902
+ };
5903
+ }
5904
+ /**
5905
+ * The column count that packs a set of boxes into the least elongated block.
5906
+ *
5907
+ * The measure is logarithmic, so a block twice as wide as it is tall scores the
5908
+ * same as one twice as tall as it is wide. A linear measure would call a wide
5909
+ * strip "close enough" whenever the target were small, which is the failure
5910
+ * this whole module exists to avoid.
5911
+ *
5912
+ * @param sizes - the child extents.
5913
+ * @returns the best column count, at least 1.
5914
+ */
5915
+ function squarestColumns(sizes) {
5916
+ let best = 1;
5917
+ let bestError = Infinity;
5918
+ const limit = Math.min(sizes.length, 4);
5919
+ for (let columns = 1; columns <= limit; columns++) {
5920
+ const packed = pack(sizes, columns);
5921
+ const error = Math.abs(Math.log(packed.width / packed.height));
5922
+ if (error < bestError) {
5923
+ bestError = error;
5924
+ best = columns;
5925
+ }
5926
+ }
5927
+ return best;
5928
+ }
5929
+ /**
5930
+ * Measure a tree, bottom up.
5931
+ *
5932
+ * @param node - the node to measure.
5933
+ * @returns its extent and its children's, all positioned at the origin.
5934
+ */
5935
+ function measure(node) {
5936
+ if (node.children.length === 0) {
5937
+ const detail$1 = node.detail ?? [];
5938
+ const label = labelWithFigure(node.label, node.figure);
5939
+ const widest = Math.max(textWidth(label), ...detail$1.map((line) => textWidth(line)));
5940
+ return {
5941
+ node,
5942
+ width: Math.max(widest + PADDING$1 * 2, MIN_LEAF_WIDTH),
5943
+ height: LINE_HEIGHT + PADDING$1 + detail$1.length * DETAIL_LINE_HEIGHT,
5944
+ columns: 1,
5945
+ children: []
5946
+ };
5947
+ }
5948
+ const children = equalWidth(node.children.map((child) => measure(child)));
5949
+ const columns = squarestColumns(children);
5950
+ const packed = pack(children, columns);
5951
+ const detail = node.detail ?? [];
5952
+ return {
5953
+ node,
5954
+ width: Math.max(packed.width, textWidthOf(detail)) + PADDING$1 * 2,
5955
+ height: packed.height + bandHeight(detail) + PADDING$1,
5956
+ columns,
5957
+ children
5958
+ };
5959
+ }
5960
+ /**
5961
+ * Give every sibling the width of the widest one.
5962
+ *
5963
+ * The width is applied to each child's OWN width, so a container among them
5964
+ * keeps room for its own contents; only the excess is added, never taken away.
5965
+ * Heights are left alone — a tall container beside a short leaf is a real
5966
+ * difference, and equalising it would pad every leaf to the size of a VPC.
5967
+ *
5968
+ * @param siblings - the measured children of one parent.
5969
+ * @returns the same children, widened to a common width.
5970
+ */
5971
+ function equalWidth(siblings) {
5972
+ if (siblings.length < 2) return [...siblings];
5973
+ const widest = Math.max(...siblings.map((child) => child.width));
5974
+ return siblings.map((child) => child.width === widest ? child : {
5975
+ ...child,
5976
+ width: widest
5977
+ });
5978
+ }
5979
+ /**
5980
+ * Position a measured tree, top down.
5981
+ *
5982
+ * @param measured - the tree to place.
5983
+ * @param x - the left edge to place it at.
5984
+ * @param y - the top edge to place it at.
5985
+ * @param depth - the nesting depth, for the caller's styling.
5986
+ * @returns the placed boxes.
5987
+ */
5988
+ function place(measured, x, y, depth) {
5989
+ const self = {
5990
+ id: measured.node.id,
5991
+ label: measured.node.label,
5992
+ x,
5993
+ y,
5994
+ width: measured.width,
5995
+ height: measured.height,
5996
+ depth,
5997
+ existing: measured.node.existing === true,
5998
+ provider: measured.node.provider ?? "",
5999
+ detail: measured.node.detail ?? [],
6000
+ figure: measured.node.figure,
6001
+ children: []
6002
+ };
6003
+ if (measured.children.length === 0) return [self];
6004
+ const direct = [];
6005
+ const descendants = [];
6006
+ const rows = Math.ceil(measured.children.length / measured.columns);
6007
+ let cursorY = y + bandHeight(measured.node.detail ?? []);
6008
+ for (let row = 0; row < rows; row++) {
6009
+ const slice = measured.children.slice(row * measured.columns, (row + 1) * measured.columns);
6010
+ const rowWidth = slice.reduce((sum, child) => sum + child.width, 0) + SIBLING_GAP * (slice.length - 1);
6011
+ let cursorX = x + PADDING$1 + (measured.width - PADDING$1 * 2 - rowWidth) / 2;
6012
+ for (const child of slice) {
6013
+ const [self_, ...rest] = place(child, cursorX, cursorY, depth + 1);
6014
+ direct.push(self_);
6015
+ descendants.push(self_, ...rest);
6016
+ cursorX += child.width + SIBLING_GAP;
6017
+ }
6018
+ cursorY += Math.max(...slice.map((child) => child.height)) + SIBLING_GAP;
6019
+ }
6020
+ return [{
6021
+ ...self,
6022
+ children: direct
6023
+ }, ...descendants];
6024
+ }
6025
+ /**
6026
+ * Lay out a tree of nested boxes.
6027
+ *
6028
+ * ## How the roots are arranged
6029
+ *
6030
+ * The roots are the same layer of the picture — a VPC, a band of shared
6031
+ * services — so they are packed beside each other rather than stacked. Which
6032
+ * The roots go in ONE row, however narrow the result. They are the top of the
6033
+ * picture — regions, usually — and a reader compares them left to right: which
6034
+ * region holds the VPC, which holds only a default group. Wrapping them onto
6035
+ * several rows puts two regions above two others with nothing saying they are
6036
+ * peers, and the eye reads that as a hierarchy that does not exist.
6037
+ *
6038
+ * Everything below a root is packed by the square rule, because there the
6039
+ * alternatives really are equivalent and the aspect decides.
6040
+ *
6041
+ * @param roots - the outermost boxes.
6042
+ * @param margin - space left around the whole drawing.
6043
+ * @returns the placed boxes and the canvas extent.
6044
+ */
6045
+ function layoutTree(roots, margin = 40) {
6046
+ const measured = roots.map((root) => measure(root));
6047
+ const columns = measured.length;
6048
+ const packed = pack(measured, columns);
6049
+ const placed = [];
6050
+ const rows = Math.ceil(measured.length / columns);
6051
+ let cursorY = margin;
6052
+ for (let row = 0; row < rows; row++) {
6053
+ const slice = measured.slice(row * columns, (row + 1) * columns);
6054
+ const rowWidth = slice.reduce((sum, box) => sum + box.width, 0) + SIBLING_GAP * (slice.length - 1);
6055
+ let cursorX = margin + (packed.width - rowWidth) / 2;
6056
+ for (const box of slice) {
6057
+ placed.push(...place(box, cursorX, cursorY, 0));
6058
+ cursorX += box.width + SIBLING_GAP;
6059
+ }
6060
+ cursorY += Math.max(...slice.map((box) => box.height)) + SIBLING_GAP;
6061
+ }
6062
+ return {
6063
+ boxes: placed,
6064
+ roots: placed.filter((box) => box.depth === 0),
6065
+ width: packed.width + margin * 2,
6066
+ height: cursorY - SIBLING_GAP + margin
6067
+ };
6068
+ }
6069
+
6070
+ //#endregion
6071
+ //#region src/svg-render.ts
6072
+ /**
6073
+ * The hues a container is drawn in, by its nesting depth.
6074
+ *
6075
+ * Depth alone cannot say WHICH thing a box is — a security group and an ECS sit
6076
+ * at the same level — so this is not an identity, only a way to read the nesting
6077
+ * at a glance. Two colours alternate down the levels, which is enough to see
6078
+ * where one container ends and the next begins without turning the picture into
6079
+ * a palette.
6080
+ *
6081
+ * A resource's own service is a different question, answered by `serviceHue`.
6082
+ */
6083
+ const CONTAINER_DEPTH_FILL = [
6084
+ "#e8eef7",
6085
+ "#dde7f5",
6086
+ "#d2dff2"
6087
+ ];
6088
+ const CONTAINER_DEPTH_STROKE = [
6089
+ "#9aa8bd",
6090
+ "#8294af",
6091
+ "#6b80a0"
5825
6092
  ];
5826
6093
  /**
6094
+ * Convert HSL to a `#rrggbb` string.
6095
+ *
6096
+ * The conversion is done here rather than left to the renderer, because several
6097
+ * SVG rasterisers do not parse the space-separated CSS Color 4 syntax and fall
6098
+ * back to black without reporting anything.
6099
+ *
6100
+ * @param hue - 0–359.
6101
+ * @param saturation - 0–100.
6102
+ * @param lightness - 0–100.
6103
+ * @returns the colour as hex.
6104
+ */
6105
+ function hslToHex(hue, saturation, lightness) {
6106
+ const s = saturation / 100;
6107
+ const l = lightness / 100;
6108
+ const c = (1 - Math.abs(2 * l - 1)) * s;
6109
+ const x = c * (1 - Math.abs(hue / 60 % 2 - 1));
6110
+ const m = l - c / 2;
6111
+ const [r, g, b] = hue < 60 ? [
6112
+ c,
6113
+ x,
6114
+ 0
6115
+ ] : hue < 120 ? [
6116
+ x,
6117
+ c,
6118
+ 0
6119
+ ] : hue < 180 ? [
6120
+ 0,
6121
+ c,
6122
+ x
6123
+ ] : hue < 240 ? [
6124
+ 0,
6125
+ x,
6126
+ c
6127
+ ] : hue < 300 ? [
6128
+ x,
6129
+ 0,
6130
+ c
6131
+ ] : [
6132
+ c,
6133
+ 0,
6134
+ x
6135
+ ];
6136
+ const channel = (value) => Math.round((value + m) * 255).toString(16).padStart(2, "0");
6137
+ return `#${channel(r)}${channel(g)}${channel(b)}`;
6138
+ }
6139
+ /**
6140
+ * The hue a service's boxes are tinted with.
6141
+ *
6142
+ * Keyed by the provider the inventory reports, which is a stable identity: every
6143
+ * `ecs` resource is the same service whatever it is called. A hash rather than a
6144
+ * table, for the reason the connector colours use one — a table would need a
6145
+ * line per service and would be wrong the first time an unfamiliar one appeared.
6146
+ *
6147
+ * @param provider - the service that reported the resource.
6148
+ * @returns a hue in degrees, 0–359.
6149
+ */
6150
+ function serviceHue(provider) {
6151
+ let value = 0;
6152
+ for (const character of provider) value = value * 31 + character.charCodeAt(0) >>> 0;
6153
+ return value % 360;
6154
+ }
6155
+ /**
6156
+ * The fill and stroke for one box.
6157
+ *
6158
+ * @param role - whether the box holds other boxes.
6159
+ * @param provider - the service that reported it, for a resource.
6160
+ * @param depth - the nesting level, for a container.
6161
+ * @returns the two colours.
6162
+ */
6163
+ function boxColours(role, provider, depth) {
6164
+ if (role === "container") {
6165
+ const level = Math.min(depth, CONTAINER_DEPTH_FILL.length - 1);
6166
+ return {
6167
+ fill: CONTAINER_DEPTH_FILL[level],
6168
+ stroke: CONTAINER_DEPTH_STROKE[level]
6169
+ };
6170
+ }
6171
+ const hue = serviceHue(provider);
6172
+ return {
6173
+ fill: hslToHex(hue, 45, 88),
6174
+ stroke: hslToHex(hue, 40, 55)
6175
+ };
6176
+ }
6177
+ /** Colours and metrics, kept in one place so both themes stay in step. */
6178
+ const TOKENS = {
6179
+ ink: "#1b1f24",
6180
+ muted: "#57606a",
6181
+ canvas: "#ffffff",
6182
+ containerFill: "#eef4ff",
6183
+ containerStroke: "#9cc0f5",
6184
+ resourceFill: "#f7f8fa",
6185
+ resourceStroke: "#c7ccd4",
6186
+ traffic: "#0969da",
6187
+ policy: "#8250df",
6188
+ labelBackground: "#ffffff"
6189
+ };
6190
+ /**
6191
+ * Escape text for XML content and attributes.
6192
+ *
6193
+ * @param text - the string to escape.
6194
+ * @returns the same text with the five XML metacharacters replaced.
6195
+ */
6196
+ function escapeXml(text) {
6197
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&apos;");
6198
+ }
6199
+ /**
6200
+ * Where a connector meets a box's border, on the side facing the other box.
6201
+ *
6202
+ * The connector is drawn as an orthogonal path, so it leaves through a
6203
+ * horizontal edge when the boxes are stacked and through a vertical edge when
6204
+ * they are side by side. Picking the side from the relative position is what
6205
+ * keeps the first and last segment perpendicular to the border it touches —
6206
+ * a line meeting a box at an angle reads as passing behind it.
6207
+ *
6208
+ * @param box - the box whose border point is wanted.
6209
+ * @param towardX - the other box's centre, x.
6210
+ * @param towardY - the other box's centre, y.
6211
+ * @returns the point on the box's border.
6212
+ */
6213
+ function borderPoint(box, towardX, towardY) {
6214
+ const cx = box.x + box.width / 2;
6215
+ const cy = box.y + box.height / 2;
6216
+ const dx = towardX - cx;
6217
+ const dy = towardY - cy;
6218
+ const horizontal = Math.abs(dx) / (box.width / 2 || 1);
6219
+ const vertical = Math.abs(dy) / (box.height / 2 || 1);
6220
+ if (horizontal > vertical) return {
6221
+ x: dx > 0 ? box.x + box.width : box.x,
6222
+ y: cy
6223
+ };
6224
+ return {
6225
+ x: cx,
6226
+ y: dy > 0 ? box.y + box.height : box.y
6227
+ };
6228
+ }
6229
+ /**
6230
+ * Draw one box: its rectangle, then its label.
6231
+ *
6232
+ * A container's label sits in its title band, at the top, left-aligned — the
6233
+ * convention every architecture diagram uses, and what makes a nested box read
6234
+ * as "this region contains the things below it" rather than as a floating card.
6235
+ *
6236
+ * A leaf's label is centred in its box.
6237
+ *
6238
+ * @param box - the placed box.
6239
+ * @param role - how to draw it.
6240
+ * @returns the markup for the box itself, not its children.
6241
+ */
6242
+ function drawBox(box, role) {
6243
+ const isContainer = role === "container";
6244
+ const { fill, stroke } = boxColours(role, box.provider, box.depth);
6245
+ const radius = isContainer ? 6 : 4;
6246
+ const weight = isContainer ? 600 : 400;
6247
+ const dash = box.existing ? " stroke-dasharray=\"7 5\"" : "";
6248
+ const shape = `<rect x="${box.x}" y="${box.y}" width="${box.width}" height="${box.height}" rx="${radius}" fill="${fill}" stroke="${stroke}" stroke-width="1.5"${dash}/>`;
6249
+ if (isContainer) {
6250
+ const textX = box.x + 16;
6251
+ let textY = box.y + 18;
6252
+ let markup$1 = shape + `<text x="${textX}" y="${textY}" font-size="13" font-weight="${weight}" fill="${TOKENS.ink}">${escapeXml(box.label)}</text>`;
6253
+ for (const line of box.detail) {
6254
+ textY += DETAIL_LINE;
6255
+ markup$1 += `<text x="${textX}" y="${textY}" font-size="10" fill="${TOKENS.muted}" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">${escapeXml(line)}</text>`;
6256
+ }
6257
+ return markup$1;
6258
+ }
6259
+ const centreX = box.x + box.width / 2;
6260
+ const lines = box.detail.length;
6261
+ const blockHeight = lines * DETAIL_LINE;
6262
+ const labelY = box.y + box.height / 2 + 4 - blockHeight / 2;
6263
+ let markup = shape + `<text x="${centreX}" y="${labelY}" font-size="12" text-anchor="middle" font-weight="${weight}" fill="${TOKENS.ink}">${escapeXml(labelWithFigure(box.label, box.figure))}</text>`;
6264
+ const leftX = box.x + PADDING;
6265
+ for (const [index, line] of box.detail.entries()) {
6266
+ const y = labelY + DETAIL_LINE * (index + 1);
6267
+ markup += `<text x="${leftX}" y="${y}" font-size="10" fill="${TOKENS.muted}" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">${escapeXml(line)}</text>`;
6268
+ }
6269
+ return markup;
6270
+ }
6271
+ /** The vertical distance between detail lines, matching the layout's own. */
6272
+ const DETAIL_LINE = 17;
6273
+ /** The padding a leaf's left-aligned rules start from. */
6274
+ const PADDING = 16;
6275
+ /**
6276
+ * The points an orthogonal connector turns at.
6277
+ *
6278
+ * ## Why orthogonal and not straight
6279
+ *
6280
+ * A straight line between two boxes passes over whatever lies between them —
6281
+ * and in a packed box tree, that is the sibling boxes. Measured on a real
6282
+ * account: every one of twenty-seven connectors crossed a box that was not one
6283
+ * of its endpoints. An orthogonal path with one bend in the gap between rows
6284
+ * stays in the empty corridor the layout already leaves there.
6285
+ *
6286
+ * The path leaves along the axis its border point faces, turns once in the
6287
+ * corridor, and arrives along the same axis. Two segments per bend, so the
6288
+ * route is always three or four points and never doubles back.
6289
+ *
6290
+ * @param from - the source box.
6291
+ * @param to - the target box.
6292
+ * @returns the polyline's points, source first.
6293
+ */
6294
+ function routePoints(from, to) {
6295
+ const fromCx = from.x + from.width / 2;
6296
+ const fromCy = from.y + from.height / 2;
6297
+ const toCx = to.x + to.width / 2;
6298
+ const toCy = to.y + to.height / 2;
6299
+ const start = borderPoint(from, toCx, toCy);
6300
+ const end = borderPoint(to, fromCx, fromCy);
6301
+ const startVertical = start.x === fromCx;
6302
+ const endVertical = end.x === toCx;
6303
+ if (startVertical && endVertical) {
6304
+ const midY = (start.y + end.y) / 2;
6305
+ return [
6306
+ start,
6307
+ {
6308
+ x: start.x,
6309
+ y: midY
6310
+ },
6311
+ {
6312
+ x: end.x,
6313
+ y: midY
6314
+ },
6315
+ end
6316
+ ];
6317
+ }
6318
+ if (!startVertical && !endVertical) {
6319
+ const midX = (start.x + end.x) / 2;
6320
+ return [
6321
+ start,
6322
+ {
6323
+ x: midX,
6324
+ y: start.y
6325
+ },
6326
+ {
6327
+ x: midX,
6328
+ y: end.y
6329
+ },
6330
+ end
6331
+ ];
6332
+ }
6333
+ return [
6334
+ start,
6335
+ {
6336
+ x: end.x,
6337
+ y: start.y
6338
+ },
6339
+ end
6340
+ ];
6341
+ }
6342
+ /**
6343
+ * Draw one connector as an orthogonal path, with its label on the route.
6344
+ *
6345
+ * The two kinds are told apart by weight and dash: a traffic flow is solid and
6346
+ * heavier — it is where requests go — while a policy rule is dashed, because
6347
+ * nothing travels along it. Colour alone would not survive a black-and-white
6348
+ * print, and the difference matters enough to be readable there.
6349
+ *
6350
+ * @param edge - the connector.
6351
+ * @param from - the box it leaves.
6352
+ * @param to - the box it arrives at.
6353
+ * @returns the markup.
6354
+ */
6355
+ function drawEdge(edge, from, to) {
6356
+ const points = routePoints(from, to);
6357
+ const path = points.map((point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`).join(" ");
6358
+ const traffic = edge.kind === "traffic";
6359
+ const stroke = traffic ? TOKENS.traffic : TOKENS.policy;
6360
+ const width = traffic ? 2 : 1.2;
6361
+ const dash = traffic ? "" : ` stroke-dasharray="5 4"`;
6362
+ const marker = traffic ? "arrowTraffic" : "arrowPolicy";
6363
+ const line = `<path d="${path}" fill="none" stroke="${stroke}" stroke-width="${width}"${dash} marker-end="url(#${marker})"/>`;
6364
+ if (edge.label === "") return line;
6365
+ const middle = points.length >= 4 ? {
6366
+ x: (points[1].x + points[2].x) / 2,
6367
+ y: (points[1].y + points[2].y) / 2
6368
+ } : {
6369
+ x: (points[0].x + points.at(-1).x) / 2,
6370
+ y: (points[0].y + points.at(-1).y) / 2
6371
+ };
6372
+ const width_ = edge.label.length * 7 + 8;
6373
+ const plaque = `<rect x="${middle.x - width_ / 2}" y="${middle.y - 9}" width="${width_}" height="18" rx="3" fill="${TOKENS.labelBackground}" fill-opacity="0.92"/>`;
6374
+ const text = `<text x="${middle.x}" y="${middle.y + 4}" font-size="11" text-anchor="middle" fill="${traffic ? TOKENS.ink : TOKENS.muted}" font-weight="${traffic ? 600 : 400}">${escapeXml(edge.label)}</text>`;
6375
+ return line + plaque + text;
6376
+ }
6377
+ /**
6378
+ * Render the diagram.
6379
+ *
6380
+ * The SVG declares `width` and `height` from the layout, not only a `viewBox`.
6381
+ * Without them a browser treats the file as a replaced element with no size and
6382
+ * lays it out at the CSS default of 300×150, scaling everything into that box —
6383
+ * which draws a readable diagram at about one pixel.
6384
+ *
6385
+ * @param diagram - the placed boxes and connectors.
6386
+ * @returns the SVG document, with no XML declaration so it embeds in HTML.
6387
+ */
6388
+ function renderDiagram(diagram) {
6389
+ const byId = new Map(diagram.boxes.map((box) => [box.id, box]));
6390
+ const parts = [];
6391
+ parts.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${diagram.width}" height="${diagram.height}" viewBox="0 0 ${diagram.width} ${diagram.height}" font-family="ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif">`);
6392
+ parts.push(`<defs><marker id="arrowTraffic" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="${TOKENS.traffic}"/></marker><marker id="arrowPolicy" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="${TOKENS.policy}"/></marker></defs>`);
6393
+ parts.push(`<rect width="${diagram.width}" height="${diagram.height}" fill="${TOKENS.canvas}"/>`);
6394
+ for (const box of diagram.boxes) parts.push(drawBox(box, diagram.roles.get(box.id) ?? "resource"));
6395
+ for (const edge of diagram.edges) {
6396
+ const from = byId.get(edge.from);
6397
+ const to = byId.get(edge.to);
6398
+ if (from === void 0 || to === void 0) continue;
6399
+ parts.push(drawEdge(edge, from, to));
6400
+ }
6401
+ parts.push("</svg>");
6402
+ return parts.join("");
6403
+ }
6404
+
6405
+ //#endregion
6406
+ //#region src/existing-topology.ts
6407
+ /**
5827
6408
  * Every scalar the properties contain, keyed by its dotted path.
5828
6409
  *
5829
6410
  * Nested objects and arrays are flattened because the inventory nests ids
@@ -5880,681 +6461,1082 @@ function isJsonEncoded(text) {
5880
6461
  const first = text.trimStart()[0];
5881
6462
  return first === "[" || first === "{";
5882
6463
  }
5883
- /** The kinds a box can be drawn inside, and how specific each is. */
5884
- const LOCATION_KINDS = [{
5885
- nouns: ["vpc"],
5886
- rank: 1
5887
- }, {
5888
- nouns: ["subnet", "network"],
5889
- rank: 2
5890
- }];
5891
- /**
5892
- * How specific a location an attribute names, 0 when it names none.
5893
- *
5894
- * The tail of the path is what counts: `vnic.vpcId` and `metadata.vpcId` both
5895
- * end in a noun describing the container. Everything before the last dot is the
5896
- * service's own nesting and says nothing about which container this is.
5897
- *
5898
- * The `id`/`uid`/`uuid` suffix is stripped rather than required to be present,
5899
- * because the provider writes all three (`subnet_id`, `subnetId`,
5900
- * `virsubnet_id`) and a rule that demanded one spelling would miss the others.
5901
- * A plural suffix is stripped too: `elb_virsubnet_ids` holds several subnets,
5902
- * and whether the attribute holds one id or a list does not change what it
5903
- * names. Suffix matching, not equality, is what makes `virsubnet` and
5904
- * `subnetwork` land on the same noun.
6464
+
6465
+ //#endregion
6466
+ //#region src/account-view.ts
6467
+ /**
6468
+ * Read a string-valued property, unwrapping the JSON encoding RMS uses.
6469
+ *
6470
+ * The inventory ships some ids as `"[\"…\"]"` — a JSON array inside a string —
6471
+ * and a plain comparison against an id never matches. One unwrap is enough:
6472
+ * the provider does not double-encode.
6473
+ *
6474
+ * @param value - the property value.
6475
+ * @returns the id it holds, or `undefined`.
6476
+ */
6477
+ function idOf$1(value) {
6478
+ if (typeof value === "string") {
6479
+ const trimmed = value.trim();
6480
+ if (trimmed.startsWith("[")) try {
6481
+ const parsed = JSON.parse(trimmed);
6482
+ if (Array.isArray(parsed) && typeof parsed[0] === "string") return parsed[0];
6483
+ } catch {
6484
+ return trimmed;
6485
+ }
6486
+ return trimmed === "" ? void 0 : trimmed;
6487
+ }
6488
+ if (Array.isArray(value) && typeof value[0] === "string") return value[0];
6489
+ return void 0;
6490
+ }
6491
+ /**
6492
+ * The attribute names that mean "this is drawn inside that".
6493
+ *
6494
+ * Two kinds, and both are nesting:
6495
+ *
6496
+ * - **Placement** — `vpc_id`, `subnet_id`, `networkId`. Where a thing lives.
6497
+ * - **Attachment** — `serverID`, `host_id`, `clusterUID`, and an EIP's
6498
+ * `associateInstanceId`. What a thing is part of.
6499
+ *
6500
+ * Both answer the same question for the reader ("what does this belong to"),
6501
+ * and both are drawn the same way. Keeping one table rather than two is what
6502
+ * lets a service this build has never seen nest correctly: it only has to name
6503
+ * the relationship the way the others do.
6504
+ *
6505
+ * Ranked: a more specific container wins. A server names both its VPC and its
6506
+ * subnet, and the subnet is where it lives.
6507
+ *
6508
+ * ## Every entry points from the member to its container
6509
+ *
6510
+ * The direction is part of the meaning, not a detail. A balancer lists its EIPs
6511
+ * in `eips[].eip_id`, which reads like a container holding a member — but the
6512
+ * EIP is the one that names the balancer, through `associateInstanceId`, and
6513
+ * only the EIP's property says where it belongs. Reading the balancer's list as
6514
+ * placement put the balancer inside its own address.
6515
+ *
6516
+ * So an attribute belongs here only when it says "I am part of that". A
6517
+ * container that lists its members does not.
6518
+ */
6519
+ const NESTS_IN = [
6520
+ {
6521
+ match: /vpc[._]?id$/i,
6522
+ rank: 1
6523
+ },
6524
+ {
6525
+ match: /(subnet|network)[._]?(id|uid)s?$/i,
6526
+ rank: 2
6527
+ },
6528
+ {
6529
+ match: /^(vnic\.)?deviceId$/i,
6530
+ rank: 3
6531
+ },
6532
+ {
6533
+ match: /(^|\.)(server|host)[._]?id$/i,
6534
+ rank: 4
6535
+ },
6536
+ {
6537
+ match: /cluster(uid|[._]?id)$/i,
6538
+ rank: 4
6539
+ },
6540
+ {
6541
+ match: /^associateInstanceId$/i,
6542
+ rank: 4
6543
+ },
6544
+ {
6545
+ match: /^loadbalancers?[._]id$/i,
6546
+ rank: 4
6547
+ }
6548
+ ];
6549
+ /**
6550
+ * The attribute names that name a security group guarding this resource.
6551
+ *
6552
+ * These do NOT nest and do NOT become edges: a group is a property of the thing
6553
+ * it guards, so it is drawn as text inside that thing's box.
6554
+ */
6555
+ const GUARDS_BY = [/security[._]?group[._]?id$/i, /secgroup$/i];
6556
+ /**
6557
+ * How many resources must name a container before it counts as one.
6558
+ *
6559
+ * Two is enough to tell "everything inside me points here" from "one thing
6560
+ * mentioned me". A NAT gateway is named by the single EIP attached to it and is
6561
+ * still a thing placed inside a VPC; a VPC is named by every subnet, server and
6562
+ * load balancer it holds and is a root.
6563
+ */
6564
+ const CONTAINER_REFERENTS = 2;
6565
+ /**
6566
+ * How specifically an attribute names a container, 0 for none.
5905
6567
  *
5906
6568
  * @param attribute - a dotted property path.
5907
- * @returns the rank of the location it names, or 0 for a plain association.
6569
+ * @returns the rank, higher being more specific.
5908
6570
  */
5909
- function locationRank(attribute) {
5910
- const tail = attribute.split(".").pop() ?? attribute;
5911
- const noun = tail.replace(/(_?ids|_?id|_?uids|_?uid|uuid)$/i, "").replace(/[^a-z]/gi, "").toLowerCase();
5912
- for (const { nouns, rank } of LOCATION_KINDS) for (const word of nouns) if (noun.endsWith(word)) return rank;
6571
+ function nestRank(attribute) {
6572
+ if (attribute === "description" || attribute.startsWith("description.")) return 0;
6573
+ for (const { match, rank } of NESTS_IN) if (match.test(attribute)) return rank;
5913
6574
  return 0;
5914
6575
  }
5915
6576
  /**
5916
- * Derive the picture from what the inventory reported.
6577
+ * Whether an attribute names a security group.
5917
6578
  *
5918
- * @param resources - every resource the inventory returned.
5919
- * @returns nodes, edges, and the nesting derived from both.
6579
+ * @param attribute - a dotted property path.
6580
+ * @returns whether it does.
5920
6581
  */
5921
- function deriveInventoryTopology(resources) {
5922
- const byId = new Map();
5923
- const duplicates = [];
5924
- for (const resource of resources) {
5925
- if (byId.has(resource.id)) {
5926
- if (!duplicates.includes(resource.id)) duplicates.push(resource.id);
5927
- continue;
5928
- }
5929
- byId.set(resource.id, resource);
5930
- }
5931
- const flat = new Map();
5932
- for (const [id, resource] of byId) flat.set(id, flattenProperties(resource.properties ?? {}));
5933
- const raw = [];
5934
- const seen = new Set();
5935
- for (const [id, properties] of flat) for (const [attribute, value] of properties) {
5936
- if (value === id) continue;
5937
- if (!byId.has(value)) continue;
5938
- const key = `${id}\u0000${value}`;
5939
- if (seen.has(key)) continue;
5940
- seen.add(key);
5941
- raw.push({
5942
- from: id,
5943
- to: value,
5944
- attribute,
5945
- location: locationRank(attribute)
5946
- });
5947
- }
5948
- const edges = raw.map((entry) => ({
5949
- from: entry.from,
5950
- to: entry.to,
5951
- attribute: entry.attribute,
5952
- contains: entry.location > 0
5953
- }));
6582
+ function isGuardAttribute(attribute) {
6583
+ return GUARDS_BY.some((match) => match.test(attribute));
6584
+ }
6585
+ /**
6586
+ * Read the placement and attachment layer.
6587
+ *
6588
+ * @param resources - the account's resources.
6589
+ * @returns resource id → the id of its container.
6590
+ */
6591
+ function containment(resources) {
6592
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
5954
6593
  const parentOf = new Map();
5955
- const parentRank = new Map();
5956
- for (const entry of raw) {
5957
- if (entry.location === 0) continue;
5958
- if (entry.location > (parentRank.get(entry.from) ?? 0)) {
5959
- parentOf.set(entry.from, entry.to);
5960
- parentRank.set(entry.from, entry.location);
5961
- }
5962
- }
5963
- for (const [child, parent] of [...parentOf]) {
5964
- const seenChain = new Set([child]);
5965
- let cursor = parent;
6594
+ const rankOf = new Map();
6595
+ /** Record a placement, keeping the most specific one. */
6596
+ const place$1 = (child, parent, rank) => {
6597
+ if (child === parent || !byId.has(parent)) return;
6598
+ if (rank <= (rankOf.get(child) ?? 0)) return;
6599
+ parentOf.set(child, parent);
6600
+ rankOf.set(child, rank);
6601
+ };
6602
+ for (const resource of resources) for (const [attribute, value] of flattenProperties(resource.properties ?? {})) {
6603
+ const rank = nestRank(attribute);
6604
+ if (rank === 0) continue;
6605
+ const target = idOf$1(value);
6606
+ if (target === void 0) continue;
6607
+ place$1(resource.id, target, rank);
6608
+ }
6609
+ const namedBy = new Map();
6610
+ for (const resource of resources) for (const [attribute, value] of flattenProperties(resource.properties ?? {})) {
6611
+ const rank = nestRank(attribute);
6612
+ if (rank === 0) continue;
6613
+ const target = idOf$1(value);
6614
+ if (target === void 0 || target === resource.id) continue;
6615
+ if (!byId.has(target)) continue;
6616
+ const listed = namedBy.get(target) ?? [];
6617
+ if (listed.some((entry) => entry.from === resource.id)) continue;
6618
+ namedBy.set(target, [...listed, {
6619
+ from: resource.id,
6620
+ rank
6621
+ }]);
6622
+ }
6623
+ for (const [named, referrers] of namedBy) {
6624
+ if (parentOf.has(named)) continue;
6625
+ if (referrers.length >= CONTAINER_REFERENTS) continue;
6626
+ const inherited = inheritedContainer(byId.get(named), resources, parentOf, namedBy);
6627
+ if (inherited === void 0 || inherited === named) continue;
6628
+ if (holdsTransitively(named, inherited, parentOf)) continue;
6629
+ const rank = referrers.reduce((best, referrer) => Math.max(best, referrer.rank), 0);
6630
+ place$1(named, inherited, rank);
6631
+ }
6632
+ for (const [child] of [...parentOf]) {
6633
+ const seen = new Set([child]);
6634
+ let cursor = parentOf.get(child);
5966
6635
  while (cursor !== void 0) {
5967
- if (seenChain.has(cursor)) {
6636
+ if (seen.has(cursor)) {
5968
6637
  parentOf.delete(child);
5969
6638
  break;
5970
6639
  }
5971
- seenChain.add(cursor);
6640
+ seen.add(cursor);
5972
6641
  cursor = parentOf.get(cursor);
5973
6642
  }
5974
6643
  }
5975
- const childrenOf = new Map();
5976
- for (const [child, parent] of parentOf) {
5977
- const list = childrenOf.get(parent) ?? [];
5978
- list.push(child);
5979
- childrenOf.set(parent, list);
5980
- }
5981
- const factsOf = (resource) => {
5982
- const properties = flat.get(resource.id) ?? new Map();
5983
- const label = resource.name ?? "";
5984
- const facts = [];
5985
- for (const key of LABEL_ATTRIBUTES) {
5986
- const value = properties.get(key);
5987
- if (value === void 0 || value === "" || value === label) continue;
5988
- if (facts.some((fact) => fact.value === value)) continue;
5989
- facts.push({
5990
- key,
5991
- value
5992
- });
5993
- }
5994
- return facts;
5995
- };
5996
- const ancestorsOf = (id) => {
5997
- const chain = [];
5998
- const seenChain = new Set([id]);
5999
- let cursor = parentOf.get(id);
6000
- while (cursor !== void 0 && !seenChain.has(cursor)) {
6001
- seenChain.add(cursor);
6002
- chain.push(cursor);
6003
- cursor = parentOf.get(cursor);
6004
- }
6005
- return chain;
6006
- };
6007
- const build = (id) => {
6008
- const resource = byId.get(id);
6009
- return {
6010
- id,
6011
- provider: resource.provider,
6012
- type: resource.type,
6013
- label: resource.name !== void 0 && resource.name !== "" ? resource.name : `${resource.provider}/${resource.type} ${id.slice(0, 8)}`,
6014
- facts: factsOf(resource),
6015
- parent: parentOf.get(id),
6016
- ancestors: ancestorsOf(id),
6017
- children: (childrenOf.get(id) ?? []).map(build)
6018
- };
6019
- };
6020
- const rootIds = [...byId.keys()].filter((id) => !parentOf.has(id));
6021
- const depth = (id) => ancestorsOf(id).length;
6022
- rootIds.sort((a, b) => {
6023
- const da = depth(a), db = depth(b);
6024
- if (da !== db) return db - da;
6025
- return (byId.get(a).name ?? a).localeCompare(byId.get(b).name ?? b);
6026
- });
6027
- return {
6028
- roots: rootIds.map(build),
6029
- nodes: [...byId.keys()].map(build),
6030
- edges,
6031
- duplicates
6032
- };
6644
+ return parentOf;
6033
6645
  }
6034
-
6035
- //#endregion
6036
- //#region src/d2-engine.ts
6037
6646
  /**
6038
- * The D2 themes, light and dark.
6647
+ * Every container a resource's properties name, most specific first.
6039
6648
  *
6040
- * Theme 5 rather than 0 for light. Theme 0 collapses its accent ramps into one
6041
- * blue-grey: `B`, `AA` and `AB` all resolve to shades of `#EDF0FD`/`#F7F8FE`
6042
- * there, so a diagram styled with three kinds of box draws three boxes in one
6043
- * colour. Theme 5 keeps them apart — blue, violet, pink (measured against the
6044
- * rendered palette, not the docs).
6045
- *
6046
- * 201 rather than 200 for dark, for the same reason and by the same measurement:
6047
- * 200 collapses the same way (`B2` and `AA2` both `#CBA6f7`), 201 keeps a
6048
- * distinguishable blue/violet/teal.
6049
- *
6050
- * Both ids must be given. With no `dark-theme-id` D2 emits NO dark palette at
6051
- * all, and every class would resolve in light colours on a dark ground.
6052
- */
6053
- const LIGHT_THEME_ID = 5;
6054
- const DARK_THEME_ID = 201;
6055
- /**
6056
- * The `vars` block every generated diagram opens with.
6057
- *
6058
- * The theme ids are written into the diagram rather than passed to `render`, so
6059
- * the generated source is the whole description of what was drawn — a reader
6060
- * feeding it to the D2 CLI gets the same colours.
6061
- *
6062
- * @returns the opening lines of a D2 document.
6063
- */
6064
- function themePreamble() {
6065
- return [
6066
- "direction: down",
6067
- "",
6068
- "vars: {",
6069
- " d2-config: {",
6070
- ` theme-id: ${LIGHT_THEME_ID}`,
6071
- ` dark-theme-id: ${DARK_THEME_ID}`,
6072
- " }",
6073
- "}",
6074
- ""
6075
- ];
6076
- }
6077
- /**
6078
- * Compile D2 source and render it to an SVG.
6649
+ * A resource may state more than one placement, and they are all true: an EIP
6650
+ * attached to a NAT gateway names the gateway (it is drawn inside it) AND the
6651
+ * VPC it sits in. Only one of them can be the box it is drawn in, but the
6652
+ * others still say where it lives — which is what a resource that states no
6653
+ * placement of its own can borrow.
6079
6654
  *
6080
- * @param source - the D2 source text.
6081
- * @returns the SVG, with no XML declaration.
6082
- * @throws when the source does not compile. That is a defect in the generator
6083
- * rather than in the user's configuration — the generator produced the text —
6084
- * so the caller names the generated fragment in its message.
6655
+ * @param resource - the resource.
6656
+ * @returns the container ids, ordered by how specific the attribute was.
6085
6657
  */
6086
- async function renderD2(source$1) {
6087
- const d2 = new D2();
6088
- try {
6089
- const compiled$1 = await d2.compile(source$1, { options: { layout: "elk" } });
6090
- const svg = await d2.render(compiled$1.diagram, {
6091
- ...compiled$1.renderOptions,
6092
- pad: 20,
6093
- noXMLTag: true
6658
+ function allContainers(resource) {
6659
+ const found = [];
6660
+ for (const [attribute, value] of flattenProperties(resource.properties ?? {})) {
6661
+ const rank = nestRank(attribute);
6662
+ if (rank === 0) continue;
6663
+ const target = idOf$1(value);
6664
+ if (target === void 0 || target === resource.id) continue;
6665
+ found.push({
6666
+ id: target,
6667
+ rank
6094
6668
  });
6095
- return withIntrinsicSize(svg);
6096
- } finally {
6097
- await closeD2(d2);
6098
6669
  }
6670
+ return found.sort((a, b) => b.rank - a.rank);
6099
6671
  }
6100
6672
  /**
6101
- * Give the outer `<svg>` an intrinsic size.
6673
+ * The container a resource is in, following the naming chain when needed.
6102
6674
  *
6103
- * ## Why this is not cosmetic
6675
+ * ## Why one hop is not enough
6104
6676
  *
6105
- * D2 emits the outer element with a `viewBox` and no `width`/`height`. In CSS,
6106
- * an SVG with no intrinsic dimensions is a replaced element with no size, and
6107
- * the browser falls back to 300×150 — then scales the whole `viewBox` into that
6108
- * box. A picture of a real account is around 5000×1800, so the scale factor is
6109
- * roughly 0.06 and a 16px label is drawn at about 1px: the diagram renders, and
6110
- * is unreadable at any preview size.
6677
+ * A NAT gateway reports only its spec. The EIP attached to it knows two things:
6678
+ * that it belongs to the gateway, and that the gateway sits in a VPC. The
6679
+ * gateway's placement is therefore one link away — it is in whatever VPC the
6680
+ * thing that names it names.
6111
6681
  *
6112
- * That is not a layout problem to tune — the file is correct, and it has no
6113
- * size of its own. Declaring one gives the browser something to lay out at its
6114
- * natural dimensions; whatever container shows it can then scale a legible
6115
- * image down rather than a legible image already scaled to nothing.
6116
- *
6117
- * The values come from the viewBox, which is what D2 computed from the content,
6118
- * so nothing is guessed. A viewBox D2 did not emit is left alone: a wrong size
6119
- * would be worse than the default, and the caller's render would be reported
6120
- * as broken for a reason that is not theirs.
6121
- *
6122
- * @param svg - the rendered SVG.
6123
- * @returns the same SVG with `width` and `height` on the outer element.
6682
+ * @param resource - the resource whose container is wanted.
6683
+ * @param resources - everything in the account.
6684
+ * @param parentOf - the placement resolved so far.
6685
+ * @param namedBy - which resources name each other.
6686
+ * @returns the container id, or `undefined` when the chain leads nowhere.
6124
6687
  */
6125
- function withIntrinsicSize(svg) {
6126
- const outer = /<svg\b[^>]*>/.exec(svg);
6127
- if (outer === null) return svg;
6128
- const tag = outer[0];
6129
- if (/\swidth="/.test(tag) || /\sheight="/.test(tag)) return svg;
6130
- const viewBox = /\sviewBox="([^"]*)"/.exec(tag);
6131
- const parts = viewBox?.[1]?.trim().split(/[\s,]+/) ?? [];
6132
- if (parts.length !== 4) return svg;
6133
- const width = Number(parts[2]);
6134
- const height = Number(parts[3]);
6135
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return svg;
6136
- const sized = tag.replace(/^<svg\b/, `<svg width="${width}" height="${height}"`);
6137
- return sized + svg.slice(outer.index + tag.length);
6688
+ function inheritedContainer(resource, resources, parentOf, namedBy) {
6689
+ const byId = new Map(resources.map((entry) => [entry.id, entry]));
6690
+ const seen = new Set([resource.id]);
6691
+ const queue = (namedBy.get(resource.id) ?? []).map((entry) => entry.from);
6692
+ while (queue.length > 0) {
6693
+ const id = queue.shift();
6694
+ if (seen.has(id)) continue;
6695
+ seen.add(id);
6696
+ const referrer = byId.get(id);
6697
+ if (referrer === void 0) continue;
6698
+ const placed = parentOf.get(id);
6699
+ if (placed !== void 0 && placed !== resource.id) return placed;
6700
+ const candidate = allContainers(referrer).find((entry) => entry.id !== resource.id);
6701
+ if (candidate !== void 0) return candidate.id;
6702
+ queue.push(...(namedBy.get(id) ?? []).map((entry) => entry.from));
6703
+ }
6704
+ return void 0;
6138
6705
  }
6139
6706
  /**
6140
- * Terminate the renderer's worker.
6707
+ * Whether `container` already sits inside `resource`.
6141
6708
  *
6142
- * `D2` exposes no disposal API, so the thread is terminated directly. The
6143
- * failure is swallowed: a render that already produced its SVG must not be
6144
- * reported as failed because the cleanup raced the worker's own shutdown.
6709
+ * Used to refuse a placement that would invert the nesting: a VPC named by an
6710
+ * EIP whose gateway the VPC also holds must not then be placed inside that
6711
+ * gateway. The walk follows the placement chain upwards, and stops at a cycle
6712
+ * rather than looping.
6145
6713
  *
6146
- * @param d2 - the renderer whose worker to stop.
6714
+ * @param resource - the resource that would be the new container.
6715
+ * @param container - the box that would be placed inside it.
6716
+ * @param parentOf - the placement resolved so far.
6717
+ * @returns whether `container` is already below `resource`.
6147
6718
  */
6148
- async function closeD2(d2) {
6149
- const worker = d2.worker;
6150
- try {
6151
- await worker?.terminate?.();
6152
- } catch {}
6719
+ function holdsTransitively(resource, container, parentOf) {
6720
+ const seen = new Set([container]);
6721
+ let cursor = parentOf.get(container);
6722
+ while (cursor !== void 0) {
6723
+ if (cursor === resource) return true;
6724
+ if (seen.has(cursor)) return false;
6725
+ seen.add(cursor);
6726
+ cursor = parentOf.get(cursor);
6727
+ }
6728
+ return false;
6153
6729
  }
6154
6730
  /**
6155
- * Quote a string for a D2 label.
6731
+ * Read which security groups guard each resource.
6156
6732
  *
6157
- * @param text - the label.
6158
- * @returns the text inside double quotes, with its own quotes escaped.
6733
+ * @param resources - the account's resources.
6734
+ * @returns resource id → the group NAMES, sorted so two runs agree.
6159
6735
  */
6160
- function quote(text) {
6161
- return `"${text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`;
6736
+ function guards(resources) {
6737
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
6738
+ const found = new Map();
6739
+ for (const resource of resources) for (const [attribute, value] of flattenProperties(resource.properties ?? {})) {
6740
+ if (!isGuardAttribute(attribute)) continue;
6741
+ const target = idOf$1(value);
6742
+ if (target === void 0 || target === resource.id) continue;
6743
+ const group = byId.get(target);
6744
+ if (group === void 0) continue;
6745
+ const names = found.get(resource.id) ?? [];
6746
+ if (!names.includes(group.name ?? group.id)) names.push(group.name ?? group.id);
6747
+ found.set(resource.id, names);
6748
+ }
6749
+ for (const names of found.values()) names.sort();
6750
+ return found;
6162
6751
  }
6163
6752
  /**
6164
- * The D2 identifier for an address or cloud id.
6753
+ * The resources that use each security group.
6165
6754
  *
6166
- * A `.` in a D2 key means "member of the block before it", so an unreplaced one
6167
- * nests the node inside a box named after the part before the dot — inventing a
6168
- * container that does not exist. Every character D2 reserves is replaced by `_`
6169
- * for the same reason.
6755
+ * ## Why this is worth showing
6170
6756
  *
6171
- * A collision is possible in principle (`a_b.c` and `a.b_c` both map to
6172
- * `a_b_c`). It cannot occur inside one provider namespace, where the separator
6173
- * between resource types and names is always the same `.`, but callers draw
6174
- * from a map keyed by the original id, so a collision would drop an edge rather
6175
- * than misplace it.
6757
+ * A group's rules say what it admits; its users say whether it matters. On a
6758
+ * live account 13 groups exist and only 6 are used by anything — and one of
6759
+ * those is used by three resources. A reader who has to open each group to find
6760
+ * out whether it is live cannot tell a housekeeping leftover from the group
6761
+ * guarding the database.
6176
6762
  *
6177
- * @param address - a terraform `type.name` address or a cloud resource id.
6178
- * @returns an identifier D2 accepts.
6763
+ * @param resources - the account's resources.
6764
+ * @returns group id → the ids of the resources that name it.
6179
6765
  */
6180
- function d2Id(address) {
6181
- return address.replaceAll(".", "_").replaceAll(/[^A-Za-z0-9_]/g, "_");
6766
+ function groupUsers(resources) {
6767
+ const users = new Map();
6768
+ for (const resource of resources) for (const [attribute, value] of flattenProperties(resource.properties ?? {})) {
6769
+ if (!isGuardAttribute(attribute)) continue;
6770
+ const target = idOf$1(value);
6771
+ if (target === void 0 || target === resource.id) continue;
6772
+ const groupId = target;
6773
+ if (!resources.some((entry) => entry.id === groupId)) continue;
6774
+ const listed = users.get(groupId) ?? [];
6775
+ if (!listed.includes(resource.id)) listed.push(resource.id);
6776
+ users.set(groupId, listed);
6777
+ }
6778
+ return users;
6182
6779
  }
6183
-
6184
- //#endregion
6185
- //#region src/d2-inventory.ts
6186
6780
  /**
6187
- * The D2 palette ramps, one hue each with three lightness steps.
6781
+ * Read the policy edges between security groups.
6782
+ *
6783
+ * ## What makes this an edge
6784
+ *
6785
+ * A rule on group A whose `remote_group_id` is group B says: traffic from
6786
+ * anything carrying B may reach anything carrying A, on this port. That is a
6787
+ * statement about reachability between two groups, with a direction and a port
6788
+ * — the only relationship in the account that has all three.
6188
6789
  *
6189
- * Four ramps rather than a per-provider table: `hash(provider) % 4` picks one,
6190
- * so a provider not named anywhere still gets a stable, distinct colour.
6790
+ * Two rules that say the same thing (a group's rules are often duplicated by
6791
+ * the provider) are collapsed: a reader comparing the picture to the console
6792
+ * should not have to work out which arrow is which duplicate.
6793
+ *
6794
+ * @param resources - the account's resources.
6795
+ * @returns the policy edges, sorted for a stable picture.
6191
6796
  */
6192
- const PROVIDER_RAMPS = [
6193
- [
6194
- "fill-B5, stroke-B3",
6195
- "fill-B6, stroke-B4",
6196
- "fill-B4, stroke-B2"
6197
- ],
6198
- [
6199
- "fill-AA4, stroke-AA2",
6200
- "fill-AA5, stroke-AA4",
6201
- "fill-AA3, stroke-AA2"
6202
- ],
6203
- [
6204
- "fill-AB5, stroke-AB4",
6205
- "fill-AB4, stroke-AB4",
6206
- "fill-AB6, stroke-AB5"
6207
- ],
6208
- [
6209
- "fill-N7, stroke-N5",
6210
- "fill-N6, stroke-N4",
6211
- "fill-N5, stroke-N3"
6212
- ]
6213
- ];
6214
- /** The class an arrow into a resource carries: "traffic flows here". */
6215
- const CONNECTION_CLASS$1 = "stroke-AB3";
6797
+ function policies(resources) {
6798
+ const groupNames = new Map(resources.filter((resource) => resource.type === "securityGroups").map((resource) => [resource.id, resource.name ?? resource.id]));
6799
+ const edges = [];
6800
+ const seen = new Set();
6801
+ for (const resource of resources) {
6802
+ if (resource.type !== "securityGroups") continue;
6803
+ const rules = resource.properties?.["security_group_rules"];
6804
+ if (!Array.isArray(rules)) continue;
6805
+ for (const rule of rules) {
6806
+ if (rule === null || typeof rule !== "object") continue;
6807
+ const fields = rule;
6808
+ const remote = idOf$1(fields["remote_group_id"]);
6809
+ if (remote === void 0 || remote === resource.id) continue;
6810
+ if (!groupNames.has(remote)) continue;
6811
+ const direction = typeof fields["direction"] === "string" ? fields["direction"] : "ingress";
6812
+ const protocol = typeof fields["protocol"] === "string" && fields["protocol"] !== "" ? fields["protocol"] : "any";
6813
+ const low = fields["port_range_min"];
6814
+ const high = fields["port_range_max"];
6815
+ const ports = typeof low === "number" || typeof low === "string" ? `${String(low)}${String(low) === String(high) ? "" : `-${String(high)}`}` : void 0;
6816
+ const key = `${remote}\u0000${resource.id}\u0000${direction}\u0000${protocol}\u0000${ports ?? ""}`;
6817
+ if (seen.has(key)) continue;
6818
+ seen.add(key);
6819
+ edges.push({
6820
+ from: remote,
6821
+ to: resource.id,
6822
+ direction,
6823
+ protocol,
6824
+ ports
6825
+ });
6826
+ }
6827
+ }
6828
+ edges.sort((a, b) => (groupNames.get(a.from) ?? "").localeCompare(groupNames.get(b.from) ?? "") || (groupNames.get(a.to) ?? "").localeCompare(groupNames.get(b.to) ?? ""));
6829
+ return edges;
6830
+ }
6216
6831
  /**
6217
- * How many top-level boxes go in one row of an inventory picture.
6832
+ * Whether a rule says anything a reader would not assume.
6833
+ *
6834
+ * Three shapes are assumed and therefore dropped:
6835
+ *
6836
+ * - a rule admitting the group's own members (`remote_group_id` = itself),
6837
+ * which is the cloud's default for any group;
6838
+ * - an egress rule admitting everything, which nearly every group has;
6839
+ * - an exact duplicate of a rule already kept.
6218
6840
  *
6219
- * Three. Measured on a live 30-resource account: one row (D2's arrangement for
6220
- * unconnected roots) is 9.6:1, five columns is 5.8:1, four is 4.8:1 and three is
6221
- * 3.4:1. Below three the picture grows tall rather than wide, and a wider grid
6222
- * pushes the strip down a level instead of removing it.
6841
+ * @param rule - the provider's rule object.
6842
+ * @param groupId - the id of the group the rule belongs to.
6843
+ * @param nameOf - resolves a group id to its name.
6844
+ * @returns the summary, or `undefined` when the rule says nothing new.
6223
6845
  */
6224
- const GRID_COLUMNS = 3;
6846
+ function summarizeRule(rule, groupId, nameOf) {
6847
+ const direction = typeof rule["direction"] === "string" ? rule["direction"] : "ingress";
6848
+ const protocol = typeof rule["protocol"] === "string" && rule["protocol"] !== "" ? rule["protocol"] : "any";
6849
+ const low = rule["port_range_min"];
6850
+ const high = rule["port_range_max"];
6851
+ const ports = typeof low === "number" || typeof low === "string" ? String(low) === String(high) ? String(low) : `${String(low)}-${String(high)}` : "all";
6852
+ const remoteGroup = idOf$1(rule["remote_group_id"]);
6853
+ const remoteCidr = typeof rule["remote_ip_prefix"] === "string" && rule["remote_ip_prefix"] !== "" ? rule["remote_ip_prefix"] : void 0;
6854
+ if (remoteGroup === groupId) return void 0;
6855
+ const source$1 = remoteGroup !== void 0 ? nameOf(remoteGroup) ?? remoteGroup : remoteCidr ?? "self";
6856
+ if (direction === "egress" && ports === "all" && protocol === "any") return void 0;
6857
+ return {
6858
+ direction,
6859
+ protocol,
6860
+ ports,
6861
+ source: source$1
6862
+ };
6863
+ }
6225
6864
  /**
6226
- * The class for one provider/type pair, stable across runs and pictures.
6865
+ * The rules worth showing for one security group, split by direction.
6227
6866
  *
6228
- * @param provider - the service that reported the resource.
6229
- * @param type - that service's own type name.
6230
- * @returns a D2 theme class reference.
6867
+ * @param resources - the account's resources.
6868
+ * @returns group id → its ingress and egress summaries, each de-duplicated.
6231
6869
  */
6232
- function inventoryClass(provider, type) {
6233
- const hash = (text) => {
6234
- let value = 0;
6235
- for (const character of text) value = value * 31 + character.charCodeAt(0) >>> 0;
6236
- return value;
6237
- };
6238
- const ramp = PROVIDER_RAMPS[hash(provider) % PROVIDER_RAMPS.length];
6239
- return ramp[hash(type) % ramp.length];
6870
+ function ruleSummaries(resources) {
6871
+ const nameOf = (id) => resources.find((resource) => resource.id === id)?.name;
6872
+ const found = new Map();
6873
+ for (const resource of resources) {
6874
+ if (resource.type !== "securityGroups") continue;
6875
+ const rules = resource.properties?.["security_group_rules"];
6876
+ if (!Array.isArray(rules)) continue;
6877
+ const bucket = {
6878
+ ingress: [],
6879
+ egress: []
6880
+ };
6881
+ const seen = new Set();
6882
+ for (const rule of rules) {
6883
+ if (rule === null || typeof rule !== "object") continue;
6884
+ const summary = summarizeRule(rule, resource.id, nameOf);
6885
+ if (summary === void 0) continue;
6886
+ const key = `${summary.direction}\u0000${summary.protocol}\u0000${summary.ports}\u0000${summary.source}`;
6887
+ if (seen.has(key)) continue;
6888
+ seen.add(key);
6889
+ if (summary.direction === "egress") bucket.egress.push(summary);
6890
+ else bucket.ingress.push(summary);
6891
+ }
6892
+ if (bucket.ingress.length > 0 || bucket.egress.length > 0) found.set(resource.id, bucket);
6893
+ }
6894
+ return found;
6240
6895
  }
6241
6896
  /**
6242
- * Draw an inventory-derived topology.
6897
+ * Read all three layers at once.
6243
6898
  *
6244
- * @param topology - the picture derived from the inventory.
6245
- * @returns the D2 source and the SVG it renders to.
6899
+ * @param resources - the account's resources.
6900
+ * @returns the resolved view.
6246
6901
  */
6247
- async function renderInventoryTopology(topology) {
6248
- const source$1 = inventoryToD2(topology);
6902
+ function accountView(resources) {
6903
+ const policyEdges = policies(resources);
6904
+ const policyGroups = new Set();
6905
+ for (const edge of policyEdges) {
6906
+ policyGroups.add(edge.from);
6907
+ policyGroups.add(edge.to);
6908
+ }
6249
6909
  return {
6250
- source: source$1,
6251
- svg: await renderD2(source$1)
6910
+ parentOf: containment(resources),
6911
+ guardsOf: guards(resources),
6912
+ policies: policyEdges,
6913
+ policyGroups
6252
6914
  };
6253
6915
  }
6916
+
6917
+ //#endregion
6918
+ //#region src/traffic.ts
6254
6919
  /**
6255
- * Generate the D2 source for an inventory-derived topology.
6920
+ * Read a string-valued property, unwrapping the JSON encoding the inventory
6921
+ * uses for some ids.
6256
6922
  *
6257
- * @param topology - the picture.
6258
- * @returns D2 source text.
6923
+ * @param value - the property value.
6924
+ * @returns the id it holds, or `undefined`.
6259
6925
  */
6260
- function inventoryToD2(topology) {
6261
- const lines = themePreamble();
6262
- if (topology.roots.length > GRID_COLUMNS) lines.push(`grid-columns: ${GRID_COLUMNS}`, "");
6263
- const write$1 = (node, depth) => {
6264
- const indent = " ".repeat(depth);
6265
- const label = node.facts.length === 0 ? node.label : `${node.label} ${node.facts.map((fact) => fact.value).join(" · ")}`;
6266
- const style = `class: [${inventoryClass(node.provider, node.type)}]`;
6267
- if (node.children.length === 0) {
6268
- lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} { ${style} }`);
6269
- return;
6926
+ function idOf(value) {
6927
+ if (typeof value === "string") {
6928
+ const trimmed = value.trim();
6929
+ if (trimmed !== "" && !trimmed.startsWith("[")) return trimmed;
6930
+ try {
6931
+ const parsed = JSON.parse(trimmed);
6932
+ return Array.isArray(parsed) && typeof parsed[0] === "string" ? parsed[0] : void 0;
6933
+ } catch {
6934
+ return void 0;
6270
6935
  }
6271
- lines.push(`${indent}${nodeId(node.id)}: ${quote(label)} {`);
6272
- lines.push(`${indent} ${style}`);
6273
- for (const child of node.children) write$1(child, depth + 1);
6274
- lines.push(`${indent}}`);
6275
- };
6276
- for (const root of topology.roots) write$1(root, 0);
6277
- if (topology.roots.length > 0) lines.push("");
6278
- for (const edge of drawnEdges(topology)) lines.push(`${nodeId(edge.from)} -> ${nodeId(edge.to)}: ${quote(edge.attribute)} { class: [${CONNECTION_CLASS$1}] }`);
6279
- return lines.join("\n");
6936
+ }
6937
+ if (Array.isArray(value) && typeof value[0] === "string") return value[0];
6938
+ return void 0;
6280
6939
  }
6281
6940
  /**
6282
- * The relationships worth drawing as an arrow.
6941
+ * The object an array-valued property's first entry holds.
6283
6942
  *
6284
- * Three kinds of association are dropped, each for a reason that shows up on a
6285
- * real account rather than being a preference:
6943
+ * The provider nests one-to-many links this way: `loadbalancers: [{ id }]`,
6944
+ * `eips: [{ eip_id, eip_address }]`. Reading the first entry is enough because a
6945
+ * listener belongs to exactly one balancer and an EIP has exactly one instance.
6286
6946
  *
6287
- * 1. **Containment.** A parent/child edge is already said by the nesting, and
6288
- * an arrow beside it draws the same fact twice — the line leaves the box
6289
- * it never left.
6290
- * 2. **The reverse of another edge.** The inventory reports both ends of a
6291
- * relationship: an EIP names its bandwidth and the bandwidth names the
6292
- * EIP, a server names its volumes and each volume names the server. Both
6293
- * are true, but one arrow per pair says as much and does not put two
6294
- * lines on top of each other. Measured on a live 49-resource account:
6295
- * 40 associations, 32 distinct pairs.
6296
- * 3. **A reference that points at an ancestor.** The VPC a resource sits in
6297
- * is visible from where the resource is drawn; a line from inside the
6298
- * container out to it adds no fact and crosses the container's border to
6299
- * say nothing. Five of those on the same account, all of them `vpc_id`.
6947
+ * @param value - the property value.
6948
+ * @returns the first entry, when it is an object.
6949
+ */
6950
+ function firstOf(value) {
6951
+ if (!Array.isArray(value)) return void 0;
6952
+ const first = value[0];
6953
+ return first !== null && typeof first === "object" ? first : void 0;
6954
+ }
6955
+ /**
6956
+ * The cluster a listener fronts, when the listener says so.
6300
6957
  *
6301
- * What is left is a genuine cross-container reference: a resource here naming
6302
- * a resource there. Those are the ones a reader has to follow, so they are the
6303
- * ones that get a line.
6958
+ * A listener created by the Kubernetes integration records its owner as JSON in
6959
+ * `description` — `{"cluster_id": "…", "service_id": "…"}`. That is the only
6960
+ * place the hop from the load balancer to the cluster is written down.
6304
6961
  *
6305
- * @param topology - the derived picture.
6306
- * @returns the edges to draw, deduplicated and without the ones nesting implies.
6962
+ * @param resource - a listener.
6963
+ * @returns the cluster id, or `undefined` when the listener is not owned by one.
6307
6964
  */
6308
- function drawnEdges(topology) {
6309
- const parentOf = new Map(topology.nodes.map((node) => [node.id, node.parent]));
6310
- const ancestorsOf = new Map(topology.nodes.map((node) => [node.id, node.ancestors]));
6311
- const seenPairs = new Set();
6312
- const drawn = [];
6313
- for (const edge of topology.edges) {
6314
- if (parentOf.get(edge.from) === edge.to) continue;
6315
- if ((ancestorsOf.get(edge.from) ?? []).includes(edge.to)) continue;
6316
- const pair = [edge.from, edge.to].sort().join("\0");
6317
- if (seenPairs.has(pair)) continue;
6318
- seenPairs.add(pair);
6319
- drawn.push(edge);
6965
+ function clusterBehind(resource) {
6966
+ const description = resource.properties?.["description"];
6967
+ if (typeof description !== "string") return void 0;
6968
+ const trimmed = description.trim();
6969
+ if (!trimmed.startsWith("{")) return void 0;
6970
+ try {
6971
+ const parsed = JSON.parse(trimmed);
6972
+ const cluster = parsed["cluster_id"];
6973
+ return typeof cluster === "string" && cluster !== "" ? cluster : void 0;
6974
+ } catch {
6975
+ return void 0;
6320
6976
  }
6321
- return drawn;
6322
6977
  }
6323
6978
  /**
6324
- * The D2 identifier for a cloud id.
6325
- *
6326
- * The `r_` prefix is what keeps an id from colliding with D2's own reserved
6327
- * words, and the base conversion handles every character D2 would otherwise
6328
- * read as syntax.
6979
+ * Every path the inventory states.
6329
6980
  *
6330
- * @param id - a cloud resource id.
6331
- * @returns an identifier D2 accepts.
6981
+ * @param resources - the account's resources.
6982
+ * @returns the paths, each starting at the internet.
6332
6983
  */
6333
- function nodeId(id) {
6334
- return d2Id(`r_${id}`);
6984
+ function trafficPaths(resources) {
6985
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
6986
+ const paths = [];
6987
+ for (const resource of resources) {
6988
+ if (resource.type !== "publicips") continue;
6989
+ const attached = idOf(resource.properties?.["associateInstanceId"]);
6990
+ if (attached === void 0 || !byId.has(attached)) continue;
6991
+ const address = typeof resource.properties?.["publicIpAddress"] === "string" ? resource.properties["publicIpAddress"] : resource.name;
6992
+ paths.push({ hops: [
6993
+ {
6994
+ kind: "internet",
6995
+ id: void 0,
6996
+ detail: void 0
6997
+ },
6998
+ {
6999
+ kind: "eip",
7000
+ id: resource.id,
7001
+ detail: address
7002
+ },
7003
+ {
7004
+ kind: "target",
7005
+ id: attached,
7006
+ detail: void 0
7007
+ }
7008
+ ] });
7009
+ }
7010
+ for (const resource of resources) {
7011
+ if (resource.type !== "listeners") continue;
7012
+ const owner = firstOf(resource.properties?.["loadbalancers"]);
7013
+ const balancer = owner === void 0 ? void 0 : idOf(owner["id"]);
7014
+ if (balancer === void 0 || !byId.has(balancer)) continue;
7015
+ const protocol = typeof resource.properties?.["protocol"] === "string" ? resource.properties["protocol"] : void 0;
7016
+ const port = resource.properties?.["protocol_port"];
7017
+ const detail = protocol !== void 0 && (typeof port === "number" || typeof port === "string") ? `${protocol}:${String(port)}` : protocol;
7018
+ const cluster = clusterBehind(resource);
7019
+ const hops = [{
7020
+ kind: "balancer",
7021
+ id: balancer,
7022
+ detail: void 0
7023
+ }, {
7024
+ kind: "listener",
7025
+ id: resource.id,
7026
+ detail
7027
+ }];
7028
+ if (cluster !== void 0 && byId.has(cluster)) hops.push({
7029
+ kind: "target",
7030
+ id: cluster,
7031
+ detail: void 0
7032
+ });
7033
+ paths.push({ hops });
7034
+ }
7035
+ return paths;
7036
+ }
7037
+ /**
7038
+ * Continue a chain past its last box, through the policy that admits it.
7039
+ *
7040
+ * ## The gap this closes, and the limit of closing it
7041
+ *
7042
+ * A Kubernetes listener records the cluster it fronts, and nothing further: the
7043
+ * inventory does not say which pods talk to which database. What it DOES say is
7044
+ * that one group admits another on a port, and which resources each group
7045
+ * guards — so a cluster guarded by group A, where A's peer group B admits the
7046
+ * database, is a flow the account actually states.
7047
+ *
7048
+ * That is a hop through a rule rather than through a resource, and it is the
7049
+ * only continuation the data supports. It is added only when exactly one group
7050
+ * admits exactly one guarded target: with several candidates the chain would be
7051
+ * a guess, and a guess drawn as a flow is the defect this module exists to
7052
+ * avoid.
7053
+ *
7054
+ * @param resources - the account's resources.
7055
+ * @param view - the resolved layers.
7056
+ * @returns extra hops, keyed by the resource a chain currently ends at.
7057
+ */
7058
+ function policyContinuations(resources, view) {
7059
+ const continuations = new Map();
7060
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
7061
+ const carrierOf = new Map();
7062
+ for (const [resourceId, names] of view.guardsOf) for (const name$1 of names) {
7063
+ const group = resources.find((resource) => resource.name === name$1 && resource.type === "securityGroups");
7064
+ if (group === void 0) continue;
7065
+ carrierOf.set(group.id, [...carrierOf.get(group.id) ?? [], resourceId]);
7066
+ }
7067
+ for (const policy of view.policies) {
7068
+ if (policy.direction !== "ingress") continue;
7069
+ const carriers = carrierOf.get(policy.from) ?? [];
7070
+ const destination = byId.get(policy.to);
7071
+ if (carriers.length !== 1) continue;
7072
+ if (destination === void 0) continue;
7073
+ const guardedResources = resources.filter((resource) => (view.guardsOf.get(resource.id) ?? []).includes(destination.name ?? "") && resource.id !== carriers[0]);
7074
+ if (guardedResources.length !== 1) continue;
7075
+ const target = guardedResources[0];
7076
+ continuations.set(carriers[0], {
7077
+ kind: "target",
7078
+ id: target.id,
7079
+ detail: policy.ports === void 0 ? void 0 : `${policy.protocol === "any" ? "tcp" : policy.protocol} ${policy.ports}`
7080
+ });
7081
+ }
7082
+ return continuations;
6335
7083
  }
6336
7084
 
6337
7085
  //#endregion
6338
- //#region src/d2-design.ts
6339
- /**
6340
- * The D2 palette classes per node kind.
6341
- *
6342
- * These are D2's OWN theme classes (`fill-B4`, `stroke-B1`, …), not custom
6343
- * colours, and that is the whole reason for using them. A custom
6344
- * `classes: { vpc: { style: { fill: "#EEF4FF" } } }` is emitted as a
6345
- * hard-coded `fill="#EEF4FF"` on the element, so it stays light-blue on a dark
6346
- * ground and the diagram becomes unreadable. The built-in classes are emitted
6347
- * as class REFERENCES, and D2 writes both palettes into the SVG with the dark
6348
- * half behind `@media (prefers-color-scheme: dark)` — so one file follows the
6349
- * viewer's theme with no JavaScript.
6350
- *
6351
- * The hues are D2's accent ramps: `B` (blue) for network structure, `AA` (red)
6352
- * for the one kind that is a warning by nature, and `N` (neutral) for anything
6353
- * unrecognised. Lightness steps apart so a subnet reads as inside its VPC.
6354
- */
6355
- const KIND_CLASSES = {
6356
- vpc: "fill-B5, stroke-B3",
6357
- subnet: "fill-B6, stroke-B4",
6358
- "security-group": "fill-AA4, stroke-AA2",
6359
- "security-group-rule": "fill-AA5, stroke-AA4",
6360
- gateway: "fill-N6, stroke-N4",
6361
- "load-balancer": "fill-B4, stroke-B2",
6362
- compute: "fill-AB5, stroke-AB4",
6363
- database: "fill-AB4, stroke-AB4"
6364
- };
7086
+ //#region src/diagram.ts
6365
7087
  /**
6366
- * The short noun a node's box is headed with.
7088
+ * The lines a security group's rules become, inside the box they guard.
6367
7089
  *
6368
- * The design vocabulary's names are this module's own (`security-group`), while
6369
- * the box is read by someone looking at a network diagram and needs the words
6370
- * the cloud uses.
7090
+ * Ingress first, then egress, each rule on its own line. The verbs are
7091
+ * `in`/`out` rather than the provider's `ingress`/`egress`: a box is scanned,
7092
+ * and the direction is the first thing a reader checks.
6371
7093
  *
6372
- * `compute` and `database` are the two kinds that cover several provider types,
6373
- * so their captions are the generic word rather than one product name: a CCE
6374
- * node is not an ECS instance and a DDS cluster is not RDS, and a box captioned
6375
- * "ECS" would claim it is. The node's own `name` and terraform type carry the
6376
- * specific identity.
7094
+ * @param summaries - the rules worth showing for the groups guarding a box.
7095
+ * @returns the detail lines, or an empty list when there are none.
6377
7096
  */
6378
- const KIND_CAPTION = {
6379
- vpc: "VPC",
6380
- subnet: "subnet",
6381
- "security-group": "secgroup",
6382
- "security-group-rule": "rule",
6383
- gateway: "gateway",
6384
- "load-balancer": "ELB",
6385
- compute: "compute",
6386
- database: "database"
6387
- };
7097
+ function ruleLines(summaries) {
7098
+ const lines = [];
7099
+ for (const bucket of summaries) {
7100
+ for (const rule of bucket.ingress) lines.push(`in ${rule.protocol} ${rule.ports} \u2190 ${rule.source}`);
7101
+ for (const rule of bucket.egress) lines.push(`out ${rule.protocol} ${rule.ports} \u2192 ${rule.source}`);
7102
+ }
7103
+ return lines;
7104
+ }
6388
7105
  /**
6389
- * The words on a connection's arrow.
7106
+ * The text a resource's box shows.
6390
7107
  *
6391
- * The cloud's own term for each, not this module's: a reader who looks at the
6392
- * console finds "对等连接", "终端节点" and "路由" — and a diagram that renamed
6393
- * them would need a translation step nobody asked for.
7108
+ * The name first — that is what the console and every other tool call it by —
7109
+ * then the one fact that makes it recognisable: a subnet's CIDR, a server's
7110
+ * flavour. Everything else is left out, because a box whose label is a dump of
7111
+ * properties cannot be scanned.
7112
+ *
7113
+ * @param resource - the resource.
7114
+ * @returns the label.
6394
7115
  */
6395
- const CONNECTION_LABEL = {
6396
- peering: "peering",
6397
- endpoint: "VPCEP",
6398
- route: "route"
6399
- };
7116
+ function labelOf(resource) {
7117
+ const name$1 = resource.name ?? resource.id.slice(0, 8);
7118
+ const properties = resource.properties ?? {};
7119
+ const detail = typeof properties["cidr"] === "string" ? properties["cidr"] : typeof properties["flavor"] === "string" ? properties["flavor"] : typeof properties["flavorCode"] === "string" ? properties["flavorCode"] : typeof properties["publicIpAddress"] === "string" ? properties["publicIpAddress"] : void 0;
7120
+ return detail === void 0 || detail === name$1 ? name$1 : `${name$1} ${detail}`;
7121
+ }
6400
7122
  /**
6401
- * The D2 class an edge carries.
7123
+ * Build the node tree for one group of resources.
6402
7124
  *
6403
- * D2's connection classes take the same palette vocabulary as shapes, so the
6404
- * connection uses the accent that reads as "traffic flows here" rather than the
6405
- * neutral a plain reference gets. It is a theme class, not a literal colour, so
6406
- * the dark palette follows.
7125
+ * @param members - the resources to include.
7126
+ * @param parentOf - the resolved containment.
7127
+ * @param guardsOf - the resolved guarding.
7128
+ * @param excluded - ids handled elsewhere (the policy band).
7129
+ * @returns the nodes, with the topmost ones returned rather than nested.
6407
7130
  */
6408
- const CONNECTION_CLASS = "stroke-AB3";
7131
+ function treeOf(members, parentOf, guardsOf, excluded, summaryByName) {
7132
+ const present = new Set(members.map((resource) => resource.id));
7133
+ const holds = new Set();
7134
+ for (const resource of members) {
7135
+ const parent = parentOf.get(resource.id);
7136
+ if (parent !== void 0 && present.has(parent)) holds.add(parent);
7137
+ }
7138
+ const nodes = new Map();
7139
+ const build = (resource) => {
7140
+ const existing = nodes.get(resource.id);
7141
+ if (existing !== void 0) return existing;
7142
+ const guards$1 = guardsOf.get(resource.id) ?? [];
7143
+ const label = guards$1.length === 0 ? labelOf(resource) : `${labelOf(resource)} · SG ${guards$1.join(", ")}`;
7144
+ const node = {
7145
+ id: resource.id,
7146
+ provider: resource.provider,
7147
+ label,
7148
+ lines: ruleLines(guards$1.map((name$1) => summaryByName.get(name$1)).filter((x) => x !== void 0)),
7149
+ role: holds.has(resource.id) ? "container" : "resource",
7150
+ children: []
7151
+ };
7152
+ nodes.set(resource.id, node);
7153
+ return node;
7154
+ };
7155
+ const roots = [];
7156
+ const nested = new Set();
7157
+ for (const resource of members) {
7158
+ if (excluded.has(resource.id)) continue;
7159
+ const parent = parentOf.get(resource.id);
7160
+ if (parent === void 0 || !present.has(parent)) {
7161
+ roots.push(build(resource));
7162
+ continue;
7163
+ }
7164
+ nodes.get(parent)?.children.push(build(resource));
7165
+ nested.add(resource.id);
7166
+ }
7167
+ for (const resource of members) {
7168
+ if (nested.has(resource.id) || excluded.has(resource.id)) continue;
7169
+ if (!roots.some((root) => root.id === resource.id)) roots.push(build(resource));
7170
+ }
7171
+ return roots;
7172
+ }
6409
7173
  /**
6410
- * Draw the topology.
7174
+ * Convert the tree into the layout's shape.
6411
7175
  *
6412
- * @param topology - the derived picture.
6413
- * @param edges - the relationships to draw, from `<from-address>` to
6414
- * `<to-address>`. Only addresses the topology knows are drawn.
6415
- * @returns the D2 source and the SVG it renders to.
6416
- * @throws when the generated D2 source does not compile. That is a defect in
6417
- * this module rather than in the user's configuration — the generator is
6418
- * what produced the text — so the message names the generated fragment.
7176
+ * @param node - the tree node.
7177
+ * @returns the layout node.
7178
+ /**
7179
+ * Convert the tree into the layout's shape.
7180
+ *
7181
+ * @param node - the tree node.
7182
+ * @returns the layout node.
6419
7183
  */
6420
- async function renderTopology(topology, edges) {
6421
- const source$1 = toD2(topology, edges);
7184
+ function toLayoutNode$1(node) {
6422
7185
  return {
6423
- source: source$1,
6424
- svg: await renderD2(source$1)
7186
+ id: node.id,
7187
+ label: node.label,
7188
+ ...node.provider === "" ? {} : { provider: node.provider },
7189
+ ...node.lines.length === 0 ? {} : { detail: node.lines },
7190
+ ...node.figure === void 0 ? {} : { figure: node.figure },
7191
+ children: node.children.map((child) => toLayoutNode$1(child))
6425
7192
  };
6426
7193
  }
6427
7194
  /**
6428
- * Generate the D2 source for one topology.
6429
- *
6430
- * The shape of the output is fixed by what D2 accepts:
6431
- *
6432
- * - Nothing is written as an attribute child. `cidr: "10.0.0.0/16"` inside a
6433
- * node's block renders as its own box, which would put a stray rectangle
6434
- * in every subnet. Facts go into the node's LABEL instead.
6435
- * - Facts are separated by `·` rather than aligned into columns, because D2
6436
- * treats a leading `|` as a block-string terminator.
6437
- * - No `vars` block beyond the theme: D2 discards everything under it except
6438
- * `d2-config`.
7195
+ * Build the drawable diagram for an account.
6439
7196
  *
6440
- * @param topology - the derived picture.
6441
- * @param edges - the relationships to draw.
6442
- * @returns D2 source text.
7197
+ * @param resources - everything the inventory reported.
7198
+ * @returns the placed boxes, the policy edges, and each box's role.
6443
7199
  */
6444
- function toD2(topology, edges) {
6445
- const lines = themePreamble();
6446
- const byAddress = new Map(topology.nodes.map((node) => [node.address, node]));
6447
- for (const root of topology.roots) lines.push(...nodeLines(root, 0));
6448
- if (topology.roots.length > 0) lines.push("");
6449
- for (const edge of edges) {
6450
- const from = byAddress.get(edge.from);
6451
- const to = byAddress.get(edge.to);
6452
- if (from === void 0 || to === void 0) continue;
6453
- if (edge.connection === void 0) {
6454
- lines.push(`${d2Id(edge.from)} -> ${d2Id(edge.to)}`);
6455
- continue;
7200
+ function buildDiagram(resources) {
7201
+ const view = accountView(resources);
7202
+ const byId = new Map(resources.map((resource) => [resource.id, resource]));
7203
+ const summaries = ruleSummaries(resources);
7204
+ const summaryByName = new Map(resources.filter((resource) => summaries.has(resource.id)).map((resource) => [resource.name ?? resource.id, summaries.get(resource.id)]));
7205
+ const childrenOf = new Map();
7206
+ for (const [child, parent] of view.parentOf) childrenOf.set(parent, [...childrenOf.get(parent) ?? [], child]);
7207
+ const regions = new Map();
7208
+ for (const resource of resources) {
7209
+ const region = resource.region ?? "unknown";
7210
+ regions.set(region, [...regions.get(region) ?? [], resource]);
7211
+ }
7212
+ const claimed = new Set();
7213
+ /** Build one resource's node, with its guards shown inside it. */
7214
+ const nodeFor = (resource) => ({
7215
+ id: resource.id,
7216
+ provider: resource.provider,
7217
+ label: (() => {
7218
+ const guards$1 = view.guardsOf.get(resource.id) ?? [];
7219
+ return guards$1.length === 0 ? labelOf(resource) : `${labelOf(resource)} · SG ${guards$1.join(", ")}`;
7220
+ })(),
7221
+ lines: ruleLines((view.guardsOf.get(resource.id) ?? []).map((name$1) => summaryByName.get(name$1)).filter((x) => x !== void 0)),
7222
+ role: (childrenOf.get(resource.id) ?? []).length > 0 ? "container" : "resource",
7223
+ children: []
7224
+ });
7225
+ /** Attach every descendant of `parentId`, depth first. */
7226
+ const attachBelow = (parent, parentId) => {
7227
+ for (const childId of childrenOf.get(parentId) ?? []) {
7228
+ if (claimed.has(childId)) continue;
7229
+ claimed.add(childId);
7230
+ const resource = byId.get(childId);
7231
+ if (resource === void 0) continue;
7232
+ const node = nodeFor(resource);
7233
+ parent.children.push(node);
7234
+ attachBelow(node, childId);
7235
+ }
7236
+ };
7237
+ const regionTrees = [];
7238
+ for (const [region, members] of [...regions].sort((a, b) => a[0].localeCompare(b[0]))) {
7239
+ const inRegion = new Set(members.map((resource) => resource.id));
7240
+ const regionNode = {
7241
+ id: `region:${region}`,
7242
+ label: region,
7243
+ role: "container",
7244
+ provider: "",
7245
+ lines: [],
7246
+ children: []
7247
+ };
7248
+ for (const vpc of members.filter((resource) => resource.type === "vpcs")) {
7249
+ claimed.add(vpc.id);
7250
+ const vpcNode = {
7251
+ id: vpc.id,
7252
+ provider: vpc.provider,
7253
+ label: labelOf(vpc),
7254
+ role: "container",
7255
+ lines: [],
7256
+ children: []
7257
+ };
7258
+ attachBelow(vpcNode, vpc.id);
7259
+ regionNode.children.push(vpcNode);
6456
7260
  }
6457
- const label = CONNECTION_LABEL[edge.connection];
6458
- if (label === void 0) throw new Error(`no label for connection kind "${edge.connection}" (${edge.from} -> ${edge.to})`);
6459
- lines.push(`${d2Id(edge.from)} -> ${d2Id(edge.to)}: ${quote(label)} { class: [${CONNECTION_CLASS}] }`);
7261
+ regionTrees.push(regionNode);
6460
7262
  }
6461
- const panel = findingsPanel(topology.findings);
6462
- if (panel !== void 0) lines.push("", panel);
6463
- return lines.join("\n");
7263
+ const unclaimed = resources.filter((resource) => !claimed.has(resource.id) && resource.type !== "vpcs");
7264
+ /**
7265
+ * Which resources are shown as TEXT on something else rather than as a box.
7266
+ *
7267
+ * A security group and a bandwidth are properties of what they serve: the
7268
+ * value that names them is on the served resource, and the group's rules
7269
+ * already appear inside that resource's box. Drawing them again as boxes puts
7270
+ * the same object in two places, and a group that serves three things in one.
7271
+ */
7272
+ const users = groupUsers(resources);
7273
+ /** The rule lines one security group's box carries, ingress first. */
7274
+ const groupLines = (group) => {
7275
+ const bucket = summaryByName.get(group.name ?? "");
7276
+ if (bucket === void 0) return [];
7277
+ const lines = [];
7278
+ for (const rule of bucket.ingress) lines.push(`in ${rule.protocol} ${rule.ports} \u2190 ${rule.source}`);
7279
+ for (const rule of bucket.egress) lines.push(`out ${rule.protocol} ${rule.ports} \u2192 ${rule.source}`);
7280
+ return lines;
7281
+ };
7282
+ /**
7283
+ * The figure a security group's box shows: how many resources use it.
7284
+ *
7285
+ * A single number, drawn centred and larger than the rules, because it answers
7286
+ * a different question — is this group alive — and a reader should be able to
7287
+ * tell live from leftover without reading a line of text.
7288
+ */
7289
+ const groupFigure = (group) => String((users.get(group.id) ?? []).length);
7290
+ for (const regionNode of regionTrees) {
7291
+ const region = regionNode.label;
7292
+ const mine = unclaimed.filter((resource) => (resource.region ?? "unknown") === region);
7293
+ const groups = mine.filter((resource) => resource.type === "securityGroups");
7294
+ if (groups.length > 0) regionNode.children.push({
7295
+ id: `band:security:${region}`,
7296
+ label: "Security groups",
7297
+ role: "container",
7298
+ provider: "",
7299
+ lines: [],
7300
+ children: [...groups].sort((a, b) => (a.name ?? "").localeCompare(b.name ?? "")).map((group) => ({
7301
+ id: group.id,
7302
+ provider: group.provider,
7303
+ label: group.name ?? group.id,
7304
+ lines: groupLines(group),
7305
+ figure: groupFigure(group),
7306
+ role: "resource",
7307
+ children: []
7308
+ }))
7309
+ });
7310
+ const loose = mine.filter((resource) => resource.type !== "securityGroups" && resource.type !== "bandwidths");
7311
+ if (loose.length === 0) continue;
7312
+ const kids = treeOf(loose, view.parentOf, view.guardsOf, new Set(), summaryByName);
7313
+ const sorted = [...kids].sort((a, b) => a.label.localeCompare(b.label));
7314
+ regionNode.children.push({
7315
+ id: `band:loose:${region}`,
7316
+ label: "Unattached",
7317
+ role: "container",
7318
+ provider: "",
7319
+ lines: [],
7320
+ children: sorted
7321
+ });
7322
+ }
7323
+ const roots = regionTrees;
7324
+ const layout = layoutTree(roots.map((root) => toLayoutNode$1(root)));
7325
+ const roles = new Map();
7326
+ const note = (node) => {
7327
+ roles.set(node.id, node.role);
7328
+ for (const child of node.children) note(child);
7329
+ };
7330
+ for (const root of roots) note(root);
7331
+ const edges = [];
7332
+ view.policies;
7333
+ const ambiguous = new Set();
7334
+ for (const [child, parent] of view.parentOf) ambiguous.add(`${child}\u0000${parent}`);
7335
+ for (const path of trafficPaths(resources)) for (let index = 0; index < path.hops.length - 1; index++) {
7336
+ const from = path.hops[index];
7337
+ const to = path.hops[index + 1];
7338
+ if (from.id === void 0 || to.id === void 0) continue;
7339
+ if (!roles.has(from.id) || !roles.has(to.id)) continue;
7340
+ if (ambiguous.has(`${from.id}\u0000${to.id}`)) continue;
7341
+ if (ambiguous.has(`${to.id}\u0000${from.id}`)) continue;
7342
+ edges.push({
7343
+ from: from.id,
7344
+ to: to.id,
7345
+ label: to.detail ?? from.detail ?? "",
7346
+ kind: "traffic"
7347
+ });
7348
+ }
7349
+ for (const [from, hop] of policyContinuations(resources, view)) {
7350
+ if (hop.id === void 0) continue;
7351
+ if (!roles.has(from) || !roles.has(hop.id)) continue;
7352
+ edges.push({
7353
+ from,
7354
+ to: hop.id,
7355
+ label: hop.detail ?? "",
7356
+ kind: "traffic"
7357
+ });
7358
+ }
7359
+ return {
7360
+ width: layout.width,
7361
+ height: layout.height,
7362
+ boxes: layout.boxes,
7363
+ edges,
7364
+ roles
7365
+ };
6464
7366
  }
6465
7367
  /**
6466
- * One node and its children, as D2 block lines.
7368
+ * Draw the account as a diagram.
6467
7369
  *
6468
- * The label carries the facts, because D2 has no other place for them. A leaf
6469
- * is written as `id: "label" { class: kind }`; a container additionally opens
6470
- * a block so its children nest inside it.
7370
+ * @param resources - everything the inventory reported.
7371
+ * @returns the SVG and a text record of what it shows.
7372
+ */
7373
+ function renderAccountDiagram(resources) {
7374
+ const diagram = buildDiagram(resources);
7375
+ return {
7376
+ diagram,
7377
+ svg: renderDiagram(diagram),
7378
+ source: describe$1(diagram)
7379
+ };
7380
+ }
7381
+ /**
7382
+ * A readable text form of the diagram, written beside the SVG.
7383
+ *
7384
+ * It is not D2 any more and does not claim to be: it records the nesting and the
7385
+ * policy edges as indented text, which is what a reader opens it for.
6471
7386
  *
6472
- * @param node - the node to write.
6473
- * @param depth - indentation depth, for nesting.
6474
- * @returns the lines for this node and its subtree.
7387
+ * @param diagram - the built diagram.
7388
+ * @returns the text.
6475
7389
  */
6476
- function nodeLines(node, depth) {
6477
- const indent = " ".repeat(depth);
6478
- const label = d2Label(node);
6479
- const classes = KIND_CLASSES[node.kind];
6480
- if (classes === void 0) throw new Error(`no D2 class for node kind "${node.kind}" (${node.address})`);
6481
- const style = `class: [${classes}]`;
6482
- const extra = node.existing ? ["style.stroke-dash: 4"] : [];
6483
- if (node.children.length === 0) {
6484
- if (extra.length === 0) return [`${indent}${d2Id(node.address)}: ${quote(label)} { ${style} }`];
6485
- return [
6486
- `${indent}${d2Id(node.address)}: ${quote(label)} {`,
6487
- `${indent} ${style}`,
6488
- ...extra.map((line) => `${indent} ${line.trim()}`),
6489
- `${indent}}`
6490
- ];
7390
+ function describe$1(diagram) {
7391
+ const lines = [];
7392
+ const walk = (box, depth) => {
7393
+ lines.push(`${" ".repeat(depth)}${box.label}`);
7394
+ for (const child of box.children) walk(child, depth + 1);
7395
+ };
7396
+ for (const root of diagram.boxes.filter((box) => box.depth === 0)) walk(root, 0);
7397
+ if (diagram.edges.length > 0) {
7398
+ lines.push("", "policy:");
7399
+ for (const edge of diagram.edges) lines.push(` ${edge.from} -> ${edge.to} (${edge.label})`);
6491
7400
  }
6492
- return [
6493
- `${indent}${d2Id(node.address)}: ${quote(label)} {`,
6494
- `${indent} ${style}`,
6495
- ...extra.map((line) => `${indent} ${line.trim()}`),
6496
- ...node.children.flatMap((child) => nodeLines(child, depth + 1)),
6497
- `${indent}}`
6498
- ];
7401
+ return lines.join("\n");
6499
7402
  }
7403
+
7404
+ //#endregion
7405
+ //#region src/design-render.ts
6500
7406
  /**
6501
- * The text drawn on a node's box.
7407
+ * The word a box is headed with, by kind.
6502
7408
  *
6503
- * A rule leads with its EFFECT rather than its name, because the name is the
6504
- * model's own label (`https`, `ssh`) and the effect is what a reviewer has to
6505
- * check: `ingress 22 ← 0.0.0.0/0` says what the rule admits. Every other kind
6506
- * leads with its name, which is what the configuration and every other tool
6507
- * call it by.
7409
+ * Written out rather than derived from the kind name because the kind is this
7410
+ * module's vocabulary (`security-group`) while the box is read by someone
7411
+ * looking at a network diagram and needs the words the cloud uses.
7412
+ *
7413
+ * `compute` and `database` cover several provider types, so their captions stay
7414
+ * generic: a CCE node is not an ECS instance, and a box captioned "ECS" would
7415
+ * claim it is.
7416
+ */
7417
+ const KIND_CAPTION = {
7418
+ vpc: "VPC",
7419
+ subnet: "subnet",
7420
+ "security-group": "secgroup",
7421
+ "security-group-rule": "rule",
7422
+ gateway: "gateway",
7423
+ "load-balancer": "ELB",
7424
+ compute: "compute",
7425
+ database: "database"
7426
+ };
7427
+ /**
7428
+ * The text a design node's box shows.
6508
7429
  *
6509
- * Facts that would repeat the leading text are dropped rather than printed
6510
- * twice.
7430
+ * A rule leads with its EFFECT rather than its name: `ingress 22 ← 0.0.0.0/0`
7431
+ * says what it admits, which is what a reviewer checks. Every other kind leads
7432
+ * with its cloud name, falling back to the terraform label — the label is what
7433
+ * addresses and tool results use, but the cloud name is what the console shows.
6511
7434
  *
6512
- * @param node - the node to label.
7435
+ * @param node - the design node.
6513
7436
  * @returns one line of text.
6514
7437
  */
6515
- function d2Label(node) {
7438
+ function designLabel(node) {
6516
7439
  const facts = new Map(node.facts.map((fact) => [fact.key, fact.value]));
6517
7440
  if (node.kind === "security-group-rule") {
6518
7441
  const direction = facts.get("direction") ?? "?";
6519
7442
  const ports = facts.get("ports") ?? "all ports";
6520
7443
  const remote = facts.get("remote_ip_prefix");
6521
7444
  const arrow = direction === "egress" ? "→" : "←";
6522
- const target = remote === void 0 ? "" : ` ${arrow} ${remote}`;
6523
- return `${direction} ${ports}${target}`;
7445
+ return remote === void 0 ? `${direction} ${ports}` : `${direction} ${ports} ${arrow} ${remote}`;
6524
7446
  }
6525
- const kind = KIND_CAPTION[node.kind] ?? node.kind;
6526
- const head = `${kind} ${facts.get("name") ?? node.name}`;
7447
+ const caption = KIND_CAPTION[node.kind] ?? node.kind;
7448
+ const head = `${caption} ${facts.get("name") ?? node.name}`;
6527
7449
  const shown = node.facts.filter((fact) => fact.key !== "name").map((fact) => fact.value);
6528
7450
  return shown.length === 0 ? head : `${head} ${shown.join(" · ")}`;
6529
7451
  }
6530
7452
  /**
6531
- * The findings block, when there are findings.
7453
+ * Convert a design node into the layout tree's shape.
6532
7454
  *
6533
- * Written as a markdown block pinned below the diagram, so the problems sit
6534
- * beside the picture they describe rather than in a separate message a reader
6535
- * has to pair up. D2's markdown block terminates on a leading `|`, so the
6536
- * entries are a bulleted list and never a table.
7455
+ * @param node - the design node.
7456
+ * @returns the layout node.
7457
+ */
7458
+ function toLayoutNode(node) {
7459
+ return {
7460
+ id: node.address,
7461
+ label: designLabel(node),
7462
+ provider: node.type.replace(/^huaweicloud_/, "").split("_")[0] ?? "",
7463
+ existing: node.existing,
7464
+ children: node.children.map((child) => toLayoutNode(child))
7465
+ };
7466
+ }
7467
+ /**
7468
+ * Build the drawable diagram for a design.
6537
7469
  *
6538
- * `near: bottom-center` is the D2 constant for "under the whole diagram"; a
6539
- * shape address would tie the panel to one box and leave it off screen on a
6540
- * wide picture.
7470
+ * @param topology - the derived design.
7471
+ * @param edges - the relationships to draw, already filtered to what nesting
7472
+ * does not express.
7473
+ * @returns the placed boxes, the connectors, and each box's role.
7474
+ */
7475
+ function buildDesignDiagram(topology, edges) {
7476
+ const layout = layoutTree(topology.roots.map((root) => toLayoutNode(root)));
7477
+ const roles = new Map();
7478
+ const note = (node) => {
7479
+ roles.set(node.address, node.children.length > 0 ? "container" : "resource");
7480
+ for (const child of node.children) note(child);
7481
+ };
7482
+ for (const root of topology.roots) note(root);
7483
+ const boxEdges = [];
7484
+ for (const edge of edges) {
7485
+ if (!roles.has(edge.from) || !roles.has(edge.to)) continue;
7486
+ boxEdges.push({
7487
+ from: edge.from,
7488
+ to: edge.to,
7489
+ label: edge.connection === void 0 ? "" : CONNECTION_LABEL[edge.connection] ?? edge.connection,
7490
+ kind: "traffic"
7491
+ });
7492
+ }
7493
+ return {
7494
+ width: layout.width,
7495
+ height: layout.height,
7496
+ boxes: layout.boxes,
7497
+ edges: boxEdges,
7498
+ roles
7499
+ };
7500
+ }
7501
+ /** The words on a connection's arrow: the cloud's own term, not this module's. */
7502
+ const CONNECTION_LABEL = {
7503
+ peering: "peering",
7504
+ endpoint: "VPCEP",
7505
+ route: "route"
7506
+ };
7507
+ /**
7508
+ * Draw the design.
6541
7509
  *
6542
- * @param findings - the problems found while deriving.
6543
- * @returns the panel's D2 source, or `undefined` when there are none.
7510
+ * @param topology - the derived design.
7511
+ * @param edges - the relationships to draw.
7512
+ * @returns the SVG and a text record of what it shows.
6544
7513
  */
6545
- function findingsPanel(findings) {
6546
- if (findings.length === 0) return void 0;
6547
- const rendered = findings.map((finding) => {
6548
- const marker = finding.severity === "error" ? "**error**" : "warning";
6549
- return `- ${marker} — ${finding.summary}`;
6550
- });
6551
- return [
6552
- "findings: |md",
6553
- " **Design findings**",
6554
- "",
6555
- ...rendered.map((line) => ` ${line}`),
6556
- "| { near: bottom-center }"
6557
- ].join("\n");
7514
+ function renderDesignDiagram(topology, edges) {
7515
+ const diagram = buildDesignDiagram(topology, edges);
7516
+ return {
7517
+ diagram,
7518
+ svg: renderDiagram(diagram),
7519
+ source: describe(diagram)
7520
+ };
7521
+ }
7522
+ /**
7523
+ * A readable text form of the design, written beside the SVG.
7524
+ *
7525
+ * @param diagram - the built diagram.
7526
+ * @returns the text.
7527
+ */
7528
+ function describe(diagram) {
7529
+ const lines = [];
7530
+ const walk = (box, depth) => {
7531
+ lines.push(`${" ".repeat(depth)}${box.label}`);
7532
+ for (const child of box.children) walk(child, depth + 1);
7533
+ };
7534
+ for (const root of diagram.boxes.filter((box) => box.depth === 0)) walk(root, 0);
7535
+ if (diagram.edges.length > 0) {
7536
+ lines.push("", "connections:");
7537
+ for (const edge of diagram.edges) lines.push(` ${edge.from} -> ${edge.to} (${edge.label})`);
7538
+ }
7539
+ return lines.join("\n");
6558
7540
  }
6559
7541
 
6560
7542
  //#endregion
@@ -6686,7 +7668,7 @@ async function handleValidateDesign(deployment, existing) {
6686
7668
  let svg;
6687
7669
  let d2;
6688
7670
  try {
6689
- const rendered = await renderTopology(topology, edges);
7671
+ const rendered = renderDesignDiagram(topology, edges);
6690
7672
  svg = rendered.svg;
6691
7673
  d2 = rendered.source;
6692
7674
  } catch (error) {
@@ -6869,18 +7851,20 @@ function parseValidateJson(stdout) {
6869
7851
  async function handleInventoryOnly(deployment, existing) {
6870
7852
  const withProperties = existing.filter((resource) => resource.properties !== void 0 && Object.keys(resource.properties).length > 0);
6871
7853
  if (withProperties.length === 0) return fail("none of the `existing` resources carried a `properties` object, so there are no relationships to derive — the diagram would be a list of unconnected boxes. Pass each resource's `properties` from list_existing_resources verbatim; that is where the ids that connect resources live.");
6872
- const topology = deriveInventoryTopology(withProperties.map((resource) => ({
6873
- id: resource.id,
6874
- provider: resource.provider ?? "",
6875
- type: resource.type,
6876
- ...resource.name === void 0 ? {} : { name: resource.name },
6877
- ...resource.region === void 0 ? {} : { region: resource.region },
6878
- properties: resource.properties ?? {}
6879
- })));
6880
7854
  let svg;
6881
7855
  let d2;
7856
+ let diagram;
6882
7857
  try {
6883
- const rendered = await renderInventoryTopology(topology);
7858
+ const resources = withProperties.map((resource) => ({
7859
+ id: resource.id,
7860
+ provider: resource.provider ?? "",
7861
+ type: resource.type,
7862
+ ...resource.name === void 0 ? {} : { name: resource.name },
7863
+ ...resource.region === void 0 ? {} : { region: resource.region },
7864
+ properties: resource.properties ?? {}
7865
+ }));
7866
+ const rendered = renderAccountDiagram(resources);
7867
+ diagram = rendered.diagram;
6884
7868
  svg = rendered.svg;
6885
7869
  d2 = rendered.source;
6886
7870
  } catch (error) {
@@ -6907,22 +7891,22 @@ async function handleInventoryOnly(deployment, existing) {
6907
7891
  state: "skipped",
6908
7892
  detail: "There is no configuration to validate — this picture is of resources that already exist. Write a network .tf and call this tool again to have it checked."
6909
7893
  },
6910
- resources: topology.nodes.map((node) => ({
6911
- id: node.id,
6912
- type: `${node.provider}/${node.type}`,
6913
- label: node.label,
6914
- parent: node.parent ?? null
7894
+ resources: diagram.boxes.map((box) => ({
7895
+ id: box.id,
7896
+ type: diagram.roles.get(box.id) === "container" ? "container" : "resource",
7897
+ label: box.label,
7898
+ depth: box.depth
6915
7899
  })),
6916
- edges: topology.edges.map((edge) => ({
7900
+ edges: diagram.edges.map((edge) => ({
6917
7901
  from: edge.from,
6918
7902
  to: edge.to,
6919
- attribute: edge.attribute,
6920
- contains: edge.contains
7903
+ kind: edge.kind,
7904
+ label: edge.label
6921
7905
  })),
6922
7906
  summary: {
6923
- drawn: topology.nodes.length,
6924
- edges: topology.edges.length,
6925
- nested: topology.nodes.filter((node) => node.parent !== void 0).length,
7907
+ drawn: diagram.boxes.length,
7908
+ edges: diagram.edges.length,
7909
+ nested: diagram.boxes.filter((box) => box.depth > 0).length,
6926
7910
  ...provided === 0 ? {} : { without_properties: provided },
6927
7911
  validation: "skipped"
6928
7912
  },
@@ -9696,6 +10680,11 @@ function apply(ctx, config) {
9696
10680
  store,
9697
10681
  get region() {
9698
10682
  return config.defaultRegion.get();
10683
+ },
10684
+ onRejected: () => {
10685
+ clearCredentials(store);
10686
+ forgetAccount();
10687
+ ctx.emit("aishell/credentials-updated");
9699
10688
  }
9700
10689
  });
9701
10690
  const { registrar, captured } = createRegistrar();