@principal-ai/subsystems-core 0.52.0 → 0.53.1
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/README.md +30 -2
- package/dist/audit/boundary.d.ts +104 -0
- package/dist/audit/boundary.d.ts.map +1 -0
- package/dist/audit/boundary.js +363 -0
- package/dist/audit/boundary.js.map +1 -0
- package/dist/audit/c4.d.ts +41 -0
- package/dist/audit/c4.d.ts.map +1 -0
- package/dist/audit/c4.js +41 -0
- package/dist/audit/c4.js.map +1 -0
- package/dist/audit/engine.d.ts +135 -0
- package/dist/audit/engine.d.ts.map +1 -0
- package/dist/audit/engine.js +865 -0
- package/dist/audit/engine.js.map +1 -0
- package/dist/audit/fixes.d.ts +80 -0
- package/dist/audit/fixes.d.ts.map +1 -0
- package/dist/audit/fixes.js +162 -0
- package/dist/audit/fixes.js.map +1 -0
- package/dist/audit/graphify-provider.d.ts +51 -0
- package/dist/audit/graphify-provider.d.ts.map +1 -0
- package/dist/audit/graphify-provider.js +36 -0
- package/dist/audit/graphify-provider.js.map +1 -0
- package/dist/audit/hash.d.ts +25 -0
- package/dist/audit/hash.d.ts.map +1 -0
- package/dist/audit/hash.js +53 -0
- package/dist/audit/hash.js.map +1 -0
- package/dist/audit/index.d.ts +12 -0
- package/dist/audit/index.d.ts.map +1 -0
- package/dist/audit/index.js +40 -0
- package/dist/audit/index.js.map +1 -0
- package/dist/audit/local-graphify.d.ts +75 -0
- package/dist/audit/local-graphify.d.ts.map +1 -0
- package/dist/audit/local-graphify.js +283 -0
- package/dist/audit/local-graphify.js.map +1 -0
- package/dist/audit/paths.d.ts +16 -0
- package/dist/audit/paths.d.ts.map +1 -0
- package/dist/audit/paths.js +31 -0
- package/dist/audit/paths.js.map +1 -0
- package/dist/audit/pure.d.ts +18 -0
- package/dist/audit/pure.d.ts.map +1 -0
- package/dist/audit/pure.js +50 -0
- package/dist/audit/pure.js.map +1 -0
- package/dist/audit/report-logic.d.ts +17 -0
- package/dist/audit/report-logic.d.ts.map +1 -0
- package/dist/audit/report-logic.js +206 -0
- package/dist/audit/report-logic.js.map +1 -0
- package/dist/audit/report.d.ts +140 -0
- package/dist/audit/report.d.ts.map +1 -0
- package/dist/audit/report.js +3 -0
- package/dist/audit/report.js.map +1 -0
- package/dist/audit/trail.d.ts +29 -0
- package/dist/audit/trail.d.ts.map +1 -0
- package/dist/audit/trail.js +59 -0
- package/dist/audit/trail.js.map +1 -0
- package/dist/audit/verification.d.ts +98 -0
- package/dist/audit/verification.d.ts.map +1 -0
- package/dist/audit/verification.js +11 -0
- package/dist/audit/verification.js.map +1 -0
- package/dist/audit/verify/component.d.ts +68 -0
- package/dist/audit/verify/component.d.ts.map +1 -0
- package/dist/audit/verify/component.js +500 -0
- package/dist/audit/verify/component.js.map +1 -0
- package/dist/audit/verify/declarations.d.ts +58 -0
- package/dist/audit/verify/declarations.d.ts.map +1 -0
- package/dist/audit/verify/declarations.js +227 -0
- package/dist/audit/verify/declarations.js.map +1 -0
- package/dist/audit/verify/grammar.d.ts +12 -0
- package/dist/audit/verify/grammar.d.ts.map +1 -0
- package/dist/audit/verify/grammar.js +57 -0
- package/dist/audit/verify/grammar.js.map +1 -0
- package/dist/audit/verify/index.d.ts +12 -0
- package/dist/audit/verify/index.d.ts.map +1 -0
- package/dist/audit/verify/index.js +31 -0
- package/dist/audit/verify/index.js.map +1 -0
- package/dist/audit/verify/parser.d.ts +19 -0
- package/dist/audit/verify/parser.d.ts.map +1 -0
- package/dist/audit/verify/parser.js +122 -0
- package/dist/audit/verify/parser.js.map +1 -0
- package/dist/audit/verify/span.d.ts +49 -0
- package/dist/audit/verify/span.d.ts.map +1 -0
- package/dist/audit/verify/span.js +377 -0
- package/dist/audit/verify/span.js.map +1 -0
- package/dist/graphify/anchor.d.ts +45 -0
- package/dist/graphify/anchor.d.ts.map +1 -0
- package/dist/graphify/anchor.js +179 -0
- package/dist/graphify/anchor.js.map +1 -0
- package/dist/graphify/consolidated.d.ts +259 -0
- package/dist/graphify/consolidated.d.ts.map +1 -0
- package/dist/graphify/consolidated.js +12 -0
- package/dist/graphify/consolidated.js.map +1 -0
- package/dist/graphify/construct.d.ts +41 -0
- package/dist/graphify/construct.d.ts.map +1 -0
- package/dist/graphify/construct.js +106 -0
- package/dist/graphify/construct.js.map +1 -0
- package/dist/graphify/ids.d.ts +19 -0
- package/dist/graphify/ids.d.ts.map +1 -0
- package/dist/graphify/ids.js +53 -0
- package/dist/graphify/ids.js.map +1 -0
- package/dist/graphify/index.d.ts +16 -0
- package/dist/graphify/index.d.ts.map +1 -0
- package/dist/graphify/index.js +32 -0
- package/dist/graphify/index.js.map +1 -0
- package/dist/graphify/resolve.d.ts +48 -0
- package/dist/graphify/resolve.d.ts.map +1 -0
- package/dist/graphify/resolve.js +89 -0
- package/dist/graphify/resolve.js.map +1 -0
- package/dist/graphify/signature.d.ts +87 -0
- package/dist/graphify/signature.d.ts.map +1 -0
- package/dist/graphify/signature.js +282 -0
- package/dist/graphify/signature.js.map +1 -0
- package/dist/graphify/types.d.ts +141 -0
- package/dist/graphify/types.d.ts.map +1 -0
- package/dist/graphify/types.js +9 -0
- package/dist/graphify/types.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.js.map +1 -1
- package/dist/infra/c4.d.ts +59 -0
- package/dist/infra/c4.d.ts.map +1 -0
- package/dist/infra/c4.js +106 -0
- package/dist/infra/c4.js.map +1 -0
- package/dist/infra/index.d.ts +17 -0
- package/dist/infra/index.d.ts.map +1 -0
- package/dist/infra/index.js +30 -0
- package/dist/infra/index.js.map +1 -0
- package/dist/infra/jsonc.d.ts +10 -0
- package/dist/infra/jsonc.d.ts.map +1 -0
- package/dist/infra/jsonc.js +77 -0
- package/dist/infra/jsonc.js.map +1 -0
- package/dist/infra/observe.d.ts +102 -0
- package/dist/infra/observe.d.ts.map +1 -0
- package/dist/infra/observe.js +347 -0
- package/dist/infra/observe.js.map +1 -0
- package/dist/infra/terraform.d.ts +41 -0
- package/dist/infra/terraform.d.ts.map +1 -0
- package/dist/infra/terraform.js +208 -0
- package/dist/infra/terraform.js.map +1 -0
- package/dist/infra/types.d.ts +107 -0
- package/dist/infra/types.d.ts.map +1 -0
- package/dist/infra/types.js +47 -0
- package/dist/infra/types.js.map +1 -0
- package/dist/infra/wrangler.d.ts +32 -0
- package/dist/infra/wrangler.d.ts.map +1 -0
- package/dist/infra/wrangler.js +177 -0
- package/dist/infra/wrangler.js.map +1 -0
- package/dist/node.d.ts +3 -0
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +4 -1
- package/dist/node.js.map +1 -1
- package/dist/storage/topic-reference-links.d.ts +3 -3
- package/dist/storage/topic-reference-links.d.ts.map +1 -1
- package/dist/storage/topic-reference-links.js +23 -8
- package/dist/storage/topic-reference-links.js.map +1 -1
- package/dist/storage/topic-share.d.ts +69 -0
- package/dist/storage/topic-share.d.ts.map +1 -0
- package/dist/storage/topic-share.js +67 -0
- package/dist/storage/topic-share.js.map +1 -0
- package/dist/storage/topic-types.d.ts +5 -1
- package/dist/storage/topic-types.d.ts.map +1 -1
- package/dist/types/subsystem-model.d.ts +59 -0
- package/dist/types/subsystem-model.d.ts.map +1 -1
- package/dist/types/subsystem-model.js +50 -1
- package/dist/types/subsystem-model.js.map +1 -1
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +25 -2
- package/dist/validation.js.map +1 -1
- package/package.json +22 -2
- package/schemas/subsystem-model.schema.json +35 -19
- package/src/audit/boundary.ts +447 -0
- package/src/audit/c4.ts +70 -0
- package/src/audit/engine.ts +1099 -0
- package/src/audit/fixes.ts +192 -0
- package/src/audit/graphify-provider.test.ts +58 -0
- package/src/audit/graphify-provider.ts +77 -0
- package/src/audit/hash.ts +58 -0
- package/src/audit/index.ts +34 -0
- package/src/audit/local-graphify.test.ts +163 -0
- package/src/audit/local-graphify.ts +354 -0
- package/src/audit/paths.ts +25 -0
- package/src/audit/pure.ts +91 -0
- package/src/audit/report-logic.test.ts +145 -0
- package/src/audit/report-logic.ts +245 -0
- package/src/audit/report.ts +207 -0
- package/src/audit/trail.ts +77 -0
- package/src/audit/verification.ts +104 -0
- package/src/audit/verify/component.ts +760 -0
- package/src/audit/verify/declarations.ts +284 -0
- package/src/audit/verify/grammar.ts +57 -0
- package/src/audit/verify/index.ts +41 -0
- package/src/audit/verify/parser.ts +124 -0
- package/src/audit/verify/span.ts +478 -0
- package/src/graphify/anchor.ts +206 -0
- package/src/graphify/consolidated.ts +298 -0
- package/src/graphify/construct.ts +153 -0
- package/src/graphify/ids.ts +48 -0
- package/src/graphify/index.ts +16 -0
- package/src/graphify/resolve.ts +115 -0
- package/src/graphify/signature.ts +354 -0
- package/src/graphify/types.ts +164 -0
- package/src/index.ts +11 -0
- package/src/infra/c4.ts +146 -0
- package/src/infra/index.ts +36 -0
- package/src/infra/infra.test.ts +360 -0
- package/src/infra/jsonc.ts +70 -0
- package/src/infra/observe.test.ts +202 -0
- package/src/infra/observe.ts +451 -0
- package/src/infra/terraform.ts +251 -0
- package/src/infra/types.ts +136 -0
- package/src/infra/wrangler.ts +203 -0
- package/src/node.ts +3 -0
- package/src/storage/topic-reference-links.test.ts +7 -1
- package/src/storage/topic-reference-links.ts +24 -8
- package/src/storage/topic-share.test.ts +91 -0
- package/src/storage/topic-share.ts +118 -0
- package/src/storage/topic-types.ts +3 -1
- package/src/storage/topicStore.test.ts +1 -0
- package/src/types/subsystem-model.test.ts +52 -2
- package/src/types/subsystem-model.ts +104 -0
- package/src/validation.test.ts +71 -7
- package/src/validation.ts +27 -2
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Looking at a live account — the checks that turn declared resource keys into
|
|
3
|
+
* {@link InfraDeploymentObservation}s.
|
|
4
|
+
*
|
|
5
|
+
* This is the one place that knows how to ask a provider whether a declared
|
|
6
|
+
* resource exists. It is given a credential and returns observations; it does
|
|
7
|
+
* not know where the credential came from (a pasted token, a CLI login, a
|
|
8
|
+
* server-held token) and it stores nothing. Hosts own both ends: Studio and
|
|
9
|
+
* the desktop app run it in their main process, a hosted service can run it in
|
|
10
|
+
* a Worker.
|
|
11
|
+
*
|
|
12
|
+
* Fetch-only and browser-safe. The token travels only in the Authorization
|
|
13
|
+
* header of requests to the provider's API, and never appears in a result.
|
|
14
|
+
*
|
|
15
|
+
* Cloudflare only: Workers, R2, D1, KV, Queues and Containers. A resource type
|
|
16
|
+
* with no lookup is reported as skipped rather than guessed at.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { InfraDeploymentObservation } from './types';
|
|
20
|
+
|
|
21
|
+
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
22
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
23
|
+
const ACCOUNT_ID_SHAPE = /^[a-f0-9]{32}$/;
|
|
24
|
+
|
|
25
|
+
/** What a check needs to run, besides the credential. */
|
|
26
|
+
export interface InfraObserveDeps {
|
|
27
|
+
fetch?: typeof fetch;
|
|
28
|
+
now?: () => Date;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A credential for one Cloudflare account. */
|
|
32
|
+
export interface CloudflareAccess {
|
|
33
|
+
/** An API token or an OAuth access token; sent as a Bearer token. */
|
|
34
|
+
token: string;
|
|
35
|
+
accountId: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
39
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
type CloudflareResult<T> =
|
|
43
|
+
| { ok: true; result: T }
|
|
44
|
+
| { ok: false; status: number; code?: number; message: string };
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* One read against the Cloudflare API. Failures come back as values: the
|
|
48
|
+
* caller decides whether "not there" and "could not ask" mean different
|
|
49
|
+
* things.
|
|
50
|
+
*/
|
|
51
|
+
async function cloudflareGet<T>(
|
|
52
|
+
path: string,
|
|
53
|
+
token: string,
|
|
54
|
+
doFetch: typeof fetch,
|
|
55
|
+
): Promise<CloudflareResult<T>> {
|
|
56
|
+
let response: Response;
|
|
57
|
+
try {
|
|
58
|
+
response = await doFetch(`${CLOUDFLARE_API}${path}`, {
|
|
59
|
+
headers: { Authorization: `Bearer ${token}` },
|
|
60
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
61
|
+
});
|
|
62
|
+
} catch {
|
|
63
|
+
return { ok: false, status: 0, message: 'could not reach the Cloudflare API' };
|
|
64
|
+
}
|
|
65
|
+
let body: unknown;
|
|
66
|
+
try {
|
|
67
|
+
body = await response.json();
|
|
68
|
+
} catch {
|
|
69
|
+
return { ok: false, status: response.status, message: `Cloudflare answered ${response.status}` };
|
|
70
|
+
}
|
|
71
|
+
if (response.ok && isRecord(body) && body['success'] === true) {
|
|
72
|
+
return { ok: true, result: body['result'] as T };
|
|
73
|
+
}
|
|
74
|
+
// The containers API answers with the bare value, not the usual envelope.
|
|
75
|
+
if (response.ok && (Array.isArray(body) || (isRecord(body) && !('success' in body)))) {
|
|
76
|
+
return { ok: true, result: body as T };
|
|
77
|
+
}
|
|
78
|
+
const first =
|
|
79
|
+
isRecord(body) && Array.isArray(body['errors']) && isRecord(body['errors'][0])
|
|
80
|
+
? body['errors'][0]
|
|
81
|
+
: undefined;
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
status: response.status,
|
|
85
|
+
...(typeof first?.['code'] === 'number' ? { code: first['code'] } : {}),
|
|
86
|
+
message:
|
|
87
|
+
typeof first?.['message'] === 'string'
|
|
88
|
+
? first['message']
|
|
89
|
+
: `Cloudflare answered ${response.status}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export type CloudflareAccountResult =
|
|
94
|
+
| { ok: true; accountId: string; account?: string }
|
|
95
|
+
| {
|
|
96
|
+
ok: false;
|
|
97
|
+
error: string;
|
|
98
|
+
/** Set when the token sees several accounts and one must be chosen. */
|
|
99
|
+
accounts?: Array<{ id: string; name: string }>;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Work out which account a Cloudflare token is for, and prove it can do the
|
|
104
|
+
* job: it must resolve to one account and be able to read that account's
|
|
105
|
+
* Workers. A token that cannot is refused with the reason, so a person finds
|
|
106
|
+
* out when connecting rather than from cards that never light up.
|
|
107
|
+
*/
|
|
108
|
+
export async function resolveCloudflareAccount(
|
|
109
|
+
input: { token: string; accountId?: string },
|
|
110
|
+
deps: InfraObserveDeps = {},
|
|
111
|
+
): Promise<CloudflareAccountResult> {
|
|
112
|
+
const doFetch = deps.fetch ?? fetch;
|
|
113
|
+
const { token } = input;
|
|
114
|
+
let accountId = input.accountId?.trim() ?? '';
|
|
115
|
+
if (accountId && !ACCOUNT_ID_SHAPE.test(accountId)) {
|
|
116
|
+
return { ok: false, error: 'The account id should be 32 hexadecimal characters.' };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
let account: string | undefined;
|
|
120
|
+
const listed = await cloudflareGet<Array<{ id?: string; name?: string }>>(
|
|
121
|
+
'/accounts?per_page=50',
|
|
122
|
+
token,
|
|
123
|
+
doFetch,
|
|
124
|
+
);
|
|
125
|
+
if (!listed.ok && (listed.status === 401 || listed.status === 403) && !accountId) {
|
|
126
|
+
return { ok: false, error: `Cloudflare rejected the token: ${listed.message}` };
|
|
127
|
+
}
|
|
128
|
+
if (!listed.ok && listed.status === 0) return { ok: false, error: listed.message };
|
|
129
|
+
const accounts = (listed.ok && Array.isArray(listed.result) ? listed.result : [])
|
|
130
|
+
.filter((a): a is { id: string; name?: string } => typeof a?.id === 'string')
|
|
131
|
+
.map((a) => ({ id: a.id, name: a.name ?? a.id }));
|
|
132
|
+
if (accountId) {
|
|
133
|
+
account = accounts.find((a) => a.id === accountId)?.name;
|
|
134
|
+
} else if (accounts.length === 1) {
|
|
135
|
+
accountId = accounts[0]!.id;
|
|
136
|
+
account = accounts[0]!.name;
|
|
137
|
+
} else if (accounts.length > 1) {
|
|
138
|
+
return { ok: false, error: 'This token can see several accounts. Choose one.', accounts };
|
|
139
|
+
} else {
|
|
140
|
+
return {
|
|
141
|
+
ok: false,
|
|
142
|
+
error: 'This token cannot list its account. Enter the account id as well.',
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// The permission the checks need. Also proves the account id is right.
|
|
147
|
+
const probe = await cloudflareGet<{ subdomain?: string }>(
|
|
148
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
149
|
+
token,
|
|
150
|
+
doFetch,
|
|
151
|
+
);
|
|
152
|
+
if (!probe.ok) {
|
|
153
|
+
// 10007: no workers.dev subdomain registered — the token still works.
|
|
154
|
+
const usable = probe.status === 404 || probe.code === 10007;
|
|
155
|
+
if (!usable) {
|
|
156
|
+
return {
|
|
157
|
+
ok: false,
|
|
158
|
+
error:
|
|
159
|
+
probe.status === 0
|
|
160
|
+
? probe.message
|
|
161
|
+
: `The token cannot read Workers on that account: ${probe.message}`,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return { ok: true, accountId, ...(account ? { account } : {}) };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `cloudflare:worker:name` → `name`. Names may not contain a colon. */
|
|
169
|
+
function parseKey(key: string): { provider: string; resourceType: string; identifier: string } | null {
|
|
170
|
+
const [provider, resourceType, ...rest] = key.split(':');
|
|
171
|
+
const identifier = rest.join(':');
|
|
172
|
+
return provider && resourceType && identifier ? { provider, resourceType, identifier } : null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** What one lookup learned about one resource. */
|
|
176
|
+
type Seen =
|
|
177
|
+
| {
|
|
178
|
+
state: 'deployed';
|
|
179
|
+
resourceId?: string;
|
|
180
|
+
liveUrls?: string[];
|
|
181
|
+
consoleUrl?: string;
|
|
182
|
+
version?: string;
|
|
183
|
+
deployedAt?: string;
|
|
184
|
+
}
|
|
185
|
+
| { state: 'not-found' }
|
|
186
|
+
/** The question could not be asked: auth, network, or an answer we cannot read. */
|
|
187
|
+
| { state: 'unknown'; reason: string };
|
|
188
|
+
|
|
189
|
+
interface CheckContext {
|
|
190
|
+
accountId: string;
|
|
191
|
+
get: <T>(path: string) => Promise<CloudflareResult<T>>;
|
|
192
|
+
/** The account's workers.dev subdomain, fetched once and only if needed. */
|
|
193
|
+
workersSubdomain: () => Promise<string | undefined>;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function missing(result: { status: number; code?: number }): boolean {
|
|
197
|
+
return result.status === 404 || result.code === 10007;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function isoOrUndefined(value: unknown): string | undefined {
|
|
201
|
+
return typeof value === 'string' && !Number.isNaN(Date.parse(value))
|
|
202
|
+
? new Date(value).toISOString()
|
|
203
|
+
: undefined;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const dash = (accountId: string, path: string) => `https://dash.cloudflare.com/${accountId}/${path}`;
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* One lookup per resource type. Each asks for exactly the declared thing — by
|
|
210
|
+
* the same name or id the config uses — and never lists more of the account
|
|
211
|
+
* than it needs to find it. Every call is a read.
|
|
212
|
+
*/
|
|
213
|
+
const CHECKS: Record<string, (identifier: string, ctx: CheckContext) => Promise<Seen>> = {
|
|
214
|
+
worker: async (name, ctx) => {
|
|
215
|
+
const script = encodeURIComponent(name);
|
|
216
|
+
const base = `/accounts/${ctx.accountId}/workers/scripts/${script}`;
|
|
217
|
+
const state = await ctx.get<{ enabled?: boolean }>(`${base}/subdomain`);
|
|
218
|
+
if (!state.ok) return missing(state) ? { state: 'not-found' } : { state: 'unknown', reason: state.message };
|
|
219
|
+
|
|
220
|
+
// Everything below is best effort: the Worker is already known to exist.
|
|
221
|
+
const liveUrls: string[] = [];
|
|
222
|
+
const domains = await ctx.get<Array<{ hostname?: string }>>(
|
|
223
|
+
`/accounts/${ctx.accountId}/workers/domains/records?service=${script}`,
|
|
224
|
+
);
|
|
225
|
+
if (domains.ok && Array.isArray(domains.result)) {
|
|
226
|
+
for (const domain of domains.result) {
|
|
227
|
+
if (typeof domain?.hostname === 'string' && domain.hostname) {
|
|
228
|
+
liveUrls.push(`https://${domain.hostname}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (state.result?.enabled) {
|
|
233
|
+
const subdomain = await ctx.workersSubdomain();
|
|
234
|
+
if (subdomain) liveUrls.push(`https://${name}.${subdomain}.workers.dev`);
|
|
235
|
+
}
|
|
236
|
+
const deployments = await ctx.get<{
|
|
237
|
+
deployments?: Array<{ created_on?: string; versions?: Array<{ version_id?: string }> }>;
|
|
238
|
+
}>(`${base}/deployments`);
|
|
239
|
+
const latest = deployments.ok ? deployments.result?.deployments?.[0] : undefined;
|
|
240
|
+
const version = latest?.versions?.[0]?.version_id;
|
|
241
|
+
const deployedAt = isoOrUndefined(latest?.created_on);
|
|
242
|
+
return {
|
|
243
|
+
state: 'deployed',
|
|
244
|
+
// A custom domain, when there is one, is the address people use.
|
|
245
|
+
...(liveUrls.length > 0 ? { liveUrls } : {}),
|
|
246
|
+
consoleUrl: dash(ctx.accountId, `workers/services/view/${script}/production`),
|
|
247
|
+
...(typeof version === 'string' ? { version } : {}),
|
|
248
|
+
...(deployedAt ? { deployedAt } : {}),
|
|
249
|
+
};
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
r2_bucket: async (name, ctx) => {
|
|
253
|
+
const bucket = encodeURIComponent(name);
|
|
254
|
+
const found = await ctx.get<{ creation_date?: string }>(
|
|
255
|
+
`/accounts/${ctx.accountId}/r2/buckets/${bucket}`,
|
|
256
|
+
);
|
|
257
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
258
|
+
return {
|
|
259
|
+
state: 'deployed',
|
|
260
|
+
consoleUrl: dash(ctx.accountId, `r2/default/buckets/${bucket}`),
|
|
261
|
+
};
|
|
262
|
+
},
|
|
263
|
+
|
|
264
|
+
d1_database: async (name, ctx) => {
|
|
265
|
+
// The endpoint accepts a database name as well as its id.
|
|
266
|
+
const found = await ctx.get<{ uuid?: string }>(
|
|
267
|
+
`/accounts/${ctx.accountId}/d1/database/${encodeURIComponent(name)}`,
|
|
268
|
+
);
|
|
269
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
270
|
+
const uuid = typeof found.result?.uuid === 'string' ? found.result.uuid : undefined;
|
|
271
|
+
return {
|
|
272
|
+
state: 'deployed',
|
|
273
|
+
...(uuid ? { resourceId: uuid, consoleUrl: dash(ctx.accountId, `workers/d1/databases/${uuid}`) } : {}),
|
|
274
|
+
};
|
|
275
|
+
},
|
|
276
|
+
|
|
277
|
+
kv_namespace: async (id, ctx) => {
|
|
278
|
+
const found = await ctx.get<{ id?: string }>(
|
|
279
|
+
`/accounts/${ctx.accountId}/storage/kv/namespaces/${encodeURIComponent(id)}`,
|
|
280
|
+
);
|
|
281
|
+
if (!found.ok) return missing(found) ? { state: 'not-found' } : { state: 'unknown', reason: found.message };
|
|
282
|
+
return {
|
|
283
|
+
state: 'deployed',
|
|
284
|
+
resourceId: id,
|
|
285
|
+
consoleUrl: dash(ctx.accountId, `workers/kv/namespaces/${encodeURIComponent(id)}`),
|
|
286
|
+
};
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
queue: async (name, ctx) => {
|
|
290
|
+
const listed = await ctx.get<Array<{ queue_id?: string; queue_name?: string }>>(
|
|
291
|
+
`/accounts/${ctx.accountId}/queues?name=${encodeURIComponent(name)}`,
|
|
292
|
+
);
|
|
293
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
294
|
+
if (!Array.isArray(listed.result)) return { state: 'unknown', reason: 'unexpected answer for queues' };
|
|
295
|
+
// The filter may be a prefix match; only an exact name counts.
|
|
296
|
+
const queue = listed.result.find((q) => q?.queue_name === name);
|
|
297
|
+
if (!queue) return { state: 'not-found' };
|
|
298
|
+
return {
|
|
299
|
+
state: 'deployed',
|
|
300
|
+
...(typeof queue.queue_id === 'string' ? { resourceId: queue.queue_id } : {}),
|
|
301
|
+
};
|
|
302
|
+
},
|
|
303
|
+
|
|
304
|
+
container: async (name, ctx) => {
|
|
305
|
+
const listed = await ctx.get<Array<{ id?: string; name?: string; created_at?: string }>>(
|
|
306
|
+
`/accounts/${ctx.accountId}/containers/applications?name=${encodeURIComponent(name)}`,
|
|
307
|
+
);
|
|
308
|
+
if (!listed.ok) return { state: 'unknown', reason: listed.message };
|
|
309
|
+
if (!Array.isArray(listed.result)) {
|
|
310
|
+
return { state: 'unknown', reason: 'unexpected answer for container applications' };
|
|
311
|
+
}
|
|
312
|
+
const app = listed.result.find((a) => a?.name === name);
|
|
313
|
+
if (!app) return { state: 'not-found' };
|
|
314
|
+
return {
|
|
315
|
+
state: 'deployed',
|
|
316
|
+
...(typeof app.id === 'string' ? { resourceId: app.id } : {}),
|
|
317
|
+
};
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
/** Cloudflare resource types a check can look at. */
|
|
322
|
+
export const CLOUDFLARE_OBSERVED_TYPES: readonly string[] = Object.keys(CHECKS);
|
|
323
|
+
|
|
324
|
+
/** What one run of checks learned. Nothing here has been stored. */
|
|
325
|
+
export interface InfraObserveResult {
|
|
326
|
+
/**
|
|
327
|
+
* One observation per resource that was looked at, `unknown` ones included.
|
|
328
|
+
* A host that already holds an observation for a key should pass these
|
|
329
|
+
* through {@link withoutUnknownOverwrites} before storing them.
|
|
330
|
+
*/
|
|
331
|
+
observations: InfraDeploymentObservation[];
|
|
332
|
+
/** Keys that were not looked at, with the reason. */
|
|
333
|
+
skipped: Array<{ resourceKey: string; reason: string }>;
|
|
334
|
+
/** Why some lookups could not be made, when any could not. */
|
|
335
|
+
failure?: string;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Look at the named Cloudflare resources and say what was seen.
|
|
340
|
+
*
|
|
341
|
+
* Three outcomes per resource, kept apart on purpose:
|
|
342
|
+
* - it is there → `deployed`, with whatever address and dashboard page it has;
|
|
343
|
+
* - Cloudflare says it does not exist → `not-found`;
|
|
344
|
+
* - the question could not be asked (auth, network) → `unknown`.
|
|
345
|
+
*
|
|
346
|
+
* Failures are per resource: a token that cannot read R2 still gets the
|
|
347
|
+
* Workers checked, and the R2 failure is reported in `failure`. Keys for other
|
|
348
|
+
* providers are ignored.
|
|
349
|
+
*/
|
|
350
|
+
export async function observeCloudflare(
|
|
351
|
+
resourceKeys: readonly string[],
|
|
352
|
+
access: CloudflareAccess,
|
|
353
|
+
deps: InfraObserveDeps = {},
|
|
354
|
+
): Promise<InfraObserveResult> {
|
|
355
|
+
const doFetch = deps.fetch ?? fetch;
|
|
356
|
+
const now = deps.now ?? (() => new Date());
|
|
357
|
+
const { token, accountId } = access;
|
|
358
|
+
|
|
359
|
+
const skipped: InfraObserveResult['skipped'] = [];
|
|
360
|
+
const targets: Array<{ key: string; resourceType: string; identifier: string }> = [];
|
|
361
|
+
for (const key of new Set(resourceKeys)) {
|
|
362
|
+
const parsed = parseKey(key);
|
|
363
|
+
if (!parsed || parsed.provider !== 'cloudflare') continue;
|
|
364
|
+
if (CHECKS[parsed.resourceType]) targets.push({ key, ...parsed });
|
|
365
|
+
else skipped.push({ resourceKey: key, reason: `${parsed.resourceType} is not checked yet` });
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const observedAt = now().toISOString();
|
|
369
|
+
const source = 'cloudflare-api';
|
|
370
|
+
let subdomain: Promise<string | undefined> | undefined;
|
|
371
|
+
const ctx: CheckContext = {
|
|
372
|
+
accountId,
|
|
373
|
+
get: (path) => cloudflareGet(path, token, doFetch),
|
|
374
|
+
workersSubdomain: () => {
|
|
375
|
+
subdomain ??= cloudflareGet<{ subdomain?: string }>(
|
|
376
|
+
`/accounts/${accountId}/workers/subdomain`,
|
|
377
|
+
token,
|
|
378
|
+
doFetch,
|
|
379
|
+
).then((sub) =>
|
|
380
|
+
sub.ok && typeof sub.result?.subdomain === 'string' ? sub.result.subdomain : undefined,
|
|
381
|
+
);
|
|
382
|
+
return subdomain;
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
const observations: InfraDeploymentObservation[] = [];
|
|
387
|
+
const failures = new Set<string>();
|
|
388
|
+
for (const { key, resourceType, identifier } of targets) {
|
|
389
|
+
let seen: Seen;
|
|
390
|
+
try {
|
|
391
|
+
seen = await CHECKS[resourceType]!(identifier, ctx);
|
|
392
|
+
} catch {
|
|
393
|
+
seen = { state: 'unknown', reason: `could not check ${resourceType}` };
|
|
394
|
+
}
|
|
395
|
+
if (seen.state === 'unknown') {
|
|
396
|
+
failures.add(`${resourceType.replace(/_/g, ' ')}: ${seen.reason}`);
|
|
397
|
+
observations.push({ resourceKey: key, status: 'unknown', observedAt, source });
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
if (seen.state === 'not-found') {
|
|
401
|
+
observations.push({ resourceKey: key, status: 'not-found', observedAt, source });
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
const { state: _state, ...facts } = seen;
|
|
405
|
+
observations.push({ resourceKey: key, status: 'deployed', ...facts, observedAt, source });
|
|
406
|
+
}
|
|
407
|
+
return {
|
|
408
|
+
observations,
|
|
409
|
+
skipped,
|
|
410
|
+
...(failures.size > 0 ? { failure: [...failures].join('; ') } : {}),
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Drop `unknown` observations for resources something is already known about.
|
|
416
|
+
* A failed check must not erase what was known: `unknown` is only worth
|
|
417
|
+
* keeping when it is the first thing said about a resource.
|
|
418
|
+
*/
|
|
419
|
+
export function withoutUnknownOverwrites(
|
|
420
|
+
observations: readonly InfraDeploymentObservation[],
|
|
421
|
+
alreadyKnown: ReadonlySet<string>,
|
|
422
|
+
): InfraDeploymentObservation[] {
|
|
423
|
+
return observations.filter(
|
|
424
|
+
(observation) => observation.status !== 'unknown' || !alreadyKnown.has(observation.resourceKey),
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* Read the answer of `wrangler auth token --json` — the credential of whoever
|
|
430
|
+
* is logged in to wrangler on this machine, refreshed by wrangler itself.
|
|
431
|
+
*
|
|
432
|
+
* Only a Bearer credential is usable here: an OAuth login or an API token. A
|
|
433
|
+
* global API key (key + email) is not, and reads as null, as does anything
|
|
434
|
+
* that is not wrangler's JSON.
|
|
435
|
+
*/
|
|
436
|
+
export function parseWranglerAuthToken(
|
|
437
|
+
stdout: string,
|
|
438
|
+
): { token: string; type: 'oauth' | 'api_token' } | null {
|
|
439
|
+
let parsed: unknown;
|
|
440
|
+
try {
|
|
441
|
+
parsed = JSON.parse(stdout);
|
|
442
|
+
} catch {
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
if (!isRecord(parsed)) return null;
|
|
446
|
+
const { type, token } = parsed;
|
|
447
|
+
if (type !== 'oauth' && type !== 'api_token') return null;
|
|
448
|
+
// A header value: refuse anything that could not have been a token.
|
|
449
|
+
if (typeof token !== 'string' || !/^[\x21-\x7e]{20,4096}$/.test(token)) return null;
|
|
450
|
+
return { token, type };
|
|
451
|
+
}
|
|
@@ -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
|
+
}
|