@principal-ai/subsystems-core 0.51.5 → 0.51.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/index.d.ts +3 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +6 -1
  4. package/dist/index.js.map +1 -1
  5. package/dist/infra/c4.d.ts +59 -0
  6. package/dist/infra/c4.d.ts.map +1 -0
  7. package/dist/infra/c4.js +101 -0
  8. package/dist/infra/c4.js.map +1 -0
  9. package/dist/infra/index.d.ts +13 -0
  10. package/dist/infra/index.d.ts.map +1 -0
  11. package/dist/infra/index.js +22 -0
  12. package/dist/infra/index.js.map +1 -0
  13. package/dist/infra/jsonc.d.ts +10 -0
  14. package/dist/infra/jsonc.d.ts.map +1 -0
  15. package/dist/infra/jsonc.js +77 -0
  16. package/dist/infra/jsonc.js.map +1 -0
  17. package/dist/infra/terraform.d.ts +41 -0
  18. package/dist/infra/terraform.d.ts.map +1 -0
  19. package/dist/infra/terraform.js +208 -0
  20. package/dist/infra/terraform.js.map +1 -0
  21. package/dist/infra/types.d.ts +107 -0
  22. package/dist/infra/types.d.ts.map +1 -0
  23. package/dist/infra/types.js +47 -0
  24. package/dist/infra/types.js.map +1 -0
  25. package/dist/infra/wrangler.d.ts +24 -0
  26. package/dist/infra/wrangler.d.ts.map +1 -0
  27. package/dist/infra/wrangler.js +116 -0
  28. package/dist/infra/wrangler.js.map +1 -0
  29. package/dist/node.d.ts +2 -0
  30. package/dist/node.d.ts.map +1 -1
  31. package/dist/node.js +3 -1
  32. package/dist/node.js.map +1 -1
  33. package/dist/storage/topic-share.d.ts +57 -0
  34. package/dist/storage/topic-share.d.ts.map +1 -0
  35. package/dist/storage/topic-share.js +55 -0
  36. package/dist/storage/topic-share.js.map +1 -0
  37. package/package.json +1 -1
  38. package/src/index.ts +6 -0
  39. package/src/infra/c4.ts +141 -0
  40. package/src/infra/index.ts +21 -0
  41. package/src/infra/infra.test.ts +300 -0
  42. package/src/infra/jsonc.ts +70 -0
  43. package/src/infra/terraform.ts +251 -0
  44. package/src/infra/types.ts +136 -0
  45. package/src/infra/wrangler.ts +148 -0
  46. package/src/node.ts +2 -0
  47. package/src/storage/topic-share.test.ts +71 -0
  48. package/src/storage/topic-share.ts +91 -0
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Infrastructure-as-code read side. Pure and browser-safe.
3
+ */
4
+
5
+ export { infraResourceKey, mergeInfraManifests } from './types';
6
+ export type {
7
+ InfraBinding,
8
+ InfraDeploymentObservation,
9
+ InfraDeploymentStatus,
10
+ InfraManifest,
11
+ InfraResource,
12
+ InfraResourceSource,
13
+ InfraTool,
14
+ } from './types';
15
+ export { parseJsonc, stripJsonc } from './jsonc';
16
+ export { extractWranglerManifest } from './wrangler';
17
+ export type { ExtractWranglerOptions } from './wrangler';
18
+ export { extractTerraformManifest, terraformStateObservations } from './terraform';
19
+ export type { ExtractTerraformOptions } from './terraform';
20
+ export { infraContainerId, infraDeploymentRef, infraToC4 } from './c4';
21
+ export type { InfraC4Container, InfraC4Deployment, InfraC4Edge } from './c4';
@@ -0,0 +1,300 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import {
3
+ extractTerraformManifest,
4
+ extractWranglerManifest,
5
+ infraToC4,
6
+ mergeInfraManifests,
7
+ parseJsonc,
8
+ terraformStateObservations,
9
+ } from './index';
10
+
11
+ // The two real configs this was built against, verbatim.
12
+ const DEV_FEED = `{
13
+ "name": "dev-feed",
14
+ "main": "src/worker/index.ts",
15
+ "compatibility_date": "2025-11-01",
16
+ "vars": { "ALLOWED_ORGS": "pingdotgg,anomalyco,earendil-works" },
17
+ "ratelimits": [
18
+ { "name": "API_LIMITER", "namespace_id": "1001", "simple": { "limit": 120, "period": 60 } }
19
+ ],
20
+ "assets": { "not_found_handling": "single-page-application" },
21
+ "kv_namespaces": [{ "binding": "CACHE", "id": "347138f6fdef49d585fc898d6d9cf65d" }]
22
+ }`;
23
+
24
+ const TOPIC_SHARE = `{
25
+ "name": "topic-share",
26
+ "main": "src/worker/index.ts",
27
+ "compatibility_date": "2025-11-01",
28
+ // Days a shared topic lives after its last publish.
29
+ "vars": { "TTL_DAYS": "7", "MAX_PUBLISHES_PER_DAY": "200" },
30
+ "ratelimits": [
31
+ { "name": "API_LIMITER", "namespace_id": "1002", "simple": { "limit": 120, "period": 60 } }
32
+ ],
33
+ "assets": { "not_found_handling": "single-page-application", "binding": "ASSETS" },
34
+ "r2_buckets": [{ "binding": "TOPIC_BLOBS", "bucket_name": "topic-share" }],
35
+ // Replace database_id with the id from \`wrangler d1 create topic-share\` before the first deploy.
36
+ "d1_databases": [
37
+ {
38
+ "binding": "SHARE_INDEX",
39
+ "database_name": "topic-share",
40
+ "database_id": "62f4ec1e-1371-468d-9d13-eef5015c44ea",
41
+ "migrations_dir": "migrations"
42
+ }
43
+ ],
44
+ // Daily sweep of expired topics.
45
+ "triggers": { "crons": ["17 4 * * *"] }
46
+ }`;
47
+
48
+ describe('parseJsonc', () => {
49
+ test('drops comments and trailing commas but not string contents', () => {
50
+ const parsed = parseJsonc(`{
51
+ // line
52
+ "url": "https://example.com/a,]//b", /* block */
53
+ "list": [1, 2,],
54
+ }`);
55
+ expect(parsed).toEqual({ url: 'https://example.com/a,]//b', list: [1, 2] });
56
+ });
57
+
58
+ test('throws on malformed input', () => {
59
+ expect(() => parseJsonc('{ "a": ')).toThrow(SyntaxError);
60
+ });
61
+ });
62
+
63
+ describe('extractWranglerManifest', () => {
64
+ test('dev-feed: a Worker bound to one KV namespace', () => {
65
+ const manifest = extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' });
66
+ expect(manifest.resources.map((r) => r.key)).toEqual([
67
+ 'cloudflare:worker:dev-feed',
68
+ 'cloudflare:kv_namespace:347138f6fdef49d585fc898d6d9cf65d',
69
+ ]);
70
+ // A KV namespace is declared by opaque id, so the binding labels it.
71
+ expect(manifest.resources[1]).toMatchObject({
72
+ label: 'CACHE',
73
+ source: { tool: 'wrangler', file: 'wrangler.jsonc', pointer: '/kv_namespaces/0' },
74
+ });
75
+ expect(manifest.resources[0]!.attributes).toEqual({
76
+ main: 'src/worker/index.ts',
77
+ assets: 'true',
78
+ });
79
+ expect(manifest.bindings).toHaveLength(1);
80
+ expect(manifest.bindings[0]).toMatchObject({
81
+ from: 'cloudflare:worker:dev-feed',
82
+ to: 'cloudflare:kv_namespace:347138f6fdef49d585fc898d6d9cf65d',
83
+ binding: 'CACHE',
84
+ });
85
+ });
86
+
87
+ test('topic-share: R2 and D1 share a name but not a key; crons are kept', () => {
88
+ const manifest = extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' });
89
+ expect(manifest.resources.map((r) => r.key)).toEqual([
90
+ 'cloudflare:worker:topic-share',
91
+ 'cloudflare:r2_bucket:topic-share',
92
+ 'cloudflare:d1_database:topic-share',
93
+ ]);
94
+ expect(manifest.resources[0]!.attributes?.crons).toBe('17 4 * * *');
95
+ expect(manifest.resources[2]!.attributes).toEqual({
96
+ id: '62f4ec1e-1371-468d-9d13-eef5015c44ea',
97
+ });
98
+ expect(manifest.bindings.map((b) => b.binding)).toEqual(['TOPIC_BLOBS', 'SHARE_INDEX']);
99
+ });
100
+
101
+ test('never copies vars into the manifest', () => {
102
+ const manifest = extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' });
103
+ expect(JSON.stringify(manifest)).not.toContain('pingdotgg');
104
+ });
105
+
106
+ test('a service binding is an access path, not a second Worker declaration', () => {
107
+ const manifest = extractWranglerManifest(
108
+ { name: 'web', services: [{ binding: 'API', service: 'api' }] },
109
+ { file: 'wrangler.jsonc' },
110
+ );
111
+ expect(manifest.resources.map((r) => r.key)).toEqual(['cloudflare:worker:web']);
112
+ expect(manifest.bindings[0]).toMatchObject({ to: 'cloudflare:worker:api', binding: 'API' });
113
+ });
114
+
115
+ test('a config with no Worker name declares nothing', () => {
116
+ expect(extractWranglerManifest('{}', { file: 'wrangler.jsonc' })).toEqual({
117
+ resources: [],
118
+ bindings: [],
119
+ });
120
+ });
121
+ });
122
+
123
+ // Hand-written to the Cloudflare provider v5 schema; not captured from a real
124
+ // `terraform show -json` run.
125
+ const TF_STATE = {
126
+ format_version: '1.0',
127
+ values: {
128
+ root_module: {
129
+ resources: [
130
+ {
131
+ address: 'cloudflare_workers_script.topic_share',
132
+ mode: 'managed',
133
+ type: 'cloudflare_workers_script',
134
+ name: 'topic_share',
135
+ values: {
136
+ id: 'topic-share',
137
+ script_name: 'topic-share',
138
+ content: 'SECRET_SOURCE',
139
+ bindings: [
140
+ { type: 'r2_bucket', name: 'TOPIC_BLOBS', bucket_name: 'topic-share' },
141
+ { type: 'd1', name: 'SHARE_INDEX', id: '62f4ec1e-1371-468d-9d13-eef5015c44ea' },
142
+ { type: 'secret_text', name: 'TOKEN', text: 'SECRET_VALUE' },
143
+ ],
144
+ },
145
+ },
146
+ { address: 'data.cloudflare_zone.z', mode: 'data', type: 'cloudflare_zone', values: {} },
147
+ ],
148
+ child_modules: [
149
+ {
150
+ address: 'module.storage',
151
+ resources: [
152
+ {
153
+ address: 'module.storage.cloudflare_r2_bucket.blobs',
154
+ mode: 'managed',
155
+ type: 'cloudflare_r2_bucket',
156
+ values: { id: 'topic-share', name: 'topic-share' },
157
+ },
158
+ {
159
+ address: 'module.storage.cloudflare_d1_database.index',
160
+ mode: 'managed',
161
+ type: 'cloudflare_d1_database',
162
+ values: { id: '62f4ec1e-1371-468d-9d13-eef5015c44ea', name: 'topic-share' },
163
+ },
164
+ ],
165
+ },
166
+ ],
167
+ },
168
+ },
169
+ };
170
+
171
+ describe('extractTerraformManifest', () => {
172
+ test('yields the same keys and bindings as the equivalent wrangler config', () => {
173
+ const tf = extractTerraformManifest(TF_STATE, { file: 'infra' });
174
+ const wrangler = extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' });
175
+ expect(tf.resources.map((r) => r.key).sort()).toEqual(
176
+ wrangler.resources.map((r) => r.key).sort(),
177
+ );
178
+ // The D1 binding names the database by id; it resolves to the name-based key.
179
+ expect(tf.bindings.map((b) => [b.to, b.binding])).toEqual(
180
+ wrangler.bindings.map((b) => [b.to, b.binding]),
181
+ );
182
+ expect(tf.resources.find((r) => r.resourceType === 'r2_bucket')!.source).toEqual({
183
+ tool: 'terraform',
184
+ file: 'infra',
185
+ pointer: 'module.storage.cloudflare_r2_bucket.blobs',
186
+ });
187
+ });
188
+
189
+ test('copies no secret-bearing attribute out of state', () => {
190
+ const text = JSON.stringify([
191
+ extractTerraformManifest(TF_STATE, { file: 'infra' }),
192
+ terraformStateObservations(TF_STATE, { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' }),
193
+ ]);
194
+ expect(text).not.toContain('SECRET');
195
+ expect(text).not.toContain('TOKEN');
196
+ });
197
+
198
+ test('reads a plan, which declares but observes nothing', () => {
199
+ const plan = { planned_values: TF_STATE.values };
200
+ expect(extractTerraformManifest(plan, { file: 'infra' }).resources).toHaveLength(3);
201
+ expect(
202
+ terraformStateObservations(plan, { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' }),
203
+ ).toEqual([]);
204
+ });
205
+
206
+ test('split worker + version: bindings come from the version, live URL only when enabled', () => {
207
+ const state = (enabled: boolean) => ({
208
+ values: {
209
+ root_module: {
210
+ resources: [
211
+ {
212
+ address: 'cloudflare_worker.api',
213
+ mode: 'managed',
214
+ type: 'cloudflare_worker',
215
+ values: {
216
+ id: 'wid-1',
217
+ name: 'api',
218
+ subdomain: { enabled, url: 'https://api.acme.workers.dev' },
219
+ },
220
+ },
221
+ {
222
+ address: 'cloudflare_worker_version.api',
223
+ mode: 'managed',
224
+ type: 'cloudflare_worker_version',
225
+ values: {
226
+ worker_id: 'wid-1',
227
+ bindings: [{ type: 'kv_namespace', name: 'CACHE', namespace_id: 'ns-1' }],
228
+ },
229
+ },
230
+ ],
231
+ },
232
+ },
233
+ });
234
+ const options = { file: 'infra', observedAt: '2026-11-29T00:00:00.000Z' };
235
+ expect(extractTerraformManifest(state(true), options).bindings[0]).toMatchObject({
236
+ from: 'cloudflare:worker:api',
237
+ to: 'cloudflare:kv_namespace:ns-1',
238
+ binding: 'CACHE',
239
+ });
240
+ expect(terraformStateObservations(state(true), options)).toEqual([
241
+ {
242
+ resourceKey: 'cloudflare:worker:api',
243
+ status: 'deployed',
244
+ resourceId: 'wid-1',
245
+ liveUrls: ['https://api.acme.workers.dev'],
246
+ observedAt: options.observedAt,
247
+ source: 'terraform-state',
248
+ },
249
+ ]);
250
+ expect(terraformStateObservations(state(false), options)[0]!.liveUrls).toBeUndefined();
251
+ });
252
+ });
253
+
254
+ describe('infraToC4', () => {
255
+ test('one proposed container per resource, one draft edge per binding', () => {
256
+ const { nodes, edges } = infraToC4(
257
+ mergeInfraManifests([
258
+ extractWranglerManifest(DEV_FEED, { file: 'wrangler.jsonc' }),
259
+ extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' }),
260
+ ]),
261
+ );
262
+ expect(nodes.map((n) => [n.id, n.containerKind, n.technology])).toEqual([
263
+ ['container:dev-feed', 'application', 'Cloudflare Worker'],
264
+ ['container:cache-kv', 'data-store', 'Cloudflare KV'],
265
+ ['container:topic-share', 'application', 'Cloudflare Worker'],
266
+ ['container:topic-share-r2', 'data-store', 'Cloudflare R2'],
267
+ ['container:topic-share-d1', 'data-store', 'Cloudflare D1'],
268
+ ]);
269
+ expect(nodes.every((n) => n.state === 'proposed')).toBe(true);
270
+ expect(nodes[0]!.deployment).toMatchObject({
271
+ resourceKey: 'cloudflare:worker:dev-feed',
272
+ provider: 'cloudflare',
273
+ });
274
+ expect(edges.map((e) => [e.source, e.target, e.label])).toEqual([
275
+ ['container:dev-feed', 'container:cache-kv', 'env.CACHE'],
276
+ ['container:topic-share', 'container:topic-share-r2', 'env.TOPIC_BLOBS'],
277
+ ['container:topic-share', 'container:topic-share-d1', 'env.SHARE_INDEX'],
278
+ ]);
279
+ });
280
+
281
+ test('drops a binding whose target no manifest declares', () => {
282
+ const { edges } = infraToC4(
283
+ extractWranglerManifest(
284
+ { name: 'web', services: [{ binding: 'API', service: 'api' }] },
285
+ { file: 'wrangler.jsonc' },
286
+ ),
287
+ );
288
+ expect(edges).toEqual([]);
289
+ });
290
+
291
+ test('merging two tools declaring one resource keeps a single container', () => {
292
+ const merged = mergeInfraManifests([
293
+ extractWranglerManifest(TOPIC_SHARE, { file: 'wrangler.jsonc' }),
294
+ extractTerraformManifest(TF_STATE, { file: 'infra' }),
295
+ ]);
296
+ expect(merged.resources).toHaveLength(3);
297
+ expect(merged.bindings).toHaveLength(2);
298
+ expect(merged.resources.every((r) => r.source.tool === 'wrangler')).toBe(true);
299
+ });
300
+ });
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Minimal JSONC reader — JSON with `//` and block comments and trailing
3
+ * commas, which is what `wrangler.jsonc` allows. Kept in-house so the
4
+ * browser-safe entry gains no dependency for a small job.
5
+ */
6
+
7
+ /** Index just past the string literal that opens at `start`. */
8
+ function skipString(text: string, start: number): number {
9
+ let i = start + 1;
10
+ while (i < text.length && text[i] !== '"') i += text[i] === '\\' ? 2 : 1;
11
+ return i + 1;
12
+ }
13
+
14
+ function stripComments(text: string): string {
15
+ let out = '';
16
+ let i = 0;
17
+ while (i < text.length) {
18
+ const ch = text[i]!;
19
+ const next = text[i + 1];
20
+ if (ch === '"') {
21
+ const end = skipString(text, i);
22
+ out += text.slice(i, end);
23
+ i = end;
24
+ } else if (ch === '/' && next === '/') {
25
+ while (i < text.length && text[i] !== '\n') i += 1;
26
+ } else if (ch === '/' && next === '*') {
27
+ const end = text.indexOf('*/', i + 2);
28
+ i = end === -1 ? text.length : end + 2;
29
+ } else {
30
+ out += ch;
31
+ i += 1;
32
+ }
33
+ }
34
+ return out;
35
+ }
36
+
37
+ function stripTrailingCommas(text: string): string {
38
+ let out = '';
39
+ let i = 0;
40
+ while (i < text.length) {
41
+ const ch = text[i]!;
42
+ if (ch === '"') {
43
+ const end = skipString(text, i);
44
+ out += text.slice(i, end);
45
+ i = end;
46
+ continue;
47
+ }
48
+ if (ch === ',') {
49
+ let j = i + 1;
50
+ while (j < text.length && /\s/.test(text[j]!)) j += 1;
51
+ if (text[j] === '}' || text[j] === ']') {
52
+ i += 1;
53
+ continue;
54
+ }
55
+ }
56
+ out += ch;
57
+ i += 1;
58
+ }
59
+ return out;
60
+ }
61
+
62
+ /** Remove comments and trailing commas, leaving string contents untouched. */
63
+ export function stripJsonc(text: string): string {
64
+ return stripTrailingCommas(stripComments(text));
65
+ }
66
+
67
+ /** Parse JSONC text. Throws `SyntaxError` like `JSON.parse` on malformed input. */
68
+ export function parseJsonc(text: string): unknown {
69
+ return JSON.parse(stripJsonc(text));
70
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Terraform → {@link InfraManifest}, read from `terraform show -json`.
3
+ *
4
+ * We read Terraform's own JSON rendering, never HCL: it is the documented
5
+ * machine-readable form, modules and variables are already resolved in it, and
6
+ * the same walk covers a plan (`planned_values`) and applied state (`values`).
7
+ *
8
+ * Cloudflare provider v5 resource shapes only. Attribute names follow the
9
+ * provider's published schema for `cloudflare_workers_script`,
10
+ * `cloudflare_worker` + `cloudflare_worker_version`, `cloudflare_r2_bucket`,
11
+ * `cloudflare_d1_database`, `cloudflare_workers_kv_namespace` and
12
+ * `cloudflare_queue`.
13
+ *
14
+ * Only type, name, id and declared URLs are ever read off a resource. State
15
+ * can hold secrets in other attributes; nothing here copies them out.
16
+ */
17
+
18
+ import {
19
+ infraResourceKey,
20
+ type InfraBinding,
21
+ type InfraDeploymentObservation,
22
+ type InfraManifest,
23
+ type InfraResource,
24
+ type InfraResourceSource,
25
+ } from './types';
26
+
27
+ const PROVIDER = 'cloudflare';
28
+
29
+ type Json = Record<string, unknown>;
30
+
31
+ function isObject(value: unknown): value is Json {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ }
34
+
35
+ function str(value: unknown): string | undefined {
36
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
37
+ }
38
+
39
+ interface TfResource {
40
+ address: string;
41
+ type: string;
42
+ values: Json;
43
+ }
44
+
45
+ /** Managed resources of a module and every child module, depth-first. */
46
+ function collectResources(module: unknown, out: TfResource[] = []): TfResource[] {
47
+ if (!isObject(module)) return out;
48
+ if (Array.isArray(module.resources)) {
49
+ for (const resource of module.resources) {
50
+ if (!isObject(resource) || resource.mode !== 'managed') continue;
51
+ const address = str(resource.address);
52
+ const type = str(resource.type);
53
+ if (!address || !type) continue;
54
+ out.push({ address, type, values: isObject(resource.values) ? resource.values : {} });
55
+ }
56
+ }
57
+ if (Array.isArray(module.child_modules)) {
58
+ for (const child of module.child_modules) collectResources(child, out);
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** State (`values`) when present, else a plan's `planned_values`. */
64
+ function rootModule(showJson: unknown): { module: unknown; applied: boolean } {
65
+ if (!isObject(showJson)) return { module: undefined, applied: false };
66
+ if (isObject(showJson.values)) return { module: showJson.values.root_module, applied: true };
67
+ if (isObject(showJson.planned_values)) {
68
+ return { module: showJson.planned_values.root_module, applied: false };
69
+ }
70
+ return { module: undefined, applied: false };
71
+ }
72
+
73
+ /** How each store type names itself and what its key is built from. */
74
+ interface StoreType {
75
+ resourceType: string;
76
+ /** The human name field. */
77
+ nameField: string;
78
+ /**
79
+ * Whether the key is the provider id rather than the name. True for KV,
80
+ * because a wrangler config knows a namespace by id only and the two tools
81
+ * must agree on the key.
82
+ */
83
+ keyById: boolean;
84
+ }
85
+
86
+ const STORE_TYPES: Record<string, StoreType> = {
87
+ cloudflare_r2_bucket: { resourceType: 'r2_bucket', nameField: 'name', keyById: false },
88
+ cloudflare_d1_database: { resourceType: 'd1_database', nameField: 'name', keyById: false },
89
+ cloudflare_workers_kv_namespace: { resourceType: 'kv_namespace', nameField: 'title', keyById: true },
90
+ cloudflare_queue: { resourceType: 'queue', nameField: 'queue_name', keyById: false },
91
+ };
92
+
93
+ /** Binding `type` → the resource type it reaches and the field that names the target. */
94
+ const BINDING_TYPES: Record<string, { resourceType: string; refFields: readonly string[] }> = {
95
+ kv_namespace: { resourceType: 'kv_namespace', refFields: ['namespace_id'] },
96
+ r2_bucket: { resourceType: 'r2_bucket', refFields: ['bucket_name'] },
97
+ d1: { resourceType: 'd1_database', refFields: ['id', 'database_id'] },
98
+ queue: { resourceType: 'queue', refFields: ['queue_name'] },
99
+ service: { resourceType: 'worker', refFields: ['service'] },
100
+ };
101
+
102
+ export interface ExtractTerraformOptions {
103
+ /**
104
+ * Repo-root-relative path recorded on every source — the directory or file
105
+ * the JSON was rendered from (e.g. `infra/` or `infra/main.tf`).
106
+ */
107
+ file: string;
108
+ }
109
+
110
+ interface Extracted {
111
+ manifest: InfraManifest;
112
+ /** Whether the JSON was applied state rather than a plan. */
113
+ applied: boolean;
114
+ /** Per resource key: the fields an observation is allowed to carry. */
115
+ observed: Map<string, { resourceId?: string; liveUrls?: string[] }>;
116
+ }
117
+
118
+ function extract(showJson: unknown, options: ExtractTerraformOptions): Extracted {
119
+ const { module, applied } = rootModule(showJson);
120
+ const tfResources = collectResources(module);
121
+ const source = (pointer: string): InfraResourceSource => ({
122
+ tool: 'terraform',
123
+ file: options.file,
124
+ pointer,
125
+ });
126
+
127
+ const resources: InfraResource[] = [];
128
+ const observed: Extracted['observed'] = new Map();
129
+ /** `<resourceType>\0<id or name>` → key, so a binding can find its target either way. */
130
+ const lookup = new Map<string, string>();
131
+ const index = (resourceType: string, ref: string | undefined, key: string) => {
132
+ if (ref) lookup.set(`${resourceType}\u0000${ref}`, key);
133
+ };
134
+
135
+ // Stores first, so Worker bindings can resolve against them.
136
+ for (const tf of tfResources) {
137
+ const store = STORE_TYPES[tf.type];
138
+ if (!store) continue;
139
+ const name = str(tf.values[store.nameField]);
140
+ const id = str(tf.values.id);
141
+ const identifier = store.keyById ? id ?? name : name;
142
+ if (!identifier) continue;
143
+ const key = infraResourceKey(PROVIDER, store.resourceType, identifier);
144
+ resources.push({
145
+ key,
146
+ provider: PROVIDER,
147
+ resourceType: store.resourceType,
148
+ name: identifier,
149
+ label: name ?? identifier,
150
+ source: source(tf.address),
151
+ ...(id ? { attributes: { id } } : {}),
152
+ });
153
+ index(store.resourceType, id, key);
154
+ index(store.resourceType, name, key);
155
+ observed.set(key, { ...(id ? { resourceId: id } : {}) });
156
+ }
157
+
158
+ // Workers: the classic single-resource script, and the split worker + version.
159
+ /** Worker id or name → key, for `cloudflare_worker_version.worker_id`. */
160
+ const workerKeys = new Map<string, string>();
161
+ for (const tf of tfResources) {
162
+ const isScript = tf.type === 'cloudflare_workers_script';
163
+ if (!isScript && tf.type !== 'cloudflare_worker') continue;
164
+ const name = str(isScript ? tf.values.script_name : tf.values.name);
165
+ if (!name) continue;
166
+ const key = infraResourceKey(PROVIDER, 'worker', name);
167
+ const id = str(tf.values.id);
168
+ resources.push({
169
+ key,
170
+ provider: PROVIDER,
171
+ resourceType: 'worker',
172
+ name,
173
+ label: name,
174
+ source: source(tf.address),
175
+ });
176
+ workerKeys.set(name, key);
177
+ if (id) workerKeys.set(id, key);
178
+ index('worker', name, key);
179
+ // `subdomain.url` is present whenever the account owns a workers.dev
180
+ // subdomain, so it is only a live URL when the subdomain is enabled.
181
+ const subdomain = isObject(tf.values.subdomain) ? tf.values.subdomain : undefined;
182
+ const url = subdomain?.enabled === true ? str(subdomain.url) : undefined;
183
+ observed.set(key, {
184
+ ...(id ? { resourceId: id } : {}),
185
+ ...(url ? { liveUrls: [url] } : {}),
186
+ });
187
+ }
188
+
189
+ const bindings: InfraBinding[] = [];
190
+ for (const tf of tfResources) {
191
+ let from: string | undefined;
192
+ if (tf.type === 'cloudflare_workers_script') {
193
+ const name = str(tf.values.script_name);
194
+ from = name ? workerKeys.get(name) : undefined;
195
+ } else if (tf.type === 'cloudflare_worker_version') {
196
+ const workerId = str(tf.values.worker_id);
197
+ from = workerId ? workerKeys.get(workerId) : undefined;
198
+ }
199
+ if (!from || !Array.isArray(tf.values.bindings)) continue;
200
+ tf.values.bindings.forEach((entry, i) => {
201
+ if (!isObject(entry)) return;
202
+ const family = BINDING_TYPES[str(entry.type) ?? ''];
203
+ const binding = str(entry.name);
204
+ if (!family || !binding) return;
205
+ const ref = family.refFields.map((field) => str(entry[field])).find(Boolean);
206
+ if (!ref) return;
207
+ // Resolve through a declared resource when there is one, so a D1 binding
208
+ // by id lands on the database's name-based key. Otherwise key by the ref.
209
+ const to =
210
+ lookup.get(`${family.resourceType}\u0000${ref}`) ??
211
+ infraResourceKey(PROVIDER, family.resourceType, ref);
212
+ bindings.push({ from: from!, to, binding, source: source(`${tf.address}.bindings[${i}]`) });
213
+ });
214
+ }
215
+
216
+ return { manifest: { resources, bindings }, applied, observed };
217
+ }
218
+
219
+ /**
220
+ * Read the declared resources out of `terraform show -json` output — applied
221
+ * state or a saved plan. Unknown resource types are ignored.
222
+ */
223
+ export function extractTerraformManifest(
224
+ showJson: unknown,
225
+ options: ExtractTerraformOptions,
226
+ ): InfraManifest {
227
+ return extract(showJson, options).manifest;
228
+ }
229
+
230
+ /**
231
+ * Turn applied state into deployment observations.
232
+ *
233
+ * State is a record of the last apply, not a live check: a resource deleted
234
+ * out of band still appears. The observation says so through its `source`
235
+ * (`terraform-state`), and `observedAt` should be when the state was read.
236
+ * A plan yields no observations.
237
+ */
238
+ export function terraformStateObservations(
239
+ showJson: unknown,
240
+ options: ExtractTerraformOptions & { observedAt: string },
241
+ ): InfraDeploymentObservation[] {
242
+ const { manifest, applied, observed } = extract(showJson, options);
243
+ if (!applied) return [];
244
+ return manifest.resources.map((resource) => ({
245
+ resourceKey: resource.key,
246
+ status: 'deployed' as const,
247
+ ...observed.get(resource.key),
248
+ observedAt: options.observedAt,
249
+ source: 'terraform-state',
250
+ }));
251
+ }