@intentius/behold 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/AGENTS.md +64 -2787
  2. package/README.md +78 -13
  3. package/THIRD_PARTY.md +6 -5
  4. package/dist/chant-KLLNQOCK.js +117 -0
  5. package/dist/choudoufu-chant-read-MJ6DK23L.js +36 -0
  6. package/dist/chunk-26K6QLVB.js +157 -0
  7. package/dist/chunk-4IETG5U7.js +267 -0
  8. package/dist/chunk-7DQDWJI5.js +46 -0
  9. package/dist/chunk-ANJ33KX4.js +78 -0
  10. package/dist/chunk-C7OMVDI5.js +124 -0
  11. package/dist/chunk-GG3SLEYM.js +30297 -0
  12. package/dist/chunk-GMCRBXPQ.js +15578 -0
  13. package/dist/chunk-IMX6PXXA.js +1019 -0
  14. package/dist/chunk-JHLNY324.js +232 -0
  15. package/dist/chunk-JJPU2DXX.js +54 -0
  16. package/dist/chunk-KUHU6T4P.js +2820 -0
  17. package/dist/chunk-OY4EF7ZO.js +5651 -0
  18. package/dist/chunk-XKWCGNT2.js +8139 -0
  19. package/dist/chunk-YO233FHU.js +136 -0
  20. package/dist/cli.js +491 -72879
  21. package/dist/config-XKQQ4ORG.js +69 -0
  22. package/dist/config-run-4IMSAYPX.js +418 -0
  23. package/dist/declaration-5NE7H5UD.js +6867 -0
  24. package/dist/index.js +99 -0
  25. package/dist/main-4PGA5RJS.js +2509 -0
  26. package/dist/mcp-W2CHVEPI.js +753 -0
  27. package/dist/object-store-H77QSRIZ.js +1033 -0
  28. package/dist/src-54PT4UC5.js +1189 -0
  29. package/dist/tree-W23HE2EZ.js +17 -0
  30. package/example-choudoufu-estate/chant.workspace.json +1 -1
  31. package/example-terraform-estate/README.md +2 -2
  32. package/example-terraform-estate/chant.workspace.json +1 -1
  33. package/example-three-cloud/chant.workspace.json +2 -2
  34. package/example-three-cloud/package-lock.json +32 -515
  35. package/example-three-cloud/package.json +5 -5
  36. package/package.json +26 -13
  37. package/schemas/graph/v1/graph.schema.json +140 -0
  38. package/web/app.js +9 -4
  39. package/web/boot-motion.js +6 -0
  40. package/web/cut-around.d.ts +30 -0
  41. package/web/cut-around.js +138 -0
  42. package/web/edge-weight.d.ts +8 -2
  43. package/web/edge-weight.js +34 -4
  44. package/web/edge-weight.test.js +36 -1
  45. package/web/index.html +8 -20
  46. package/web/neighbourhood.js +105 -0
  47. package/web/neighbourhood.test.js +131 -0
  48. package/web/outside-refs.js +515 -0
  49. package/web/outside-refs.test.js +249 -0
  50. package/web/theme-paint.js +14 -0
@@ -0,0 +1,1033 @@
1
+ import {
2
+ presignV4,
3
+ sha256Hex,
4
+ signV4
5
+ } from "./chunk-ANJ33KX4.js";
6
+ import {
7
+ CLOUD_TARGETS_ENV,
8
+ readTargetsFile
9
+ } from "./chunk-YO233FHU.js";
10
+ import "./chunk-7DQDWJI5.js";
11
+
12
+ // node_modules/@intentius/chant/dist/object-store/errors.js
13
+ var StoreError = class extends Error {
14
+ };
15
+ var StoreConflict = class extends StoreError {
16
+ };
17
+ var isStoreConflict = (e) => e instanceof StoreConflict || e instanceof Error && (e.name === "StoreConflict" || e.constructor.name === "StoreConflict");
18
+
19
+ // node_modules/@intentius/chant/dist/object-store/common.js
20
+ var PRESIGN_MAX_SECONDS = 7 * 24 * 3600;
21
+ function parseBucketUrl(url, setting = "the bucket") {
22
+ const u = url.trim().replace(/\/+$/, "");
23
+ let m = /^gs:\/\/([a-z0-9][a-z0-9._-]{1,221}[a-z0-9])$/.exec(u);
24
+ if (m)
25
+ return { kind: "gcs", bucket: m[1] };
26
+ m = /^az:\/\/([a-z0-9]{3,24})\/([a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){2,62})$/.exec(u);
27
+ if (m)
28
+ return { kind: "azure", account: m[1], container: m[2] };
29
+ m = /^(?:s3:\/\/)?([^/:\s]+)$/.exec(u);
30
+ if (m)
31
+ return { kind: "s3", bucket: m[1] };
32
+ throw new StoreError(`${setting} must be s3://<bucket>, gs://<bucket> or az://<account>/<container>, not ${url}`);
33
+ }
34
+ var bucketUrl = (b) => b.kind === "azure" ? `az://${b.account}/${b.container}` : `${b.kind === "gcs" ? "gs" : "s3"}://${b.bucket}`;
35
+ var encodePath = (key) => key.split("/").map(encodeStrict).join("/");
36
+ var encodeStrict = (v) => encodeURIComponent(v).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
37
+ var xmlText = (xml, tag) => {
38
+ const m = new RegExp(`<${tag}>([^<]*)</${tag}>`).exec(xml);
39
+ return m?.[1].replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&").trim();
40
+ };
41
+ var xmlBlocks = (xml, tag) => [...xml.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "g"))].map((m) => m[1]);
42
+ var isoSeconds = (d) => d.toISOString().replace(/\.\d{3}Z$/, "Z");
43
+ var defaultFetch = (url, init) => fetch(url, init);
44
+ function tradedVars(env, cloud, id) {
45
+ const path = env[CLOUD_TARGETS_ENV];
46
+ if (!path)
47
+ return void 0;
48
+ let vars;
49
+ try {
50
+ vars = readTargetsFile(path).clouds[cloud]?.vars[id];
51
+ } catch (e) {
52
+ throw new StoreError(e.message);
53
+ }
54
+ if (!vars)
55
+ throw new StoreError(`the job's trade left no credentials for ${id}`);
56
+ return vars;
57
+ }
58
+ function tradedIdentities(env, cloud) {
59
+ const path = env[CLOUD_TARGETS_ENV];
60
+ if (!path)
61
+ return {};
62
+ try {
63
+ return readTargetsFile(path).clouds[cloud]?.vars ?? {};
64
+ } catch (e) {
65
+ throw new StoreError(e.message);
66
+ }
67
+ }
68
+
69
+ // node_modules/@intentius/chant/dist/object-store/s3.js
70
+ import { readFileSync } from "node:fs";
71
+ function parseBucket(url, setting = "the bucket") {
72
+ const m = /^(?:s3:\/\/)?([^/]+)\/?$/.exec(url.trim());
73
+ if (!m)
74
+ throw new StoreError(`${setting} must be s3://<bucket>, not ${url}`);
75
+ return m[1];
76
+ }
77
+ function s3FromEnv(where, env = process.env) {
78
+ const setting = where.setting ?? "the bucket";
79
+ const roleSetting = where.roleSetting ?? "the role";
80
+ const hints = where.hints ?? {};
81
+ const endpoint = where.endpoint ?? env.AWS_ENDPOINT_URL_S3 ?? env.AWS_ENDPOINT_URL;
82
+ const region = env.AWS_REGION || env.AWS_DEFAULT_REGION || "us-east-1";
83
+ const at = {
84
+ bucket: parseBucket(where.bucket, setting),
85
+ ...endpoint ? { endpoint: endpoint.replace(/\/+$/, "") } : {},
86
+ region
87
+ };
88
+ const tokenFile = env.AWS_WEB_IDENTITY_TOKEN_FILE;
89
+ const assume = (roleArn) => ({
90
+ ...at,
91
+ webIdentity: {
92
+ roleArn,
93
+ tokenFile,
94
+ sessionName: env.AWS_ROLE_SESSION_NAME || where.sessionName || "chant",
95
+ endpoint: (env.AWS_ENDPOINT_URL_STS || env.AWS_ENDPOINT_URL || `https://sts.${region}.amazonaws.com`).replace(/\/+$/, "")
96
+ }
97
+ });
98
+ if (where.role && env[CLOUD_TARGETS_ENV] && !tokenFile) {
99
+ const c = tradedVars(env, "aws", where.role);
100
+ return { ...at, accessKeyId: c.AWS_ACCESS_KEY_ID, secretAccessKey: c.AWS_SECRET_ACCESS_KEY, ...c.AWS_SESSION_TOKEN ? { sessionToken: c.AWS_SESSION_TOKEN } : {} };
101
+ }
102
+ if (where.role) {
103
+ if (!tokenFile)
104
+ throw new StoreError(`${roleSetting} is set, but AWS_WEB_IDENTITY_TOKEN_FILE is not: the job needs an OIDC token to assume ${where.role}${hints.oidc ? `, which a job with ${hints.oidc} gets` : ""}`);
105
+ return assume(where.role);
106
+ }
107
+ const accessKeyId = env.AWS_ACCESS_KEY_ID;
108
+ const secretAccessKey = env.AWS_SECRET_ACCESS_KEY;
109
+ if (accessKeyId && secretAccessKey)
110
+ return { ...at, accessKeyId, secretAccessKey, ...env.AWS_SESSION_TOKEN ? { sessionToken: env.AWS_SESSION_TOKEN } : {} };
111
+ if (env.AWS_ROLE_ARN && tokenFile)
112
+ return assume(env.AWS_ROLE_ARN);
113
+ throw new StoreError(`${setting} is set, but the job has no credentials for it: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, or AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE${hints.oidc ? ` (a job with ${hints.oidc} sets both)` : ""}, or ${roleSetting}`);
114
+ }
115
+ async function assumeRoleWithWebIdentity(w, fetchFn, readToken = (f) => readFileSync(f, "utf-8")) {
116
+ let token;
117
+ try {
118
+ token = readToken(w.tokenFile).trim();
119
+ } catch (e) {
120
+ throw new StoreError(`cannot read the OIDC token in ${w.tokenFile}: ${e.message}`);
121
+ }
122
+ if (!token)
123
+ throw new StoreError(`the OIDC token file ${w.tokenFile} is empty`);
124
+ const body = new URLSearchParams({
125
+ Action: "AssumeRoleWithWebIdentity",
126
+ Version: "2011-06-15",
127
+ RoleArn: w.roleArn,
128
+ RoleSessionName: w.sessionName,
129
+ WebIdentityToken: token
130
+ }).toString();
131
+ const res = await fetchFn(`${w.endpoint}/`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded; charset=utf-8", accept: "application/xml" }, body });
132
+ const xml = await res.text();
133
+ if (!res.ok) {
134
+ const why3 = [xmlText(xml, "Code"), xmlText(xml, "Message")].filter(Boolean).join(": ") || xml.slice(0, 300);
135
+ throw new StoreError(`AssumeRoleWithWebIdentity for ${w.roleArn}: ${res.status} ${why3}`);
136
+ }
137
+ const accessKeyId = xmlText(xml, "AccessKeyId");
138
+ const secretAccessKey = xmlText(xml, "SecretAccessKey");
139
+ const sessionToken = xmlText(xml, "SessionToken");
140
+ if (!accessKeyId || !secretAccessKey || !sessionToken)
141
+ throw new StoreError(`AssumeRoleWithWebIdentity for ${w.roleArn} answered without credentials`);
142
+ const expires = xmlText(xml, "Expiration");
143
+ return { accessKeyId, secretAccessKey, sessionToken, ...expires && !Number.isNaN(Date.parse(expires)) ? { expiration: new Date(expires) } : {} };
144
+ }
145
+ function signRequest(t, method, key, body, now = /* @__PURE__ */ new Date(), contentType, extra = {}) {
146
+ const url = objectUrl(t, key);
147
+ return { url, headers: sign(t, method, url, { ...contentType ? { "content-type": contentType } : {}, ...extra }, sha256Hex(body), now) };
148
+ }
149
+ function sign(t, method, rawUrl, extra, payload, now, service = "s3") {
150
+ return signV4({ method, url: rawUrl, headers: extra, body: "", payloadHash: payload, contentSha256: true, omitHost: true, region: t.region, service, credentials: t, now });
151
+ }
152
+ var objectUrl = (t, key) => `${t.endpoint ? `${t.endpoint}/${t.bucket}` : `https://${t.bucket}.s3.${t.region}.amazonaws.com`}/${encodePath(key)}`;
153
+ function presign(t, rawUrl, seconds, now) {
154
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > PRESIGN_MAX_SECONDS)
155
+ throw new StoreError(`a presigned link lives 1 to ${PRESIGN_MAX_SECONDS} seconds, not ${seconds}`);
156
+ return presignV4({ url: rawUrl, region: t.region, service: "s3", credentials: t, seconds, now });
157
+ }
158
+ var S3Client = class {
159
+ constructor(target, fetchFn = defaultFetch) {
160
+ this.target = target;
161
+ this.fetchFn = fetchFn;
162
+ this.conditional = true;
163
+ }
164
+ get location() {
165
+ return `s3://${this.target.bucket}`;
166
+ }
167
+ /** Static keys as given; a web identity's keys once per client, again a minute before they expire. */
168
+ async signer() {
169
+ const t = this.target;
170
+ if (!("webIdentity" in t))
171
+ return t;
172
+ const assume = () => this.creds = assumeRoleWithWebIdentity(t.webIdentity, this.fetchFn).catch((e) => {
173
+ this.creds = void 0;
174
+ throw e;
175
+ });
176
+ let held = await (this.creds ?? assume());
177
+ if (held.expiration && held.expiration.getTime() - Date.now() < 6e4)
178
+ held = await assume();
179
+ const { accessKeyId, secretAccessKey, sessionToken } = held;
180
+ return { bucket: t.bucket, ...t.endpoint ? { endpoint: t.endpoint } : {}, region: t.region, accessKeyId, secretAccessKey, ...sessionToken ? { sessionToken } : {} };
181
+ }
182
+ /**
183
+ * Write an object; with `when`, only if it still holds. A write that lost
184
+ * throws S3Conflict. The answer carries the new ETag when the store sends one.
185
+ */
186
+ async put(key, body, contentType, when) {
187
+ const cond = !when || !this.conditional ? {} : "ifMatch" in when ? { "if-match": when.ifMatch } : { "if-none-match": "*" };
188
+ const { url, headers } = signRequest(await this.signer(), "PUT", key, body, /* @__PURE__ */ new Date(), contentType, cond);
189
+ const res = await this.fetchFn(url, { method: "PUT", headers, body });
190
+ if (res.status === 501 && Object.keys(cond).length) {
191
+ this.conditional = false;
192
+ return this.put(key, body, contentType);
193
+ }
194
+ if (res.status === 412 || res.status === 409 && Object.keys(cond).length)
195
+ throw new StoreConflict(`PUT s3://${this.target.bucket}/${key}: ${res.status}, it changed since it was read`);
196
+ if (!res.ok)
197
+ throw new StoreError(`PUT s3://${this.target.bucket}/${key}: ${res.status} ${(await res.text()).slice(0, 300)}`);
198
+ const etag = res.headers?.get("etag") ?? void 0;
199
+ return etag ? { etag } : {};
200
+ }
201
+ /** The object's text and ETag, or no text when there is none. */
202
+ async read(key) {
203
+ const { url, headers } = signRequest(await this.signer(), "GET", key, "");
204
+ const res = await this.fetchFn(url, { method: "GET", headers });
205
+ if (res.status === 404)
206
+ return {};
207
+ if (!res.ok)
208
+ throw new StoreError(`GET s3://${this.target.bucket}/${key}: ${res.status} ${(await res.text()).slice(0, 300)}`);
209
+ const etag = res.headers?.get("etag") ?? void 0;
210
+ return { body: await res.text(), ...etag ? { etag } : {} };
211
+ }
212
+ /**
213
+ * A presigned GET of `key` for `seconds`. `expires` is when it stops
214
+ * working: then, or sooner when the keys that signed it expire first (an
215
+ * assumed role's session).
216
+ */
217
+ async presign(key, seconds, now = /* @__PURE__ */ new Date()) {
218
+ const t = await this.signer();
219
+ const url = presign(t, objectUrl(t, key), seconds, now);
220
+ let expires = new Date(now.getTime() + seconds * 1e3);
221
+ const held = this.creds ? await this.creds : void 0;
222
+ if (held?.expiration && held.expiration < expires)
223
+ expires = held.expiration;
224
+ return { url, expires };
225
+ }
226
+ /** The object's text, or undefined when there is none. */
227
+ async get(key) {
228
+ return (await this.read(key)).body;
229
+ }
230
+ /**
231
+ * The object's metadata and never its body: whether it exists, its ETag,
232
+ * and its version id when the bucket keeps versions. S3 sends no version id
233
+ * for a bucket whose versioning was never on, and `null` for an object
234
+ * written while it was suspended; both read as no version.
235
+ */
236
+ async head(key) {
237
+ const { url, headers } = signRequest(await this.signer(), "HEAD", key, "");
238
+ const res = await this.fetchFn(url, { method: "HEAD", headers });
239
+ if (res.status === 404)
240
+ return { exists: false };
241
+ if (!res.ok)
242
+ throw new StoreError(`HEAD s3://${this.target.bucket}/${key}: ${res.status}`);
243
+ const etag = res.headers?.get("etag") ?? void 0;
244
+ const version = res.headers?.get("x-amz-version-id") ?? void 0;
245
+ return { exists: true, ...etag ? { etag } : {}, ...version && version !== "null" ? { versionId: version } : {} };
246
+ }
247
+ /**
248
+ * Write an object only when there is none (If-None-Match: *): true when
249
+ * this write made it, false when one was there. Unlike put, a store that
250
+ * refuses the condition fails the write: a lock must never be taken
251
+ * unconditionally.
252
+ */
253
+ async putIfAbsent(key, body, contentType) {
254
+ const { url, headers } = signRequest(await this.signer(), "PUT", key, body, /* @__PURE__ */ new Date(), contentType, { "if-none-match": "*" });
255
+ const res = await this.fetchFn(url, { method: "PUT", headers, body });
256
+ if (res.status === 412 || res.status === 409)
257
+ return false;
258
+ if (res.status === 501)
259
+ throw new StoreError(`PUT s3://${this.target.bucket}/${key}: the store does not take a conditional write (501)`);
260
+ if (!res.ok)
261
+ throw new StoreError(`PUT s3://${this.target.bucket}/${key}: ${res.status} ${(await res.text()).slice(0, 300)}`);
262
+ return true;
263
+ }
264
+ /** One version of an object's text, by its version id; undefined when there is no such version. */
265
+ async readVersion(key, versionId) {
266
+ const t = await this.signer();
267
+ const url = `${objectUrl(t, key)}?versionId=${encodeStrict(versionId)}`;
268
+ const res = await this.fetchFn(url, { method: "GET", headers: sign(t, "GET", url, {}, sha256Hex(""), /* @__PURE__ */ new Date()) });
269
+ if (res.status === 404)
270
+ return void 0;
271
+ if (!res.ok)
272
+ throw new StoreError(`GET s3://${this.target.bucket}/${key}?versionId=${versionId}: ${res.status} ${(await res.text()).slice(0, 300)}`);
273
+ return res.text();
274
+ }
275
+ /** Whether a version of an object is in the bucket, from a HEAD by its version id: its metadata, never its body. */
276
+ async hasVersion(key, versionId) {
277
+ const t = await this.signer();
278
+ const url = `${objectUrl(t, key)}?versionId=${encodeStrict(versionId)}`;
279
+ const res = await this.fetchFn(url, { method: "HEAD", headers: sign(t, "HEAD", url, {}, sha256Hex(""), /* @__PURE__ */ new Date()) });
280
+ if (res.status === 404 || res.status === 400)
281
+ return false;
282
+ if (!res.ok)
283
+ throw new StoreError(`HEAD s3://${this.target.bucket}/${key}?versionId=${versionId}: ${res.status}`);
284
+ return true;
285
+ }
286
+ /**
287
+ * Every version the bucket keeps of one object, delete markers too, from
288
+ * ListObjectVersions: each one's id, its LastModified and whether it is the
289
+ * latest. Metadata only; it needs s3:ListBucketVersions. A bucket in
290
+ * another region than the client's answers 301 with its region, and the
291
+ * list is asked there.
292
+ */
293
+ async listVersions(key) {
294
+ const t = await this.signer();
295
+ let region = t.region;
296
+ const out = [];
297
+ let marker;
298
+ let redirected = false;
299
+ for (let page = 0; page < 1e3; page++) {
300
+ const at = { ...t, region };
301
+ const query = [`prefix=${encodeStrict(key)}`, "versions=", ...marker ? [`key-marker=${encodeStrict(marker.key)}`, `version-id-marker=${encodeStrict(marker.version)}`] : []].join("&");
302
+ const url = `${objectUrl(at, "")}?${query}`;
303
+ const res = await this.fetchFn(url, { method: "GET", headers: sign(at, "GET", url, {}, sha256Hex(""), /* @__PURE__ */ new Date()) });
304
+ const moved = res.headers?.get("x-amz-bucket-region") ?? void 0;
305
+ if ((res.status === 301 || res.status === 400) && moved && moved !== region && !t.endpoint && !redirected) {
306
+ region = moved;
307
+ redirected = true;
308
+ continue;
309
+ }
310
+ const xml = await res.text();
311
+ if (!res.ok)
312
+ throw new StoreError(`list the versions of s3://${this.target.bucket}/${key}: ${res.status} ${[xmlText(xml, "Code"), xmlText(xml, "Message")].filter(Boolean).join(": ") || xml.slice(0, 300)}`);
313
+ for (const [tag, deleted] of [["Version", false], ["DeleteMarker", true]]) {
314
+ for (const b of xmlBlocks(xml, tag)) {
315
+ const id = xmlText(b, "VersionId");
316
+ const when = xmlText(b, "LastModified");
317
+ if (xmlText(b, "Key") !== key || !id || id === "null" || !when)
318
+ continue;
319
+ out.push({ version_id: id, written_at: new Date(when).toISOString(), latest: xmlText(b, "IsLatest") === "true", ...deleted ? { deleted: true } : {} });
320
+ }
321
+ }
322
+ const nextKey = xmlText(xml, "NextKeyMarker");
323
+ const nextVersion = xmlText(xml, "NextVersionIdMarker");
324
+ if (xmlText(xml, "IsTruncated") !== "true" || !nextKey || !nextVersion)
325
+ break;
326
+ marker = { key: nextKey, version: nextVersion };
327
+ }
328
+ return out.sort((a, b) => Date.parse(b.written_at) - Date.parse(a.written_at));
329
+ }
330
+ /** Delete an object. One that is not there is deleted already. */
331
+ async remove(key) {
332
+ const { url, headers } = signRequest(await this.signer(), "DELETE", key, "");
333
+ const res = await this.fetchFn(url, { method: "DELETE", headers });
334
+ if (!res.ok && res.status !== 404)
335
+ throw new StoreError(`DELETE s3://${this.target.bucket}/${key}: ${res.status} ${(await res.text()).slice(0, 300)}`);
336
+ }
337
+ };
338
+
339
+ // node_modules/@intentius/chant/dist/object-store/gcs.js
340
+ import { createHash, createSign } from "node:crypto";
341
+ import { readFileSync as readFileSync2 } from "node:fs";
342
+ var GCS_ENDPOINT = "https://storage.googleapis.com";
343
+ var IAM_CREDENTIALS = "https://iamcredentials.googleapis.com";
344
+ var CLOUD_PLATFORM = "https://www.googleapis.com/auth/cloud-platform";
345
+ var READ_WRITE = "https://www.googleapis.com/auth/devstorage.read_write";
346
+ function gcsFromEnv(where, env = process.env) {
347
+ const file = env.GOOGLE_APPLICATION_CREDENTIALS;
348
+ if (!file && env.GOOGLE_OAUTH_ACCESS_TOKEN && env[CLOUD_TARGETS_ENV]) {
349
+ const signAs = Object.entries(tradedIdentities(env, "gcp")).find(([, v]) => v.GOOGLE_OAUTH_ACCESS_TOKEN === env.GOOGLE_OAUTH_ACCESS_TOKEN)?.[0];
350
+ return { bucket: where.bucket, endpoint: (where.endpoint ?? GCS_ENDPOINT).replace(/\/+$/, ""), accessToken: env.GOOGLE_OAUTH_ACCESS_TOKEN, ...signAs ? { signAs } : {} };
351
+ }
352
+ if (!file)
353
+ throw new StoreError(`${where.setting ?? "the bucket"} is gs://${where.bucket}, but the job has no credentials for it: ${where.hints?.gcp ? `give the job ${where.hints.gcp} (it sets GOOGLE_APPLICATION_CREDENTIALS), or set` : "set"} GOOGLE_APPLICATION_CREDENTIALS to a credentials file${where.hints?.gcp ? "" : " (a job's OIDC setup writes one)"}`);
354
+ return { bucket: where.bucket, endpoint: (where.endpoint ?? GCS_ENDPOINT).replace(/\/+$/, ""), credentialsFile: file };
355
+ }
356
+ var b64url = (b) => Buffer.from(b).toString("base64url");
357
+ function selfSignedJwt(key, now) {
358
+ const iat = Math.floor(now.getTime() / 1e3);
359
+ const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT", ...key.private_key_id ? { kid: key.private_key_id } : {} }));
360
+ const body = b64url(JSON.stringify({ iss: key.client_email, sub: key.client_email, scope: READ_WRITE, iat, exp: iat + 3600 }));
361
+ return `${head}.${body}.${createSign("RSA-SHA256").update(`${head}.${body}`).sign(key.private_key).toString("base64url")}`;
362
+ }
363
+ var impersonated = (url) => {
364
+ const m = /\/serviceAccounts\/([^/:]+):generateAccessToken$/.exec(url);
365
+ return m ? decodeURIComponent(m[1]) : void 0;
366
+ };
367
+ async function signedUrl(endpoint, bucket, key, email, seconds, now, sign2) {
368
+ const url = new URL(`${endpoint}/${bucket}/${encodePath(key)}`);
369
+ const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
370
+ const scope = `${stamp.slice(0, 8)}/auto/storage/goog4_request`;
371
+ const params = {
372
+ "X-Goog-Algorithm": "GOOG4-RSA-SHA256",
373
+ "X-Goog-Credential": `${email}/${scope}`,
374
+ "X-Goog-Date": stamp,
375
+ "X-Goog-Expires": String(seconds),
376
+ "X-Goog-SignedHeaders": "host"
377
+ };
378
+ const query = Object.keys(params).sort().map((k) => `${encodeStrict(k)}=${encodeStrict(params[k])}`).join("&");
379
+ const canonical = ["GET", url.pathname, query, `host:${url.host}`, "", "host", "UNSIGNED-PAYLOAD"].join("\n");
380
+ const toSign = ["GOOG4-RSA-SHA256", stamp, scope, createHash("sha256").update(canonical).digest("hex")].join("\n");
381
+ return `${url.origin}${url.pathname}?${query}&X-Goog-Signature=${(await sign2(toSign)).toString("hex")}`;
382
+ }
383
+ var why = (text) => {
384
+ try {
385
+ const j = JSON.parse(text);
386
+ if (typeof j.error === "object" && j.error?.message)
387
+ return j.error.message;
388
+ if (typeof j.error === "string")
389
+ return [j.error, j.error_description].filter(Boolean).join(": ");
390
+ } catch {
391
+ }
392
+ return text.slice(0, 300);
393
+ };
394
+ var GcsClient = class {
395
+ constructor(target, fetchFn = defaultFetch, readFile = (f) => readFileSync2(f, "utf-8")) {
396
+ this.target = target;
397
+ this.fetchFn = fetchFn;
398
+ this.readFile = readFile;
399
+ }
400
+ get location() {
401
+ return `gs://${this.target.bucket}`;
402
+ }
403
+ /** Where the credentials come from, for messages. */
404
+ get source() {
405
+ return this.target.credentialsFile ?? "the backend's credentials";
406
+ }
407
+ credentials() {
408
+ if (this.creds)
409
+ return this.creds;
410
+ const file = this.source;
411
+ let c;
412
+ try {
413
+ c = JSON.parse(this.target.credentialsJson ?? this.readFile(this.target.credentialsFile ?? ""));
414
+ } catch (e) {
415
+ throw new StoreError(`cannot read the credentials in ${file}: ${e.message}`);
416
+ }
417
+ if (c.type === "external_account" && c.token_url && c.audience && c.credential_source && (c.credential_source.file || c.credential_source.url))
418
+ return this.creds = c;
419
+ if (c.type === "service_account" && c.client_email && c.private_key)
420
+ return this.creds = c;
421
+ throw new StoreError(`${file} is not an external_account file with a credential_source file or url, nor a service_account key`);
422
+ }
423
+ async post(url, headers, body, what) {
424
+ const res = await this.fetchFn(url, { method: "POST", headers, body });
425
+ const text = await res.text();
426
+ if (!res.ok)
427
+ throw new StoreError(`${what}: ${res.status} ${why(text)}`);
428
+ try {
429
+ return JSON.parse(text);
430
+ } catch {
431
+ throw new StoreError(`${what}: the answer is not JSON`);
432
+ }
433
+ }
434
+ /** The job's OIDC token, from the file or URL the credentials name. */
435
+ async subjectToken(c) {
436
+ const src = c.credential_source;
437
+ let text;
438
+ if (src.file) {
439
+ try {
440
+ text = this.readFile(src.file);
441
+ } catch (e) {
442
+ throw new StoreError(`cannot read the OIDC token in ${src.file}: ${e.message}`);
443
+ }
444
+ } else {
445
+ const res = await this.fetchFn(src.url, { method: "GET", headers: src.headers ?? {} });
446
+ text = await res.text();
447
+ if (!res.ok)
448
+ throw new StoreError(`the OIDC token at ${src.url.split("?")[0]}: ${res.status} ${why(text)}`);
449
+ }
450
+ const field = src.format?.type === "json" ? src.format.subject_token_field_name : void 0;
451
+ let token = text.trim();
452
+ if (field) {
453
+ try {
454
+ token = String(JSON.parse(text)[field] ?? "");
455
+ } catch {
456
+ throw new StoreError(`the job's OIDC token is not JSON with ${field}`);
457
+ }
458
+ }
459
+ if (!token)
460
+ throw new StoreError(`the job's OIDC token is empty`);
461
+ return token;
462
+ }
463
+ /** STS's federated token, then the impersonated service account's, when the credentials name one. */
464
+ async exchange(c) {
465
+ const sts = await this.post(c.token_url, { "content-type": "application/x-www-form-urlencoded" }, new URLSearchParams({
466
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
467
+ audience: c.audience,
468
+ scope: CLOUD_PLATFORM,
469
+ requested_token_type: "urn:ietf:params:oauth:token-type:access_token",
470
+ subject_token: await this.subjectToken(c),
471
+ subject_token_type: c.subject_token_type
472
+ }).toString(), `Google STS refused the OIDC token for ${c.audience}`);
473
+ if (typeof sts.access_token !== "string")
474
+ throw new StoreError(`Google STS answered without a token`);
475
+ const fed = { token: sts.access_token, expires: Date.now() + Number(sts.expires_in ?? 3600) * 1e3 };
476
+ if (!c.service_account_impersonation_url)
477
+ return fed;
478
+ const sa = await this.post(c.service_account_impersonation_url, { "content-type": "application/json", authorization: `Bearer ${fed.token}` }, JSON.stringify({ scope: [CLOUD_PLATFORM], lifetime: "3600s" }), `impersonating ${impersonated(c.service_account_impersonation_url) ?? "the service account"}`);
479
+ if (typeof sa.accessToken !== "string")
480
+ throw new StoreError(`IAM answered the impersonation without a token`);
481
+ const at = typeof sa.expireTime === "string" ? Date.parse(sa.expireTime) : NaN;
482
+ return { token: sa.accessToken, expires: Number.isNaN(at) ? Date.now() + 36e5 : at };
483
+ }
484
+ /** The identity's own token: the one the target gives, a key's self-signed JWT, or STS's for the OIDC token. */
485
+ async own() {
486
+ if (this.target.accessToken)
487
+ return { token: this.target.accessToken, expires: Date.now() + 36e5 };
488
+ const c = this.credentials();
489
+ return c.type === "service_account" ? { token: selfSignedJwt(c, /* @__PURE__ */ new Date()), expires: Date.now() + 36e5 } : this.exchange(c);
490
+ }
491
+ /** The token of the service account the target impersonates, asked for with the identity's own. */
492
+ async impersonating(sa) {
493
+ const base = await this.own();
494
+ const r = await this.post(`${(this.target.iamEndpoint ?? IAM_CREDENTIALS).replace(/\/+$/, "")}/v1/projects/-/serviceAccounts/${encodeURIComponent(sa)}:generateAccessToken`, { "content-type": "application/json", authorization: `Bearer ${base.token}` }, JSON.stringify({ scope: [CLOUD_PLATFORM], lifetime: "3600s" }), `impersonating ${sa}, which needs Service Account Token Creator for the identity`);
495
+ if (typeof r.accessToken !== "string")
496
+ throw new StoreError(`IAM answered the impersonation of ${sa} without a token`);
497
+ const at = typeof r.expireTime === "string" ? Date.parse(r.expireTime) : NaN;
498
+ return { token: r.accessToken, expires: Number.isNaN(at) ? Date.now() + 36e5 : at };
499
+ }
500
+ /** An access token: once per client, again a minute before it expires. */
501
+ async bearer() {
502
+ const sa = this.target.impersonate;
503
+ const fresh = () => sa ? this.impersonating(sa) : this.own();
504
+ const again = () => this.token = fresh().catch((e) => {
505
+ this.token = void 0;
506
+ throw e;
507
+ });
508
+ let held = await (this.token ?? again());
509
+ if (held.expires - Date.now() < 6e4)
510
+ held = await again();
511
+ return held.token;
512
+ }
513
+ /** The identity's access token and when it expires, for a re-plan's trade (../oidc-trade.ts). */
514
+ async identityToken() {
515
+ return this.target.impersonate ? this.impersonating(this.target.impersonate) : this.own();
516
+ }
517
+ async put(key, body, contentType, when) {
518
+ const t = this.target;
519
+ const gen = !when ? "" : "ifMatch" in when ? when.ifMatch : "0";
520
+ const url = `${t.endpoint}/upload/storage/v1/b/${encodeURIComponent(t.bucket)}/o?uploadType=media&name=${encodeStrict(key)}${gen ? `&ifGenerationMatch=${encodeStrict(gen)}` : ""}`;
521
+ const res = await this.fetchFn(url, { method: "POST", headers: { "content-type": contentType, authorization: `Bearer ${await this.bearer()}` }, body });
522
+ if (res.status === 412)
523
+ throw new StoreConflict(`PUT ${this.location}/${key}: 412, it changed since it was read`);
524
+ const text = await res.text();
525
+ if (!res.ok)
526
+ throw new StoreError(`PUT ${this.location}/${key}: ${res.status} ${why(text)}`);
527
+ let generation;
528
+ try {
529
+ generation = JSON.parse(text).generation;
530
+ } catch {
531
+ }
532
+ return generation !== void 0 ? { etag: String(generation) } : {};
533
+ }
534
+ async read(key) {
535
+ const t = this.target;
536
+ const url = `${t.endpoint}/storage/v1/b/${encodeURIComponent(t.bucket)}/o/${encodeStrict(key)}?alt=media`;
537
+ const res = await this.fetchFn(url, { method: "GET", headers: { authorization: `Bearer ${await this.bearer()}` } });
538
+ if (res.status === 404)
539
+ return {};
540
+ if (!res.ok)
541
+ throw new StoreError(`GET ${this.location}/${key}: ${res.status} ${why(await res.text())}`);
542
+ const generation = res.headers?.get("x-goog-generation") ?? void 0;
543
+ return { body: await res.text(), ...generation ? { etag: generation } : {} };
544
+ }
545
+ async get(key) {
546
+ return (await this.read(key)).body;
547
+ }
548
+ objectUrl(key) {
549
+ return `${this.target.endpoint}/storage/v1/b/${encodeURIComponent(this.target.bucket)}/o/${encodeStrict(key)}`;
550
+ }
551
+ /** An object's metadata and never its body: whether it is there, and its generation. */
552
+ async head(key, generation) {
553
+ const url = `${this.objectUrl(key)}${generation ? `?generation=${encodeStrict(generation)}` : ""}`;
554
+ const res = await this.fetchFn(url, { method: "GET", headers: { authorization: `Bearer ${await this.bearer()}` } });
555
+ const text = await res.text();
556
+ if (res.status === 404 || generation && res.status === 400)
557
+ return { exists: false };
558
+ if (!res.ok)
559
+ throw new StoreError(`GET ${this.location}/${key} metadata: ${res.status} ${why(text)}`);
560
+ let g;
561
+ try {
562
+ g = JSON.parse(text).generation;
563
+ } catch {
564
+ }
565
+ return { exists: true, ...g !== void 0 && g !== null && g !== "" ? { generation: String(g) } : {} };
566
+ }
567
+ /** One generation of an object's text; undefined when the bucket holds no such generation. */
568
+ async readGeneration(key, generation) {
569
+ const url = `${this.objectUrl(key)}?alt=media&generation=${encodeStrict(generation)}`;
570
+ const res = await this.fetchFn(url, { method: "GET", headers: { authorization: `Bearer ${await this.bearer()}` } });
571
+ if (res.status === 404 || res.status === 400)
572
+ return void 0;
573
+ if (!res.ok)
574
+ throw new StoreError(`GET ${this.location}/${key}#${generation}: ${res.status} ${why(await res.text())}`);
575
+ return res.text();
576
+ }
577
+ /** Whether the bucket keeps each generation of an object (object versioning); undefined when the identity may not read the bucket's settings. */
578
+ async versioning() {
579
+ const url = `${this.target.endpoint}/storage/v1/b/${encodeURIComponent(this.target.bucket)}?fields=versioning`;
580
+ const res = await this.fetchFn(url, { method: "GET", headers: { authorization: `Bearer ${await this.bearer()}` } });
581
+ const text = await res.text();
582
+ if (res.status === 403 || res.status === 401)
583
+ return void 0;
584
+ if (!res.ok)
585
+ throw new StoreError(`GET ${this.location} settings: ${res.status} ${why(text)}`);
586
+ try {
587
+ return JSON.parse(text).versioning?.enabled === true;
588
+ } catch {
589
+ return void 0;
590
+ }
591
+ }
592
+ /**
593
+ * Every generation the bucket keeps of one object, from an object listing
594
+ * with `versions=true`: each one's generation, when it was written
595
+ * (`timeCreated`) and whether it is live (no `timeDeleted`). Metadata only;
596
+ * it needs storage.objects.list on the bucket.
597
+ */
598
+ async listVersions(key) {
599
+ const out = [];
600
+ let token;
601
+ for (let page = 0; page < 1e3; page++) {
602
+ const url = `${this.target.endpoint}/storage/v1/b/${encodeURIComponent(this.target.bucket)}/o?prefix=${encodeStrict(key)}&versions=true&fields=${encodeStrict("items(name,generation,timeCreated,timeDeleted),nextPageToken")}${token ? `&pageToken=${encodeStrict(token)}` : ""}`;
603
+ const res = await this.fetchFn(url, { method: "GET", headers: { authorization: `Bearer ${await this.bearer()}` } });
604
+ const text = await res.text();
605
+ if (!res.ok)
606
+ throw new StoreError(`list the generations of ${this.location}/${key}: ${res.status} ${why(text)}`);
607
+ let doc;
608
+ try {
609
+ doc = JSON.parse(text);
610
+ } catch {
611
+ throw new StoreError(`list the generations of ${this.location}/${key}: the answer is not JSON`);
612
+ }
613
+ for (const i of doc.items ?? []) {
614
+ if (i.name !== key || i.generation === void 0 || typeof i.timeCreated !== "string")
615
+ continue;
616
+ out.push({ version_id: String(i.generation), written_at: new Date(i.timeCreated).toISOString(), latest: i.timeDeleted === void 0 });
617
+ }
618
+ token = typeof doc.nextPageToken === "string" && doc.nextPageToken !== "" ? doc.nextPageToken : void 0;
619
+ if (!token)
620
+ break;
621
+ }
622
+ return out.sort((a, b) => Date.parse(b.written_at) - Date.parse(a.written_at));
623
+ }
624
+ /** Write an object only when there is none (ifGenerationMatch=0): true when this write made it, false when one was there. */
625
+ async putIfAbsent(key, body, contentType) {
626
+ try {
627
+ await this.put(key, body, contentType, { ifNoneMatch: "*" });
628
+ return true;
629
+ } catch (e) {
630
+ if (e instanceof StoreConflict)
631
+ return false;
632
+ throw e;
633
+ }
634
+ }
635
+ /** Delete an object's live generation. One that is not there is deleted already. */
636
+ async remove(key) {
637
+ const res = await this.fetchFn(this.objectUrl(key), { method: "DELETE", headers: { authorization: `Bearer ${await this.bearer()}` } });
638
+ if (!res.ok && res.status !== 404)
639
+ throw new StoreError(`DELETE ${this.location}/${key}: ${res.status} ${why(await res.text())}`);
640
+ }
641
+ /** A signed URL to `key` for `seconds`, signed by the key or by the impersonated service account through IAM. */
642
+ async presign(key, seconds, now = /* @__PURE__ */ new Date()) {
643
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > PRESIGN_MAX_SECONDS)
644
+ throw new StoreError(`a signed URL lives 1 to ${PRESIGN_MAX_SECONDS} seconds, not ${seconds}`);
645
+ let email;
646
+ let sign2;
647
+ const c = this.target.accessToken && this.target.signAs ? void 0 : this.credentials();
648
+ if (!c) {
649
+ const sa = this.target.signAs;
650
+ email = sa;
651
+ sign2 = async (s) => {
652
+ const r = await this.post(`${(this.target.iamEndpoint ?? IAM_CREDENTIALS).replace(/\/+$/, "")}/v1/projects/-/serviceAccounts/${encodeURIComponent(sa)}:signBlob`, { "content-type": "application/json", authorization: `Bearer ${await this.bearer()}` }, JSON.stringify({ payload: Buffer.from(s).toString("base64") }), `signBlob as ${sa}, which needs Service Account Token Creator on itself`);
653
+ if (typeof r.signedBlob !== "string")
654
+ throw new StoreError(`signBlob as ${sa} answered without a signature`);
655
+ return Buffer.from(r.signedBlob, "base64");
656
+ };
657
+ } else if (c.type === "service_account") {
658
+ email = c.client_email;
659
+ sign2 = async (s) => createSign("RSA-SHA256").update(s).sign(c.private_key);
660
+ } else {
661
+ const sa = c.service_account_impersonation_url ? impersonated(c.service_account_impersonation_url) : void 0;
662
+ if (!sa)
663
+ throw new StoreError(`a signed URL needs a service account to sign it, and ${this.source} impersonates none: give it a service account to impersonate`);
664
+ email = sa;
665
+ const iam = new URL(c.service_account_impersonation_url).origin;
666
+ sign2 = async (s) => {
667
+ const r = await this.post(`${iam}/v1/projects/-/serviceAccounts/${encodeURIComponent(sa)}:signBlob`, { "content-type": "application/json", authorization: `Bearer ${await this.bearer()}` }, JSON.stringify({ payload: Buffer.from(s).toString("base64") }), `signBlob as ${sa}, which needs Service Account Token Creator on itself`);
668
+ if (typeof r.signedBlob !== "string")
669
+ throw new StoreError(`signBlob as ${sa} answered without a signature`);
670
+ return Buffer.from(r.signedBlob, "base64");
671
+ };
672
+ }
673
+ const url = await signedUrl(this.target.endpoint, this.target.bucket, key, email, seconds, now, sign2);
674
+ return { url, expires: new Date(now.getTime() + seconds * 1e3) };
675
+ }
676
+ };
677
+
678
+ // node_modules/@intentius/chant/dist/object-store/azure-blob.js
679
+ import { createHmac } from "node:crypto";
680
+ import { readFileSync as readFileSync3 } from "node:fs";
681
+ var AZURE_VERSION = "2021-08-06";
682
+ var AZURE_AUTHORITY = "https://login.microsoftonline.com";
683
+ var STORAGE_SCOPE = "https://storage.azure.com/.default";
684
+ function azureFromEnv(where, env = process.env) {
685
+ const at = { account: where.account, container: where.container, endpoint: (where.endpoint ?? `https://${where.account}.blob.core.windows.net`).replace(/\/+$/, "") };
686
+ if (env.AZURE_STORAGE_KEY)
687
+ return { ...at, accountKey: env.AZURE_STORAGE_KEY };
688
+ const tenantId = env.ARM_TENANT_ID;
689
+ const clientId = env.ARM_CLIENT_ID;
690
+ const tokenFile = env.ARM_OIDC_TOKEN_FILE_PATH;
691
+ if (tenantId && clientId && tokenFile)
692
+ return { ...at, oidc: { tenantId, clientId, tokenFile, authority: (env.AZURE_AUTHORITY_HOST || AZURE_AUTHORITY).replace(/\/+$/, "") } };
693
+ throw new StoreError(`${where.setting ?? "the container"} is az://${where.account}/${where.container}, but the job has no credentials for it: ${where.hints?.azure ? `give the job ${where.hints.azure} (it sets ARM_TENANT_ID, ARM_CLIENT_ID and ARM_OIDC_TOKEN_FILE_PATH), or set AZURE_STORAGE_KEY` : "set ARM_TENANT_ID, ARM_CLIENT_ID and ARM_OIDC_TOKEN_FILE_PATH (a job's OIDC setup sets them), or AZURE_STORAGE_KEY"}`);
694
+ }
695
+ var hmac64 = (key, s) => createHmac("sha256", Buffer.from(key, "base64")).update(s, "utf8").digest("base64");
696
+ var SIGNED = ["content-encoding", "content-language", "content-length", "content-md5", "content-type", "date", "if-modified-since", "if-match", "if-none-match", "if-unmodified-since", "range"];
697
+ function sharedKey(account, accountKey, method, rawUrl, headers) {
698
+ const url = new URL(rawUrl);
699
+ const h = Object.fromEntries(Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]));
700
+ const fixed = SIGNED.map((n) => n === "content-length" && h[n] === "0" ? "" : h[n] ?? "");
701
+ const ms = Object.keys(h).filter((n) => n.startsWith("x-ms-")).sort().map((n) => `${n}:${h[n].trim()}
702
+ `).join("");
703
+ const params = /* @__PURE__ */ new Map();
704
+ for (const [k, v] of url.searchParams)
705
+ params.set(k.toLowerCase(), [...params.get(k.toLowerCase()) ?? [], v]);
706
+ const query = [...params.keys()].sort().map((k) => `
707
+ ${k}:${params.get(k).sort().join(",")}`).join("");
708
+ const toSign = [method, ...fixed].join("\n") + "\n" + ms + `/${account}${url.pathname}` + query;
709
+ return `SharedKey ${account}:${hmac64(accountKey, toSign)}`;
710
+ }
711
+ function blobSas(t, blob, expiry, sign2) {
712
+ const se = isoSeconds(expiry);
713
+ const spr = t.endpoint.startsWith("https:") ? "https" : "";
714
+ const resource = `/blob/${t.account}/${t.container}/${blob}`;
715
+ const tail = [spr, AZURE_VERSION, "b", "", "", "", "", "", "", ""];
716
+ let toSign;
717
+ let params;
718
+ if ("key" in sign2) {
719
+ const k = sign2.key;
720
+ toSign = ["r", "", se, resource, k.oid, k.tid, k.start, k.expiry, k.service, k.version, "", "", "", "", ...tail].join("\n");
721
+ params = [["skoid", k.oid], ["sktid", k.tid], ["skt", k.start], ["ske", k.expiry], ["sks", k.service], ["skv", k.version]];
722
+ } else {
723
+ toSign = ["r", "", se, resource, "", "", ...tail].join("\n");
724
+ params = [];
725
+ }
726
+ const sig = hmac64("key" in sign2 ? sign2.key.value : sign2.accountKey, toSign);
727
+ const q = new URLSearchParams([["sv", AZURE_VERSION], ["sr", "b"], ["sp", "r"], ["se", se], ...spr ? [["spr", spr]] : [], ...params, ["sig", sig]]);
728
+ return q.toString();
729
+ }
730
+ var why2 = (text) => {
731
+ try {
732
+ const j = JSON.parse(text);
733
+ if (j.error)
734
+ return [j.error, j.error_description?.split("\r\n")[0]].filter(Boolean).join(": ");
735
+ } catch {
736
+ }
737
+ return [xmlText(text, "Code"), xmlText(text, "Message")?.split("\n")[0]].filter(Boolean).join(": ") || text.slice(0, 300);
738
+ };
739
+ var AzureBlobClient = class {
740
+ constructor(target, fetchFn = defaultFetch, readToken = (f) => readFileSync3(f, "utf-8")) {
741
+ this.target = target;
742
+ this.fetchFn = fetchFn;
743
+ this.readToken = readToken;
744
+ this.keys = /* @__PURE__ */ new Map();
745
+ }
746
+ get location() {
747
+ return `az://${this.target.account}/${this.target.container}`;
748
+ }
749
+ blobUrl(key, query = "") {
750
+ const t = this.target;
751
+ const q = [query, "sas" in t ? t.sas.replace(/^\?/, "") : ""].filter(Boolean).join("&");
752
+ return `${t.endpoint}/${t.container}/${encodePath(key)}${q ? `?${q}` : ""}`;
753
+ }
754
+ /** The storage token for the OIDC identity: once per client, again a minute before it expires. */
755
+ async bearer(o) {
756
+ const fetchToken = async () => {
757
+ let assertion;
758
+ try {
759
+ assertion = this.readToken(o.tokenFile).trim();
760
+ } catch (e) {
761
+ throw new StoreError(`cannot read the OIDC token in ${o.tokenFile}: ${e.message}`);
762
+ }
763
+ if (!assertion)
764
+ throw new StoreError(`the OIDC token file ${o.tokenFile} is empty`);
765
+ const body = new URLSearchParams({
766
+ client_id: o.clientId,
767
+ scope: STORAGE_SCOPE,
768
+ grant_type: "client_credentials",
769
+ client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
770
+ client_assertion: assertion
771
+ }).toString();
772
+ const res = await this.fetchFn(`${o.authority}/${o.tenantId}/oauth2/v2.0/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body });
773
+ const text = await res.text();
774
+ if (!res.ok)
775
+ throw new StoreError(`Entra ID refused the OIDC token for client ${o.clientId}: ${res.status} ${why2(text)}`);
776
+ let j = {};
777
+ try {
778
+ j = JSON.parse(text);
779
+ } catch {
780
+ }
781
+ if (!j.access_token)
782
+ throw new StoreError(`Entra ID answered client ${o.clientId} without a token`);
783
+ return { token: j.access_token, expires: Date.now() + Number(j.expires_in ?? 3600) * 1e3 };
784
+ };
785
+ const again = () => this.token = fetchToken().catch((e) => {
786
+ this.token = void 0;
787
+ throw e;
788
+ });
789
+ let held = await (this.token ?? again());
790
+ if (held.expires - Date.now() < 6e4)
791
+ held = await again();
792
+ return held.token;
793
+ }
794
+ /** The headers for one request, signed or with the bearer token. */
795
+ async headers(method, url, extra) {
796
+ const h = { "x-ms-date": (/* @__PURE__ */ new Date()).toUTCString(), "x-ms-version": AZURE_VERSION, ...extra };
797
+ const t = this.target;
798
+ if ("accountKey" in t)
799
+ return { ...h, authorization: sharedKey(t.account, t.accountKey, method, url, h) };
800
+ if ("sas" in t)
801
+ return h;
802
+ return { ...h, authorization: `Bearer ${await this.bearer(t.oidc)}` };
803
+ }
804
+ async put(key, body, contentType, when) {
805
+ const url = this.blobUrl(key);
806
+ const cond = !when ? {} : "ifMatch" in when ? { "if-match": when.ifMatch } : { "if-none-match": "*" };
807
+ const length = typeof body === "string" ? Buffer.byteLength(body) : body.byteLength;
808
+ const headers = await this.headers("PUT", url, { "x-ms-blob-type": "BlockBlob", "content-type": contentType, "content-length": String(length), ...cond });
809
+ const res = await this.fetchFn(url, { method: "PUT", headers, body });
810
+ if (res.status === 412 || res.status === 409 && when)
811
+ throw new StoreConflict(`PUT ${this.location}/${key}: ${res.status}, it changed since it was read`);
812
+ if (!res.ok)
813
+ throw new StoreError(`PUT ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
814
+ const etag = res.headers?.get("etag") ?? void 0;
815
+ return etag ? { etag } : {};
816
+ }
817
+ async read(key) {
818
+ const url = this.blobUrl(key);
819
+ const res = await this.fetchFn(url, { method: "GET", headers: await this.headers("GET", url, {}) });
820
+ if (res.status === 404)
821
+ return {};
822
+ if (!res.ok)
823
+ throw new StoreError(`GET ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
824
+ const etag = res.headers?.get("etag") ?? void 0;
825
+ return { body: await res.text(), ...etag ? { etag } : {} };
826
+ }
827
+ async get(key) {
828
+ return (await this.read(key)).body;
829
+ }
830
+ /** A blob's properties and metadata, from a HEAD: of the blob, or of one version or snapshot of it. */
831
+ async head(key, at) {
832
+ const url = this.blobUrl(key, at ? new URLSearchParams(at).toString() : "");
833
+ const res = await this.fetchFn(url, { method: "HEAD", headers: await this.headers("HEAD", url, {}) });
834
+ if (res.status === 404 || at && res.status === 400)
835
+ return { exists: false, metadata: {} };
836
+ if (!res.ok)
837
+ throw new StoreError(`HEAD ${this.location}/${key}: ${res.status}`);
838
+ const get = (n) => res.headers?.get(n) ?? void 0;
839
+ const metadata = {};
840
+ const all = res.headers;
841
+ all?.forEach?.((v, k) => {
842
+ if (k.toLowerCase().startsWith("x-ms-meta-"))
843
+ metadata[k.toLowerCase().slice("x-ms-meta-".length)] = v;
844
+ });
845
+ const etag = get("etag");
846
+ const versionId = get("x-ms-version-id");
847
+ const leaseState = get("x-ms-lease-state");
848
+ return { exists: true, ...etag ? { etag } : {}, ...versionId ? { versionId } : {}, ...leaseState ? { leaseState } : {}, metadata };
849
+ }
850
+ /** One version or snapshot of a blob's text; undefined when there is none such. */
851
+ async readAt(key, at) {
852
+ const url = this.blobUrl(key, new URLSearchParams(at).toString());
853
+ const res = await this.fetchFn(url, { method: "GET", headers: await this.headers("GET", url, {}) });
854
+ if (res.status === 404 || res.status === 400)
855
+ return void 0;
856
+ if (!res.ok)
857
+ throw new StoreError(`GET ${this.location}/${key} ${JSON.stringify(at)}: ${res.status} ${why2(await res.text())}`);
858
+ return res.text();
859
+ }
860
+ /**
861
+ * Every version the account keeps of one blob, from List Blobs with
862
+ * `include=versions`: each one's version id, its Last-Modified and whether
863
+ * it is the current version. A blob with no version id (blob versioning
864
+ * off) lists nothing. Metadata only; it needs the container's list
865
+ * permission.
866
+ */
867
+ async listVersions(key) {
868
+ const t = this.target;
869
+ const out = [];
870
+ let marker;
871
+ for (let page = 0; page < 1e3; page++) {
872
+ const q = ["restype=container", "comp=list", "include=versions", `prefix=${encodeURIComponent(key)}`, ...marker ? [`marker=${encodeURIComponent(marker)}`] : [], ..."sas" in t ? [t.sas.replace(/^\?/, "")] : []].join("&");
873
+ const url = `${t.endpoint}/${t.container}?${q}`;
874
+ const res = await this.fetchFn(url, { method: "GET", headers: await this.headers("GET", url, {}) });
875
+ const xml = await res.text();
876
+ if (!res.ok)
877
+ throw new StoreError(`list the versions of ${this.location}/${key}: ${res.status} ${why2(xml)}`);
878
+ for (const b of xmlBlocks(xml, "Blob")) {
879
+ const id = xmlText(b, "VersionId");
880
+ const when = xmlText(b, "Last-Modified");
881
+ if (xmlText(b, "Name") !== key || !id || !when)
882
+ continue;
883
+ out.push({ version_id: id, written_at: new Date(when).toISOString(), latest: xmlText(b, "IsCurrentVersion") === "true" });
884
+ }
885
+ marker = xmlText(xml, "NextMarker") || void 0;
886
+ if (!marker)
887
+ break;
888
+ }
889
+ return out.sort((a, b) => Date.parse(b.written_at) - Date.parse(a.written_at));
890
+ }
891
+ /** Take a snapshot of a blob: its id, the time Azure gives it. */
892
+ async snapshot(key) {
893
+ const url = this.blobUrl(key, "comp=snapshot");
894
+ const res = await this.fetchFn(url, { method: "PUT", headers: await this.headers("PUT", url, { "content-length": "0" }) });
895
+ if (!res.ok)
896
+ throw new StoreError(`snapshot of ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
897
+ const id = res.headers?.get("x-ms-snapshot");
898
+ if (!id)
899
+ throw new StoreError(`snapshot of ${this.location}/${key}: Azure answered without x-ms-snapshot`);
900
+ return id;
901
+ }
902
+ /** Write a block blob with metadata, under a lease when one holds it. */
903
+ async putBlob(key, body, contentType, options = {}) {
904
+ const url = this.blobUrl(key);
905
+ const meta = Object.fromEntries(Object.entries(options.metadata ?? {}).map(([k, v]) => [`x-ms-meta-${k}`, v]));
906
+ const extra = {
907
+ "x-ms-blob-type": "BlockBlob",
908
+ "content-type": contentType,
909
+ "content-length": String(Buffer.byteLength(body)),
910
+ ...meta,
911
+ ...options.leaseId ? { "x-ms-lease-id": options.leaseId } : {},
912
+ ...options.ifNoneMatch ? { "if-none-match": "*" } : {}
913
+ };
914
+ const res = await this.fetchFn(url, { method: "PUT", headers: await this.headers("PUT", url, extra), body });
915
+ if (options.ifNoneMatch && (res.status === 409 || res.status === 412))
916
+ return false;
917
+ if (!res.ok)
918
+ throw new StoreError(`PUT ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
919
+ return true;
920
+ }
921
+ /** A blob lease: acquire one that never expires with the id given (false when one holds it), or release it. */
922
+ async lease(key, action, id) {
923
+ const url = this.blobUrl(key, "comp=lease");
924
+ const extra = { "x-ms-lease-action": action, "content-length": "0", ...action === "acquire" ? { "x-ms-lease-duration": "-1", "x-ms-proposed-lease-id": id } : { "x-ms-lease-id": id } };
925
+ const res = await this.fetchFn(url, { method: "PUT", headers: await this.headers("PUT", url, extra) });
926
+ if (action === "acquire" && res.status === 409)
927
+ return false;
928
+ if (!res.ok)
929
+ throw new StoreError(`${action} the lease of ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
930
+ return true;
931
+ }
932
+ /** Set a blob's metadata, all of it, under its lease when one holds it. */
933
+ async setMetadata(key, metadata, leaseId) {
934
+ const url = this.blobUrl(key, "comp=metadata");
935
+ const extra = { "content-length": "0", ...Object.fromEntries(Object.entries(metadata).map(([k, v]) => [`x-ms-meta-${k}`, v])), ...leaseId ? { "x-ms-lease-id": leaseId } : {} };
936
+ const res = await this.fetchFn(url, { method: "PUT", headers: await this.headers("PUT", url, extra) });
937
+ if (!res.ok)
938
+ throw new StoreError(`set the metadata of ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
939
+ }
940
+ /** Get User Delegation Key, valid from now until `expiry`: one per expiry, so the estate's one link asks once. */
941
+ delegationKey(now, expiry) {
942
+ const id = isoSeconds(expiry);
943
+ let k = this.keys.get(id);
944
+ if (!k) {
945
+ k = (async () => {
946
+ const url = `${this.target.endpoint}/?restype=service&comp=userdelegationkey`;
947
+ const body = `<?xml version="1.0" encoding="utf-8"?><KeyInfo><Start>${isoSeconds(now)}</Start><Expiry>${id}</Expiry></KeyInfo>`;
948
+ const res = await this.fetchFn(url, { method: "POST", headers: await this.headers("POST", url, { "content-type": "application/xml" }), body });
949
+ const xml = await res.text();
950
+ if (!res.ok)
951
+ throw new StoreError(`Get User Delegation Key on ${this.target.account}: ${res.status} ${why2(xml)}`);
952
+ const f = (tag) => {
953
+ const v = xmlText(xml, tag);
954
+ if (!v)
955
+ throw new StoreError(`Get User Delegation Key on ${this.target.account} answered without ${tag}`);
956
+ return v;
957
+ };
958
+ return { oid: f("SignedOid"), tid: f("SignedTid"), start: f("SignedStart"), expiry: f("SignedExpiry"), service: f("SignedService"), version: f("SignedVersion"), value: f("Value") };
959
+ })();
960
+ k.catch(() => this.keys.delete(id));
961
+ this.keys.set(id, k);
962
+ }
963
+ return k;
964
+ }
965
+ /** Delete a blob. One that is not there is deleted already. */
966
+ async remove(key) {
967
+ const url = this.blobUrl(key);
968
+ const res = await this.fetchFn(url, { method: "DELETE", headers: await this.headers("DELETE", url, {}) });
969
+ if (!res.ok && res.status !== 404)
970
+ throw new StoreError(`DELETE ${this.location}/${key}: ${res.status} ${why2(await res.text())}`);
971
+ }
972
+ /** A read-only SAS link to `key` for `seconds`. */
973
+ async presign(key, seconds, now = /* @__PURE__ */ new Date()) {
974
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > PRESIGN_MAX_SECONDS)
975
+ throw new StoreError(`a SAS link lives 1 to ${PRESIGN_MAX_SECONDS} seconds, not ${seconds}`);
976
+ const expires = new Date(Math.floor(now.getTime() / 1e3) * 1e3 + seconds * 1e3);
977
+ const t = this.target;
978
+ const sas = blobSas(t, key, expires, "accountKey" in t ? { accountKey: t.accountKey } : { key: await this.delegationKey(now, expires) });
979
+ return { url: `${this.blobUrl(key)}?${sas}`, expires };
980
+ }
981
+ };
982
+
983
+ // node_modules/@intentius/chant/dist/object-store/from-env.js
984
+ function storeFromEnv(where, env = process.env, fetchFn) {
985
+ const setting = where.setting ?? "the bucket";
986
+ const b = parseBucketUrl(where.bucket, setting);
987
+ if (b.kind !== "s3" && where.role)
988
+ throw new StoreError(`${where.roleSetting ?? "the role"} is an AWS role, and ${where.bucket} is not an S3 bucket: the job writes it with its own ${where.hints?.oidc ?? "OIDC"} identity`);
989
+ const endpoint = where.endpoint?.replace(/\/+$/, "");
990
+ if (b.kind === "gcs")
991
+ return new GcsClient(gcsFromEnv({ bucket: b.bucket, setting, ...where.hints ? { hints: where.hints } : {}, ...endpoint ? { endpoint } : {} }, env), fetchFn);
992
+ if (b.kind === "azure")
993
+ return new AzureBlobClient(azureFromEnv({ account: b.account, container: b.container, setting, ...where.hints ? { hints: where.hints } : {}, ...endpoint ? { endpoint } : {} }, env), fetchFn);
994
+ return new S3Client(s3FromEnv({ ...where, setting }, env), fetchFn);
995
+ }
996
+ export {
997
+ AZURE_AUTHORITY,
998
+ AZURE_VERSION,
999
+ AzureBlobClient,
1000
+ GCS_ENDPOINT,
1001
+ GcsClient,
1002
+ IAM_CREDENTIALS,
1003
+ PRESIGN_MAX_SECONDS,
1004
+ S3Client,
1005
+ StoreConflict as S3Conflict,
1006
+ StoreError as S3Error,
1007
+ StoreConflict,
1008
+ StoreError,
1009
+ assumeRoleWithWebIdentity,
1010
+ azureFromEnv,
1011
+ blobSas,
1012
+ bucketUrl,
1013
+ defaultFetch,
1014
+ encodePath,
1015
+ encodeStrict,
1016
+ gcsFromEnv,
1017
+ isStoreConflict,
1018
+ isoSeconds,
1019
+ parseBucket,
1020
+ parseBucketUrl,
1021
+ presign,
1022
+ s3FromEnv,
1023
+ selfSignedJwt,
1024
+ sharedKey,
1025
+ sign,
1026
+ signRequest,
1027
+ signedUrl,
1028
+ storeFromEnv,
1029
+ tradedIdentities,
1030
+ tradedVars,
1031
+ xmlBlocks,
1032
+ xmlText
1033
+ };