disk 0.8.17 → 0.8.19

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/dist/index.cjs CHANGED
@@ -1,1257 +1,1441 @@
1
- "use strict";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
2
3
  var __create = Object.create;
3
4
  var __defProp = Object.defineProperty;
4
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
7
  var __getProtoOf = Object.getPrototypeOf;
7
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
9
  var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
19
18
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Archil: () => Archil,
34
- ArchilApiError: () => ArchilApiError,
35
- ArchilError: () => ArchilError,
36
- ArchilS3Error: () => ArchilS3Error,
37
- Disk: () => Disk,
38
- DiskMultipart: () => DiskMultipart,
39
- Disks: () => Disks,
40
- Tokens: () => Tokens,
41
- USER_AGENT: () => USER_AGENT,
42
- VERSION: () => VERSION,
43
- configure: () => configure,
44
- createApiKey: () => createApiKey,
45
- createDisk: () => createDisk,
46
- deleteApiKey: () => deleteApiKey,
47
- effectiveUploadPartSize: () => effectiveUploadPartSize,
48
- exec: () => exec,
49
- getDisk: () => getDisk,
50
- listApiKeys: () => listApiKeys,
51
- listDisks: () => listDisks
52
- });
53
- module.exports = __toCommonJS(index_exports);
54
-
55
- // src/client.ts
56
- var import_openapi_fetch = __toESM(require("openapi-fetch"), 1);
57
-
58
- // src/s3xml.ts
59
- var import_fast_xml_parser = require("fast-xml-parser");
60
- var parser = new import_fast_xml_parser.XMLParser({
61
- isArray: (name) => name === "Contents" || name === "CommonPrefixes",
62
- parseTagValue: false,
63
- trimValues: true,
64
- ignoreAttributes: true
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ const require_paths = require("./paths-1c4QqbOB.cjs");
25
+ let openapi_fetch = require("openapi-fetch");
26
+ openapi_fetch = __toESM(openapi_fetch, 1);
27
+ //#region src/s3xml.ts
28
+ const parser = new (require("fast-xml-parser")).XMLParser({
29
+ isArray: (name) => name === "Contents" || name === "CommonPrefixes",
30
+ parseTagValue: false,
31
+ trimValues: true,
32
+ ignoreAttributes: true
65
33
  });
34
+ /** Parse an XML document into a plain object. Returns {} for empty/blank input. */
66
35
  function parseXml(xml) {
67
- if (!xml.trim()) return {};
68
- return parser.parse(xml);
36
+ if (!xml.trim()) return {};
37
+ return parser.parse(xml);
69
38
  }
70
-
71
- // src/errors.ts
39
+ //#endregion
40
+ //#region src/errors.ts
41
+ /**
42
+ * Base class for every error the SDK throws. Catch with `instanceof ArchilError`
43
+ * to handle control-plane and S3 failures uniformly; `status` is the HTTP status
44
+ * code and `code` a machine-readable error code when the server provided one.
45
+ */
72
46
  var ArchilError = class extends Error {
73
- /** HTTP status code associated with the failure. */
74
- status;
75
- /** Machine-readable error code (e.g. an S3 code like "NoSuchKey"), if known. */
76
- code;
77
- constructor(message, status, code) {
78
- super(message);
79
- this.name = "ArchilError";
80
- this.status = status;
81
- this.code = code;
82
- }
47
+ /** HTTP status code associated with the failure. */
48
+ status;
49
+ /** Machine-readable error code (e.g. an S3 code like "NoSuchKey"), if known. */
50
+ code;
51
+ constructor(message, status, code) {
52
+ super(message);
53
+ this.name = "ArchilError";
54
+ this.status = status;
55
+ this.code = code;
56
+ }
83
57
  };
58
+ /** Error from the control-plane REST API. */
84
59
  var ArchilApiError = class extends ArchilError {
85
- constructor(message, status, code) {
86
- super(message, status, code);
87
- this.name = "ArchilApiError";
88
- }
60
+ constructor(message, status, code) {
61
+ super(message, status, code);
62
+ this.name = "ArchilApiError";
63
+ }
89
64
  };
65
+ /**
66
+ * Error from the S3-compatible object API (getObject/putObject/deleteObject/
67
+ * headObject/listObjects). The gateway returns an S3-style XML `<Error>` body;
68
+ * this surfaces its parts as structured fields (`status`, `code`, `requestId`)
69
+ * rather than a raw blob, while keeping the full body on `raw` for debugging.
70
+ */
90
71
  var ArchilS3Error = class extends ArchilError {
91
- /** S3 request id, if the gateway returned one. */
92
- requestId;
93
- /** Raw response body (the XML document), for debugging. */
94
- raw;
95
- constructor(opts) {
96
- const detail = opts.message ?? opts.statusText ?? "";
97
- const codePart = opts.code ? ` ${opts.code}` : "";
98
- super(
99
- `S3 ${opts.operation} failed: ${opts.statusCode}${codePart}${detail ? ` \u2014 ${detail}` : ""}`,
100
- opts.statusCode,
101
- opts.code
102
- );
103
- this.name = "ArchilS3Error";
104
- this.requestId = opts.requestId;
105
- this.raw = opts.raw;
106
- }
72
+ /** S3 request id, if the gateway returned one. */
73
+ requestId;
74
+ /** Raw response body (the XML document), for debugging. */
75
+ raw;
76
+ constructor(opts) {
77
+ const detail = opts.message ?? opts.statusText ?? "";
78
+ const codePart = opts.code ? ` ${opts.code}` : "";
79
+ super(`S3 ${opts.operation} failed: ${opts.statusCode}${codePart}${detail ? ` — ${detail}` : ""}`, opts.statusCode, opts.code);
80
+ this.name = "ArchilS3Error";
81
+ this.requestId = opts.requestId;
82
+ this.raw = opts.raw;
83
+ }
107
84
  };
108
85
  function tagString(obj, tag) {
109
- const value = obj[tag];
110
- return value === void 0 || value === null ? void 0 : String(value);
86
+ const value = obj[tag];
87
+ return value === void 0 || value === null ? void 0 : String(value);
111
88
  }
89
+ /** Build an ArchilS3Error from a failed S3 response, parsing the XML body. */
112
90
  function parseS3Error(operation, statusCode, statusText, body) {
113
- let err = {};
114
- try {
115
- err = parseXml(body).Error ?? {};
116
- } catch {
117
- err = {};
118
- }
119
- return new ArchilS3Error({
120
- operation,
121
- statusCode,
122
- statusText,
123
- code: tagString(err, "Code"),
124
- message: tagString(err, "Message"),
125
- requestId: tagString(err, "RequestId"),
126
- raw: body
127
- });
91
+ let err = {};
92
+ try {
93
+ err = parseXml(body).Error ?? {};
94
+ } catch {
95
+ err = {};
96
+ }
97
+ return new ArchilS3Error({
98
+ operation,
99
+ statusCode,
100
+ statusText,
101
+ code: tagString(err, "Code"),
102
+ message: tagString(err, "Message"),
103
+ requestId: tagString(err, "RequestId"),
104
+ raw: body
105
+ });
128
106
  }
129
-
130
- // src/regions.ts
131
- var REGION_URLS = {
132
- "aws-us-east-1": "https://control.green.us-east-1.aws.prod.archil.com",
133
- "aws-us-west-2": "https://control.green.us-west-2.aws.prod.archil.com",
134
- "aws-eu-west-1": "https://control.green.eu-west-1.aws.prod.archil.com",
135
- "gcp-us-central1": "https://control.blue.us-central1.gcp.prod.archil.com"
107
+ //#endregion
108
+ //#region src/regions.ts
109
+ const REGION_URLS = {
110
+ "aws-us-east-1": "https://control.green.us-east-1.aws.prod.archil.com",
111
+ "aws-us-west-2": "https://control.green.us-west-2.aws.prod.archil.com",
112
+ "aws-eu-west-1": "https://control.green.eu-west-1.aws.prod.archil.com",
113
+ "gcp-us-central1": "https://control.blue.us-central1.gcp.prod.archil.com"
136
114
  };
137
115
  function resolveBaseUrl(region) {
138
- const url = REGION_URLS[region];
139
- if (!url) {
140
- throw new Error(
141
- `Unknown region "${region}". Valid regions: ${Object.keys(REGION_URLS).join(", ")}`
142
- );
143
- }
144
- return url;
116
+ const url = REGION_URLS[region];
117
+ if (!url) throw new Error(`Unknown region "${region}". Valid regions: ${Object.keys(REGION_URLS).join(", ")}`);
118
+ return url;
145
119
  }
120
+ /**
121
+ * Derive the S3-compatible endpoint from a control-plane base URL by swapping a
122
+ * leading `control.` hostname segment for `s3.` (e.g.
123
+ * `control.green.us-east-1.…` → `s3.green.us-east-1.…`). Returns undefined if the
124
+ * URL can't be parsed. A host without a `control.` prefix is returned unchanged.
125
+ */
146
126
  function deriveS3BaseUrl(controlBaseUrl) {
147
- try {
148
- const u = new URL(controlBaseUrl);
149
- u.hostname = u.hostname.replace(/^control\./, "s3.");
150
- return u.toString().replace(/\/$/, "");
151
- } catch {
152
- return void 0;
153
- }
127
+ try {
128
+ const u = new URL(controlBaseUrl);
129
+ u.hostname = u.hostname.replace(/^control\./, "s3.");
130
+ return u.toString().replace(/\/$/, "");
131
+ } catch {
132
+ return;
133
+ }
154
134
  }
155
-
156
- // src/version.ts
157
- var VERSION = true ? "0.8.17" : "0.0.0-dev";
158
- var USER_AGENT = `archil-js/${VERSION}`;
159
-
160
- // src/client.ts
161
- var createClient = typeof import_openapi_fetch.default === "function" ? import_openapi_fetch.default : import_openapi_fetch.default.default;
135
+ //#endregion
136
+ //#region src/version.ts
137
+ const VERSION = "0.8.19";
138
+ const USER_AGENT = `archil-js/${VERSION}`;
139
+ //#endregion
140
+ //#region src/client.ts
141
+ const createClient = typeof openapi_fetch.default === "function" ? openapi_fetch.default : openapi_fetch.default.default;
162
142
  function createApiClient(opts) {
163
- const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
164
- return createClient({
165
- baseUrl,
166
- headers: {
167
- Authorization: `key-${opts.apiKey.replace(/^key-/, "")}`,
168
- // Identifies the JS SDK (and its version) to the control plane. Honored
169
- // by Node's fetch; browsers treat User-Agent as a forbidden header and
170
- // drop it, which is fine — the SDK's primary use is server-side.
171
- "User-Agent": USER_AGENT
172
- }
173
- });
143
+ const baseUrl = opts.baseUrl ?? resolveBaseUrl(opts.region);
144
+ return createClient({
145
+ baseUrl,
146
+ headers: {
147
+ Authorization: `key-${opts.apiKey.replace(/^key-/, "")}`,
148
+ "User-Agent": USER_AGENT
149
+ }
150
+ });
174
151
  }
152
+ /**
153
+ * Unwrap the API envelope: return data on success, throw ArchilApiError on failure.
154
+ */
175
155
  async function unwrap(promise) {
176
- const { data: body, error, response } = await promise;
177
- if (error || !body) {
178
- const errBody = error;
179
- throw new ArchilApiError(
180
- errBody?.error ?? `API request failed with status ${response.status}`,
181
- response.status
182
- );
183
- }
184
- if (!body.success) {
185
- throw new ArchilApiError(
186
- body.error ?? "Unknown API error",
187
- response.status
188
- );
189
- }
190
- return body.data;
156
+ const { data: body, error, response } = await promise;
157
+ if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
158
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
159
+ return body.data;
191
160
  }
161
+ /**
162
+ * Unwrap an API response that has no data payload (e.g., delete operations).
163
+ */
192
164
  async function unwrapEmpty(promise) {
193
- const { data: body, error, response } = await promise;
194
- if (error || !body) {
195
- const errBody = error;
196
- throw new ArchilApiError(
197
- errBody?.error ?? `API request failed with status ${response.status}`,
198
- response.status
199
- );
200
- }
201
- if (!body.success) {
202
- throw new ArchilApiError(
203
- body.error ?? "Unknown API error",
204
- response.status
205
- );
206
- }
165
+ const { data: body, error, response } = await promise;
166
+ if (error || !body) throw new ArchilApiError(error?.error ?? `API request failed with status ${response.status}`, response.status);
167
+ if (!body.success) throw new ArchilApiError(body.error ?? "Unknown API error", response.status);
207
168
  }
208
-
209
- // src/disk.ts
169
+ //#endregion
170
+ //#region src/disk.ts
210
171
  var Disk = class {
211
- id;
212
- name;
213
- organization;
214
- status;
215
- provider;
216
- region;
217
- createdAt;
218
- fsHandlerStatus;
219
- lastAccessed;
220
- dataSize;
221
- monthlyUsage;
222
- mounts;
223
- metrics;
224
- connectedClients;
225
- authorizedUsers;
226
- allowedIps;
227
- /** @internal */
228
- _client;
229
- /** @internal */
230
- _archilRegion;
231
- /** Base URL for the S3-compatible API (port 9000 ingress). Empty if unset. */
232
- _s3BaseUrl;
233
- /** Lazily-constructed multipart namespace (see {@link multipart}). @internal */
234
- _multipart;
235
- /** @internal */
236
- constructor(data, client, archilRegion, s3BaseUrl) {
237
- this.id = data.id;
238
- this.name = data.name;
239
- this.organization = data.organization;
240
- this.status = data.status;
241
- this.provider = data.provider;
242
- this.region = data.region;
243
- this.createdAt = data.createdAt;
244
- this.fsHandlerStatus = data.fsHandlerStatus;
245
- this.lastAccessed = data.lastAccessed;
246
- this.dataSize = data.dataSize;
247
- this.monthlyUsage = data.monthlyUsage;
248
- this.mounts = data.mounts;
249
- this.metrics = data.metrics;
250
- this.connectedClients = data.connectedClients;
251
- this.authorizedUsers = data.authorizedUsers;
252
- this.allowedIps = data.allowedIps;
253
- this._client = client;
254
- this._archilRegion = archilRegion;
255
- this._s3BaseUrl = s3BaseUrl ?? "";
256
- }
257
- toJSON() {
258
- return {
259
- id: this.id,
260
- name: this.name,
261
- organization: this.organization,
262
- status: this.status,
263
- provider: this.provider,
264
- region: this.region,
265
- createdAt: this.createdAt,
266
- fsHandlerStatus: this.fsHandlerStatus,
267
- lastAccessed: this.lastAccessed,
268
- dataSize: this.dataSize,
269
- monthlyUsage: this.monthlyUsage,
270
- mounts: this.mounts,
271
- metrics: this.metrics,
272
- connectedClients: this.connectedClients,
273
- authorizedUsers: this.authorizedUsers,
274
- allowedIps: this.allowedIps
275
- };
276
- }
277
- async addUser(user) {
278
- return unwrap(
279
- this._client.POST("/api/disks/{id}/users", {
280
- params: { path: { id: this.id } },
281
- body: user
282
- })
283
- );
284
- }
285
- async removeUser(userType, identifier) {
286
- await unwrapEmpty(
287
- this._client.DELETE("/api/disks/{id}/users/{userType}", {
288
- params: {
289
- path: { id: this.id, userType },
290
- query: { identifier }
291
- }
292
- })
293
- );
294
- }
295
- async createToken(nickname) {
296
- const user = await unwrap(
297
- this._client.POST("/api/disks/{id}/users", {
298
- params: { path: { id: this.id } },
299
- body: { type: "token", nickname }
300
- })
301
- );
302
- if (!user.token || !user.identifier) {
303
- throw new Error("Server did not return a generated token");
304
- }
305
- return user;
306
- }
307
- async removeTokenUser(identifier) {
308
- await this.removeUser("token", identifier);
309
- }
310
- async getAllowedIPs() {
311
- const data = await unwrap(
312
- this._client.GET("/api/disks/{id}/allowed-ips", {
313
- params: { path: { id: this.id } }
314
- })
315
- );
316
- return data.allowedIps;
317
- }
318
- async setAllowedIPs(allowedIps) {
319
- const data = await unwrap(
320
- this._client.PUT("/api/disks/{id}/allowed-ips", {
321
- params: { path: { id: this.id } },
322
- body: { allowedIps }
323
- })
324
- );
325
- return data.allowedIps;
326
- }
327
- async addAllowedIP(ip) {
328
- const current = await this.getAllowedIPs();
329
- if (current.includes(ip)) return current;
330
- return this.setAllowedIPs([...current, ip]);
331
- }
332
- async removeAllowedIP(ip) {
333
- const current = await this.getAllowedIPs();
334
- return this.setAllowedIPs(current.filter((i) => i !== ip));
335
- }
336
- async delete() {
337
- await unwrapEmpty(
338
- this._client.DELETE("/api/disks/{id}", {
339
- params: { path: { id: this.id } }
340
- })
341
- );
342
- }
343
- /**
344
- * Execute a command in a container with this disk mounted.
345
- * Blocks until the command completes and returns stdout, stderr, and exit code.
346
- */
347
- async exec(command) {
348
- return unwrap(
349
- this._client.POST("/api/disks/{id}/exec", {
350
- params: { path: { id: this.id } },
351
- body: { command }
352
- })
353
- );
354
- }
355
- /**
356
- * Constant-time parallel grep across files on this disk. Listing and
357
- * matching are fanned out across ephemeral exec containers; the request
358
- * finishes within the supplied time budget regardless of dataset size.
359
- *
360
- * The returned `stoppedReason` says whether the search ran to completion
361
- * or short-circuited on `maxResults` / `maxDurationSeconds`. When
362
- * stopping early, the matches returned are a sample (whichever workers
363
- * reported first), not the lexicographically first N.
364
- */
365
- async grep(opts) {
366
- return unwrap(
367
- this._client.POST("/api/disks/{id}/grep", {
368
- params: { path: { id: this.id } },
369
- body: {
370
- directory: opts.directory,
371
- pattern: opts.pattern,
372
- recursive: opts.recursive ?? false,
373
- maxDurationSeconds: opts.maxDurationSeconds ?? 30,
374
- concurrency: opts.concurrency ?? 50,
375
- maxResults: opts.maxResults ?? 1e3
376
- }
377
- })
378
- );
379
- }
380
- /**
381
- * Create a signed, time-limited URL that lets anyone download a single file
382
- * from this disk without authentication. The returned URL embeds a
383
- * cryptographically signed token carrying the disk, the file's key, and an
384
- * expiry — share it directly; no API key is needed to redeem it.
385
- *
386
- * @param key Path to the file on the disk (e.g. "reports/2026-01/data.pdf").
387
- * @param opts `expiresIn` sets the URL lifetime in seconds (any positive
388
- * integer, max 604800 = 7 days). Defaults to 24h.
389
- */
390
- async share(key, opts = {}) {
391
- const body = { key };
392
- if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
393
- const call = this._client.POST;
394
- return unwrap(call(`/api/disks/${this.id}/share`, { body }));
395
- }
396
- /**
397
- * Read an object from the disk via the S3-compatible GetObject API and return
398
- * its full contents as bytes. Throws `ArchilS3Error` if the object does not
399
- * exist (status 404, code "NoSuchKey") or the request is rejected; use
400
- * `headObject`/`objectExists` to check existence without throwing.
401
- *
402
- * @param key Path on the disk (e.g. "reports/2026-01/data.json")
403
- */
404
- async getObject(key) {
405
- const resp = await this._s3Request("GET", key);
406
- if (!resp.ok) {
407
- throw parseS3Error("GetObject", resp.status, resp.statusText, decodeText(resp.body));
408
- }
409
- return resp.body;
410
- }
411
- /**
412
- * Fetch an object's metadata (size, etag, content type, last-modified) without
413
- * downloading its contents, via the S3-compatible HeadObject API. Returns
414
- * `null` if the object does not exist.
415
- *
416
- * @param key Path on the disk (e.g. "reports/2026-01/data.json")
417
- */
418
- async headObject(key) {
419
- const resp = await this._s3Request("HEAD", key);
420
- if (resp.status === 404) return null;
421
- if (!resp.ok) {
422
- throw parseS3Error("HeadObject", resp.status, resp.statusText, decodeText(resp.body));
423
- }
424
- const lastModified = resp.headers.get("last-modified");
425
- return {
426
- size: Number(resp.headers.get("content-length") ?? 0),
427
- etag: resp.headers.get("etag") ?? void 0,
428
- contentType: resp.headers.get("content-type") ?? void 0,
429
- lastModified: lastModified ? new Date(lastModified) : void 0
430
- };
431
- }
432
- /** Whether an object exists on the disk (a HeadObject that maps 404 → false). */
433
- async objectExists(key) {
434
- return await this.headObject(key) !== null;
435
- }
436
- /**
437
- * Write an object to the disk via the S3-compatible API. Handles any size:
438
- * bodies at or below `multipartThreshold` (defaults to `partSize`, i.e.
439
- * 16 MiB) go through a single PutObject request; larger bodies are uploaded as
440
- * a multipart upload — split into `partSize` parts, uploaded with bounded
441
- * `concurrency` (default 4), and assembled. A failed part aborts the upload so
442
- * nothing is left half-staged. For manual control over the multipart
443
- * lifecycle, use the {@link multipart} namespace.
444
- *
445
- * Faster than exec for large files — no container overhead, no command-length
446
- * limits. Returns the entity tag the server assigned (a multipart upload's tag
447
- * is S3's `md5(concat(partMd5s))-N` form rather than a plain MD5).
448
- *
449
- * @param key Path on the disk (e.g. "reports/2026-01/data.json")
450
- * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
451
- * @param options Either a content-type string, or {@link PutObjectOptions}
452
- * (`contentType`, `multipartThreshold`, `partSize`,
453
- * `concurrency`). Content type defaults to
454
- * "application/octet-stream".
455
- */
456
- async putObject(key, body, options) {
457
- const opts = typeof options === "string" ? { contentType: options } : options ?? {};
458
- const contentType = opts.contentType ?? "application/octet-stream";
459
- const partSize = Math.max(opts.partSize ?? DEFAULT_PART_SIZE, MIN_PART_SIZE);
460
- const threshold = opts.multipartThreshold ?? partSize;
461
- const bytes = toBytes(body);
462
- if (bytes.length <= threshold) {
463
- const resp = await this._s3Request("PUT", key, { body, contentType });
464
- if (!resp.ok) {
465
- throw parseS3Error("PutObject", resp.status, resp.statusText, decodeText(resp.body));
466
- }
467
- return { etag: resp.headers.get("etag") ?? void 0 };
468
- }
469
- return this._putMultipart(
470
- key,
471
- bytes,
472
- contentType,
473
- partSize,
474
- Math.max(1, opts.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY)
475
- );
476
- }
477
- /**
478
- * Upload a large body through the multipart lifecycle: split into `partSize`
479
- * parts, upload them with bounded concurrency, then complete aborting the
480
- * upload if any part fails so nothing is left half-staged. @internal
481
- */
482
- async _putMultipart(key, bytes, contentType, partSize, concurrency) {
483
- const effectivePartSize = effectiveUploadPartSize(bytes.length, partSize);
484
- const mp = this.multipart;
485
- const upload = await mp.create(key, contentType);
486
- try {
487
- const partCount = Math.ceil(bytes.length / effectivePartSize);
488
- const parts = new Array(partCount);
489
- let next = 0;
490
- const worker = async () => {
491
- for (; ; ) {
492
- const index = next++;
493
- if (index >= partCount) return;
494
- const start = index * effectivePartSize;
495
- const slice = bytes.subarray(start, Math.min(start + effectivePartSize, bytes.length));
496
- parts[index] = await mp.uploadPart(key, upload.uploadId, index + 1, slice);
497
- }
498
- };
499
- await Promise.all(Array.from({ length: Math.min(concurrency, partCount) }, worker));
500
- const done = await mp.complete(key, upload.uploadId, parts);
501
- return { etag: done.etag };
502
- } catch (err) {
503
- await mp.abort(key, upload.uploadId).catch(() => {
504
- });
505
- throw err;
506
- }
507
- }
508
- /**
509
- * Append bytes to an object via the S3-compatible PutObject append extension
510
- * (`?append=true`). If the object already exists the bytes are appended to it;
511
- * if it doesn't, it is created. Returns the entity tag of the full object
512
- * after the append.
513
- *
514
- * Each call may append at most 1 MiB — the server rejects a larger body with
515
- * `EntityTooLarge`. To grow an object past that, append in chunks (or use
516
- * {@link putObject} for a one-shot large write).
517
- *
518
- * Unlike most operations this is NOT auto-retried on a transient error:
519
- * append isn't idempotent, so retrying a succeeded-but-unacknowledged append
520
- * would duplicate the bytes. On a transient failure, re-append yourself only
521
- * after confirming the object's size.
522
- *
523
- * @param key Path on the disk (e.g. "logs/app.log")
524
- * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
525
- * @param contentType MIME type, applied only when the object is newly created.
526
- */
527
- async appendObject(key, body, contentType = "application/octet-stream") {
528
- const resp = await this._s3Request("PUT", key, {
529
- body,
530
- contentType,
531
- query: { append: "true" },
532
- retry: false
533
- });
534
- if (!resp.ok) {
535
- throw parseS3Error("AppendObject", resp.status, resp.statusText, decodeText(resp.body));
536
- }
537
- return { etag: resp.headers.get("etag") ?? void 0 };
538
- }
539
- /**
540
- * Delete an object from the disk via the S3-compatible DeleteObject API.
541
- * Idempotent: deleting a key that doesn't exist resolves successfully, per
542
- * S3 semantics.
543
- *
544
- * @param key Path on the disk (e.g. "project/dist/server.cjs")
545
- */
546
- async deleteObject(key) {
547
- const resp = await this._s3Request("DELETE", key);
548
- if (!resp.ok && resp.status !== 404) {
549
- throw parseS3Error("DeleteObject", resp.status, resp.statusText, decodeText(resp.body));
550
- }
551
- }
552
- /**
553
- * List objects on the disk via the S3-compatible ListObjectsV2 API. By
554
- * default this follows continuation tokens until the listing is exhausted and
555
- * returns every matching key. Use `limit` to cap the total, `singlePage` for a
556
- * single request, or {@link listObjectsPages} to stream pages without loading
557
- * everything into memory.
558
- *
559
- * @param prefix Only return keys beginning with this prefix (omit for all).
560
- * @param opts Listing and pagination options.
561
- */
562
- async listObjects(prefix, opts = {}) {
563
- if (opts.singlePage) {
564
- return this._listObjectsPage(prefix, opts);
565
- }
566
- const objects = [];
567
- const commonPrefixes = [];
568
- const seenPrefixes = /* @__PURE__ */ new Set();
569
- let echoedPrefix;
570
- let truncated = false;
571
- outer: for await (const page of this.listObjectsPages(prefix, opts)) {
572
- echoedPrefix = page.prefix;
573
- for (const cp of page.commonPrefixes) {
574
- if (!seenPrefixes.has(cp)) {
575
- seenPrefixes.add(cp);
576
- commonPrefixes.push(cp);
577
- }
578
- }
579
- for (const obj of page.objects) {
580
- if (opts.limit !== void 0 && objects.length >= opts.limit) {
581
- truncated = true;
582
- break outer;
583
- }
584
- objects.push(obj);
585
- }
586
- }
587
- return { objects, commonPrefixes, isTruncated: truncated, keyCount: objects.length, prefix: echoedPrefix };
588
- }
589
- /**
590
- * Yield ListObjectsV2 pages lazily, following continuation tokens. A
591
- * memory-friendly way to process a large listing without materializing it:
592
- *
593
- * ```ts
594
- * for await (const page of disk.listObjectsPages("logs/")) {
595
- * for (const obj of page.objects) process(obj);
596
- * }
597
- * ```
598
- *
599
- * @param prefix Only return keys beginning with this prefix (omit for all).
600
- * @param opts Listing options (`limit` / `singlePage` are ignored here
601
- * control your own loop).
602
- */
603
- async *listObjectsPages(prefix, opts = {}) {
604
- const seenTokens = /* @__PURE__ */ new Set();
605
- let continuationToken = opts.continuationToken;
606
- for (; ; ) {
607
- const page = await this._listObjectsPage(prefix, { ...opts, continuationToken });
608
- yield page;
609
- const next = page.isTruncated ? page.nextContinuationToken : void 0;
610
- if (!next || seenTokens.has(next)) break;
611
- seenTokens.add(next);
612
- continuationToken = next;
613
- }
614
- }
615
- /** Fetch a single ListObjectsV2 page. @internal */
616
- async _listObjectsPage(prefix, opts) {
617
- const query = { "list-type": 2 };
618
- if (prefix !== void 0) query.prefix = prefix;
619
- if (!opts.recursive) query.delimiter = "/";
620
- if (opts.continuationToken !== void 0) query["continuation-token"] = opts.continuationToken;
621
- if (opts.startAfter !== void 0) query["start-after"] = opts.startAfter;
622
- const resp = await this._s3Request("GET", "", { query });
623
- if (!resp.ok) {
624
- throw parseS3Error("ListObjectsV2", resp.status, resp.statusText, decodeText(resp.body));
625
- }
626
- return parseListObjectsResult(decodeText(resp.body));
627
- }
628
- /**
629
- * Delete up to many objects in a single S3-compatible DeleteObjects request.
630
- * Unlike {@link deleteObject}, failures are reported per key rather than
631
- * thrown: the result's `deleted` lists the keys that were removed and
632
- * `errors` lists the ones that weren't (with the server's code/message). A
633
- * key that didn't exist still counts as deleted, per S3 semantics.
634
- *
635
- * The server caps a single request at 1000 keys; this method transparently
636
- * splits larger inputs into 1000-key batches and merges the results.
637
- *
638
- * @param keys Object keys to delete.
639
- * @param opts `quiet` suppresses the per-key success list server-side.
640
- */
641
- async deleteObjects(keys, opts = {}) {
642
- const deleted = [];
643
- const errors = [];
644
- for (let i = 0; i < keys.length; i += MAX_DELETE_OBJECTS_PER_REQUEST) {
645
- const batch = keys.slice(i, i + MAX_DELETE_OBJECTS_PER_REQUEST);
646
- const xml = buildDeleteObjectsXml(batch, opts.quiet ?? false);
647
- const resp = await this._s3Request("POST", "", {
648
- query: { delete: "" },
649
- body: xml,
650
- contentType: "application/xml"
651
- });
652
- if (!resp.ok) {
653
- throw parseS3Error("DeleteObjects", resp.status, resp.statusText, decodeText(resp.body));
654
- }
655
- const parsed = parseDeleteObjectsResult(decodeText(resp.body));
656
- deleted.push(...parsed.deleted);
657
- errors.push(...parsed.errors);
658
- }
659
- return { deleted, errors };
660
- }
661
- /**
662
- * The advanced, opt-in multipart-upload API. Drive the raw lifecycle
663
- * yourself `create` `uploadPart` → `complete` (or `abort`), plus
664
- * `listParts` / `listUploads`. Most callers don't need this: {@link putObject}
665
- * runs the whole lifecycle automatically for large bodies. Reach for it only
666
- * when you need manual control (e.g. uploading parts from separate processes),
667
- * and note you then own part-size, memory, and concurrency management.
668
- */
669
- get multipart() {
670
- return this._multipart ??= new DiskMultipart(this.id, this._s3Request.bind(this));
671
- }
672
- /**
673
- * Send a single request to the disk's S3-compatible endpoint. This reuses the
674
- * control-plane client purely for its credential and transport — the same
675
- * `Authorization` header is sent and verified by the same code server-side —
676
- * pointed at the S3 host. Returns the response status and fully-buffered body
677
- * so callers can inspect both regardless of the verb used.
678
- *
679
- * The S3 routes (`/{diskId}/{key}` for objects, `/{diskId}` for the bucket)
680
- * are not part of the typed control-plane API, so the path and per-request
681
- * options are passed untyped. An empty `key` targets the bucket itself (used
682
- * by listObjects).
683
- *
684
- * @internal
685
- */
686
- async _s3Request(method, key, opts = {}) {
687
- if (!this._s3BaseUrl) {
688
- throw new Error(
689
- "S3 base URL not configured. Pass s3BaseUrl to new Archil({...}) or set ARCHIL_S3_BASE_URL."
690
- );
691
- }
692
- const call = this._client[method];
693
- const trimmedKey = key.replace(/^\//, "");
694
- const encodedKey = trimmedKey.split("/").map(encodeURIComponent).join("/");
695
- const path = encodedKey ? `/${this.id}/${encodedKey}` : `/${this.id}`;
696
- const init = {
697
- baseUrl: this._s3BaseUrl,
698
- parseAs: "stream",
699
- ...opts.query ? { params: { query: opts.query } } : {},
700
- // fetch accepts string / Uint8Array / ArrayBuffer bodies directly; pass it
701
- // through unchanged (no Node Buffer in the data path). Bodies are fully
702
- // buffered (never streams), so re-sending one on a retry is safe.
703
- ...opts.body !== void 0 ? { body: opts.body, bodySerializer: (b) => b } : {},
704
- ...opts.contentType ? { headers: { "Content-Type": opts.contentType } } : {}
705
- };
706
- const hasBody = method === "GET" || method === "POST";
707
- const maxRetries = opts.retry === false ? 0 : MAX_S3_RETRIES;
708
- for (let attempt = 0; ; attempt++) {
709
- let error;
710
- let response;
711
- try {
712
- ({ error, response } = await call(path, init));
713
- } catch (transportError) {
714
- if (attempt < maxRetries) {
715
- await sleep(s3RetryDelayMs(attempt));
716
- continue;
717
- }
718
- throw transportError;
719
- }
720
- if (!response.ok) {
721
- if (isTransientS3Status(response.status) && attempt < maxRetries) {
722
- await response.body?.cancel().catch(() => {
723
- });
724
- await sleep(s3RetryDelayMs(attempt));
725
- continue;
726
- }
727
- const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
728
- return {
729
- ok: false,
730
- status: response.status,
731
- statusText: response.statusText,
732
- headers: response.headers,
733
- body: new TextEncoder().encode(message)
734
- };
735
- }
736
- const bytes = hasBody ? new Uint8Array(await response.arrayBuffer()) : new Uint8Array(0);
737
- return {
738
- ok: true,
739
- status: response.status,
740
- statusText: response.statusText,
741
- headers: response.headers,
742
- body: bytes
743
- };
744
- }
745
- }
746
- /**
747
- * Connect to this disk's data plane via the native ArchilClient.
748
- *
749
- * Requires the native module to be available (platform-specific .node binary).
750
- */
751
- async mount(opts) {
752
- let ArchilClient;
753
- try {
754
- const nativeSpecifier = "@archildata/native";
755
- const native = await import(nativeSpecifier);
756
- ArchilClient = native.ArchilClient ?? native.default?.ArchilClient;
757
- if (!ArchilClient) {
758
- throw new Error("@archildata/native did not export ArchilClient");
759
- }
760
- } catch {
761
- throw new Error(
762
- "Native client not available. Install @archildata/native (platform-specific binary) or use ArchilClient.connect() directly. mount() is not supported in browsers."
763
- );
764
- }
765
- return ArchilClient.connect({
766
- region: this._archilRegion,
767
- diskName: `${this.organization}/${this.name}`,
768
- authToken: opts?.authToken,
769
- logLevel: opts?.logLevel,
770
- serverAddress: opts?.serverAddress,
771
- insecure: opts?.insecure
772
- });
773
- }
172
+ id;
173
+ name;
174
+ organization;
175
+ status;
176
+ provider;
177
+ region;
178
+ createdAt;
179
+ fsHandlerStatus;
180
+ lastAccessed;
181
+ dataSize;
182
+ monthlyUsage;
183
+ mounts;
184
+ metrics;
185
+ connectedClients;
186
+ authorizedUsers;
187
+ allowedIps;
188
+ /** @internal */
189
+ _client;
190
+ /** @internal */
191
+ _archilRegion;
192
+ /** Base URL for the S3-compatible API (port 9000 ingress). Empty if unset. */
193
+ _s3BaseUrl;
194
+ /** Lazily-constructed multipart namespace (see {@link multipart}). @internal */
195
+ _multipart;
196
+ /** @internal */
197
+ constructor(data, client, archilRegion, s3BaseUrl) {
198
+ this.id = data.id;
199
+ this.name = data.name;
200
+ this.organization = data.organization;
201
+ this.status = data.status;
202
+ this.provider = data.provider;
203
+ this.region = data.region;
204
+ this.createdAt = data.createdAt;
205
+ this.fsHandlerStatus = data.fsHandlerStatus;
206
+ this.lastAccessed = data.lastAccessed;
207
+ this.dataSize = data.dataSize;
208
+ this.monthlyUsage = data.monthlyUsage;
209
+ this.mounts = data.mounts;
210
+ this.metrics = data.metrics;
211
+ this.connectedClients = data.connectedClients;
212
+ this.authorizedUsers = data.authorizedUsers;
213
+ this.allowedIps = data.allowedIps;
214
+ this._client = client;
215
+ this._archilRegion = archilRegion;
216
+ this._s3BaseUrl = s3BaseUrl ?? "";
217
+ }
218
+ toJSON() {
219
+ return {
220
+ id: this.id,
221
+ name: this.name,
222
+ organization: this.organization,
223
+ status: this.status,
224
+ provider: this.provider,
225
+ region: this.region,
226
+ createdAt: this.createdAt,
227
+ fsHandlerStatus: this.fsHandlerStatus,
228
+ lastAccessed: this.lastAccessed,
229
+ dataSize: this.dataSize,
230
+ monthlyUsage: this.monthlyUsage,
231
+ mounts: this.mounts,
232
+ metrics: this.metrics,
233
+ connectedClients: this.connectedClients,
234
+ authorizedUsers: this.authorizedUsers,
235
+ allowedIps: this.allowedIps
236
+ };
237
+ }
238
+ async addUser(user) {
239
+ return unwrap(this._client.POST("/api/disks/{id}/users", {
240
+ params: { path: { id: this.id } },
241
+ body: user
242
+ }));
243
+ }
244
+ async removeUser(userType, identifier) {
245
+ await unwrapEmpty(this._client.DELETE("/api/disks/{id}/users/{userType}", { params: {
246
+ path: {
247
+ id: this.id,
248
+ userType
249
+ },
250
+ query: { identifier }
251
+ } }));
252
+ }
253
+ async createToken(nickname) {
254
+ const user = await unwrap(this._client.POST("/api/disks/{id}/users", {
255
+ params: { path: { id: this.id } },
256
+ body: {
257
+ type: "token",
258
+ nickname
259
+ }
260
+ }));
261
+ if (!user.token || !user.identifier) throw new Error("Server did not return a generated token");
262
+ return user;
263
+ }
264
+ async removeTokenUser(identifier) {
265
+ await this.removeUser("token", identifier);
266
+ }
267
+ async getAllowedIPs() {
268
+ return (await unwrap(this._client.GET("/api/disks/{id}/allowed-ips", { params: { path: { id: this.id } } }))).allowedIps;
269
+ }
270
+ async setAllowedIPs(allowedIps) {
271
+ return (await unwrap(this._client.PUT("/api/disks/{id}/allowed-ips", {
272
+ params: { path: { id: this.id } },
273
+ body: { allowedIps }
274
+ }))).allowedIps;
275
+ }
276
+ async addAllowedIP(ip) {
277
+ const current = await this.getAllowedIPs();
278
+ if (current.includes(ip)) return current;
279
+ return this.setAllowedIPs([...current, ip]);
280
+ }
281
+ async removeAllowedIP(ip) {
282
+ const current = await this.getAllowedIPs();
283
+ return this.setAllowedIPs(current.filter((i) => i !== ip));
284
+ }
285
+ async delete() {
286
+ await unwrapEmpty(this._client.DELETE("/api/disks/{id}", { params: { path: { id: this.id } } }));
287
+ }
288
+ /**
289
+ * Execute a command in a container with this disk mounted.
290
+ * Blocks until the command completes and returns stdout, stderr, and exit code.
291
+ */
292
+ async exec(command) {
293
+ return unwrap(this._client.POST("/api/disks/{id}/exec", {
294
+ params: { path: { id: this.id } },
295
+ body: { command }
296
+ }));
297
+ }
298
+ /**
299
+ * Constant-time parallel grep across files on this disk. Listing and
300
+ * matching are fanned out across ephemeral exec containers; the request
301
+ * finishes within the supplied time budget regardless of dataset size.
302
+ *
303
+ * The returned `stoppedReason` says whether the search ran to completion
304
+ * or short-circuited on `maxResults` / `maxDurationSeconds`. When
305
+ * stopping early, the matches returned are a sample (whichever workers
306
+ * reported first), not the lexicographically first N.
307
+ */
308
+ async grep(opts) {
309
+ return unwrap(this._client.POST("/api/disks/{id}/grep", {
310
+ params: { path: { id: this.id } },
311
+ body: {
312
+ directory: opts.directory,
313
+ pattern: opts.pattern,
314
+ recursive: opts.recursive ?? false,
315
+ maxDurationSeconds: opts.maxDurationSeconds ?? 30,
316
+ concurrency: opts.concurrency ?? 50,
317
+ maxResults: opts.maxResults ?? 1e3
318
+ }
319
+ }));
320
+ }
321
+ /**
322
+ * Create a signed, time-limited URL that lets anyone download a single file
323
+ * from this disk without authentication. The returned URL embeds a
324
+ * cryptographically signed token carrying the disk, the file's key, and an
325
+ * expiry — share it directly; no API key is needed to redeem it.
326
+ *
327
+ * @param key Path to the file on the disk (e.g. "reports/2026-01/data.pdf").
328
+ * @param opts `expiresIn` sets the URL lifetime in seconds (any positive
329
+ * integer, max 604800 = 7 days). Defaults to 24h.
330
+ */
331
+ async share(key, opts = {}) {
332
+ const body = { key };
333
+ if (opts.expiresIn !== void 0) body.expiresIn = opts.expiresIn;
334
+ const call = this._client.POST;
335
+ return unwrap(call(`/api/disks/${this.id}/share`, { body }));
336
+ }
337
+ /**
338
+ * Read an object from the disk via the S3-compatible GetObject API and return
339
+ * its full contents as bytes. Throws `ArchilS3Error` if the object does not
340
+ * exist (status 404, code "NoSuchKey") or the request is rejected; use
341
+ * `headObject`/`objectExists` to check existence without throwing.
342
+ *
343
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
344
+ */
345
+ async getObject(key) {
346
+ const resp = await this._s3Request("GET", key);
347
+ if (!resp.ok) throw parseS3Error("GetObject", resp.status, resp.statusText, decodeText(resp.body));
348
+ return resp.body;
349
+ }
350
+ /**
351
+ * Fetch an object's metadata (size, etag, content type, last-modified) without
352
+ * downloading its contents, via the S3-compatible HeadObject API. Returns
353
+ * `null` if the object does not exist.
354
+ *
355
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
356
+ */
357
+ async headObject(key) {
358
+ const resp = await this._s3Request("HEAD", key);
359
+ if (resp.status === 404) return null;
360
+ if (!resp.ok) throw parseS3Error("HeadObject", resp.status, resp.statusText, decodeText(resp.body));
361
+ const lastModified = resp.headers.get("last-modified");
362
+ return {
363
+ size: Number(resp.headers.get("content-length") ?? 0),
364
+ etag: resp.headers.get("etag") ?? void 0,
365
+ contentType: resp.headers.get("content-type") ?? void 0,
366
+ lastModified: lastModified ? new Date(lastModified) : void 0
367
+ };
368
+ }
369
+ /** Whether an object exists on the disk (a HeadObject that maps 404 → false). */
370
+ async objectExists(key) {
371
+ return await this.headObject(key) !== null;
372
+ }
373
+ /**
374
+ * Write an object to the disk via the S3-compatible API. Handles any size:
375
+ * bodies at or below `multipartThreshold` (defaults to `partSize`, i.e.
376
+ * 16 MiB) go through a single PutObject request; larger bodies are uploaded as
377
+ * a multipart upload split into `partSize` parts, uploaded with bounded
378
+ * `concurrency` (default 4), and assembled. A failed part aborts the upload so
379
+ * nothing is left half-staged. For manual control over the multipart
380
+ * lifecycle, use the {@link multipart} namespace.
381
+ *
382
+ * Faster than exec for large files — no container overhead, no command-length
383
+ * limits. Returns the entity tag the server assigned (a multipart upload's tag
384
+ * is S3's `md5(concat(partMd5s))-N` form rather than a plain MD5).
385
+ *
386
+ * @param key Path on the disk (e.g. "reports/2026-01/data.json")
387
+ * @param body Contents as a string, Uint8Array/Buffer, or ArrayBuffer
388
+ * @param options Either a content-type string, or {@link PutObjectOptions}
389
+ * (`contentType`, `multipartThreshold`, `partSize`,
390
+ * `concurrency`). Content type defaults to
391
+ * "application/octet-stream".
392
+ */
393
+ async putObject(key, body, options) {
394
+ const opts = typeof options === "string" ? { contentType: options } : options ?? {};
395
+ const contentType = opts.contentType ?? "application/octet-stream";
396
+ const partSize = Math.max(opts.partSize ?? DEFAULT_PART_SIZE, MIN_PART_SIZE);
397
+ const threshold = opts.multipartThreshold ?? partSize;
398
+ const bytes = toBytes(body);
399
+ if (bytes.length <= threshold) {
400
+ const resp = await this._s3Request("PUT", key, {
401
+ body,
402
+ contentType
403
+ });
404
+ if (!resp.ok) throw parseS3Error("PutObject", resp.status, resp.statusText, decodeText(resp.body));
405
+ return { etag: resp.headers.get("etag") ?? void 0 };
406
+ }
407
+ return this._putMultipart(key, bytes, contentType, partSize, Math.max(1, opts.concurrency ?? DEFAULT_UPLOAD_CONCURRENCY));
408
+ }
409
+ /**
410
+ * Upload a large body through the multipart lifecycle: split into `partSize`
411
+ * parts, upload them with bounded concurrency, then complete — aborting the
412
+ * upload if any part fails so nothing is left half-staged. @internal
413
+ */
414
+ async _putMultipart(key, bytes, contentType, partSize, concurrency) {
415
+ const effectivePartSize = effectiveUploadPartSize(bytes.length, partSize);
416
+ const mp = this.multipart;
417
+ const upload = await mp.create(key, contentType);
418
+ try {
419
+ const partCount = Math.ceil(bytes.length / effectivePartSize);
420
+ const parts = new Array(partCount);
421
+ let next = 0;
422
+ const worker = async () => {
423
+ for (;;) {
424
+ const index = next++;
425
+ if (index >= partCount) return;
426
+ const start = index * effectivePartSize;
427
+ const slice = bytes.subarray(start, Math.min(start + effectivePartSize, bytes.length));
428
+ parts[index] = await mp.uploadPart(key, upload.uploadId, index + 1, slice);
429
+ }
430
+ };
431
+ await Promise.all(Array.from({ length: Math.min(concurrency, partCount) }, worker));
432
+ return { etag: (await mp.complete(key, upload.uploadId, parts)).etag };
433
+ } catch (err) {
434
+ await mp.abort(key, upload.uploadId).catch(() => {});
435
+ throw err;
436
+ }
437
+ }
438
+ /**
439
+ * Append bytes to an object via the S3-compatible PutObject append extension
440
+ * (`?append=true`). If the object already exists the bytes are appended to it;
441
+ * if it doesn't, it is created. Returns the entity tag of the full object
442
+ * after the append.
443
+ *
444
+ * Each call may append at most 1 MiB — the server rejects a larger body with
445
+ * `EntityTooLarge`. To grow an object past that, append in chunks (or use
446
+ * {@link putObject} for a one-shot large write).
447
+ *
448
+ * Unlike most operations this is NOT auto-retried on a transient error:
449
+ * append isn't idempotent, so retrying a succeeded-but-unacknowledged append
450
+ * would duplicate the bytes. On a transient failure, re-append yourself only
451
+ * after confirming the object's size.
452
+ *
453
+ * @param key Path on the disk (e.g. "logs/app.log")
454
+ * @param body Bytes to append (string, Uint8Array/Buffer, or ArrayBuffer)
455
+ * @param contentType MIME type, applied only when the object is newly created.
456
+ */
457
+ async appendObject(key, body, contentType = "application/octet-stream") {
458
+ const resp = await this._s3Request("PUT", key, {
459
+ body,
460
+ contentType,
461
+ query: { append: "true" },
462
+ retry: false
463
+ });
464
+ if (!resp.ok) throw parseS3Error("AppendObject", resp.status, resp.statusText, decodeText(resp.body));
465
+ return { etag: resp.headers.get("etag") ?? void 0 };
466
+ }
467
+ /**
468
+ * Delete an object from the disk via the S3-compatible DeleteObject API.
469
+ * Idempotent: deleting a key that doesn't exist resolves successfully, per
470
+ * S3 semantics.
471
+ *
472
+ * @param key Path on the disk (e.g. "project/dist/server.cjs")
473
+ */
474
+ async deleteObject(key) {
475
+ const resp = await this._s3Request("DELETE", key);
476
+ if (!resp.ok && resp.status !== 404) throw parseS3Error("DeleteObject", resp.status, resp.statusText, decodeText(resp.body));
477
+ }
478
+ /**
479
+ * List objects on the disk via the S3-compatible ListObjectsV2 API. By
480
+ * default this follows continuation tokens until the listing is exhausted and
481
+ * returns every matching key. Use `limit` to cap the total, `singlePage` for a
482
+ * single request, or {@link listObjectsPages} to stream pages without loading
483
+ * everything into memory.
484
+ *
485
+ * @param prefix Only return keys beginning with this prefix (omit for all).
486
+ * @param opts Listing and pagination options.
487
+ */
488
+ async listObjects(prefix, opts = {}) {
489
+ if (opts.singlePage) return this._listObjectsPage(prefix, opts);
490
+ const objects = [];
491
+ const commonPrefixes = [];
492
+ const seenPrefixes = /* @__PURE__ */ new Set();
493
+ let echoedPrefix;
494
+ let truncated = false;
495
+ outer: for await (const page of this.listObjectsPages(prefix, opts)) {
496
+ echoedPrefix = page.prefix;
497
+ for (const cp of page.commonPrefixes) if (!seenPrefixes.has(cp)) {
498
+ seenPrefixes.add(cp);
499
+ commonPrefixes.push(cp);
500
+ }
501
+ for (const obj of page.objects) {
502
+ if (opts.limit !== void 0 && objects.length >= opts.limit) {
503
+ truncated = true;
504
+ break outer;
505
+ }
506
+ objects.push(obj);
507
+ }
508
+ }
509
+ return {
510
+ objects,
511
+ commonPrefixes,
512
+ isTruncated: truncated,
513
+ keyCount: objects.length,
514
+ prefix: echoedPrefix
515
+ };
516
+ }
517
+ /**
518
+ * Yield ListObjectsV2 pages lazily, following continuation tokens. A
519
+ * memory-friendly way to process a large listing without materializing it:
520
+ *
521
+ * ```ts
522
+ * for await (const page of disk.listObjectsPages("logs/")) {
523
+ * for (const obj of page.objects) process(obj);
524
+ * }
525
+ * ```
526
+ *
527
+ * @param prefix Only return keys beginning with this prefix (omit for all).
528
+ * @param opts Listing options (`limit` / `singlePage` are ignored here —
529
+ * control your own loop).
530
+ */
531
+ async *listObjectsPages(prefix, opts = {}) {
532
+ const seenTokens = /* @__PURE__ */ new Set();
533
+ let continuationToken = opts.continuationToken;
534
+ for (;;) {
535
+ const page = await this._listObjectsPage(prefix, {
536
+ ...opts,
537
+ continuationToken
538
+ });
539
+ yield page;
540
+ const next = page.isTruncated ? page.nextContinuationToken : void 0;
541
+ if (!next || seenTokens.has(next)) break;
542
+ seenTokens.add(next);
543
+ continuationToken = next;
544
+ }
545
+ }
546
+ /** Fetch a single ListObjectsV2 page. @internal */
547
+ async _listObjectsPage(prefix, opts) {
548
+ const query = { "list-type": 2 };
549
+ if (prefix !== void 0) query.prefix = prefix;
550
+ if (!opts.recursive) query.delimiter = "/";
551
+ if (opts.continuationToken !== void 0) query["continuation-token"] = opts.continuationToken;
552
+ if (opts.startAfter !== void 0) query["start-after"] = opts.startAfter;
553
+ const resp = await this._s3Request("GET", "", { query });
554
+ if (!resp.ok) throw parseS3Error("ListObjectsV2", resp.status, resp.statusText, decodeText(resp.body));
555
+ return parseListObjectsResult(decodeText(resp.body));
556
+ }
557
+ /**
558
+ * Delete up to many objects in a single S3-compatible DeleteObjects request.
559
+ * Unlike {@link deleteObject}, failures are reported per key rather than
560
+ * thrown: the result's `deleted` lists the keys that were removed and
561
+ * `errors` lists the ones that weren't (with the server's code/message). A
562
+ * key that didn't exist still counts as deleted, per S3 semantics.
563
+ *
564
+ * The server caps a single request at 1000 keys; this method transparently
565
+ * splits larger inputs into 1000-key batches and merges the results.
566
+ *
567
+ * @param keys Object keys to delete.
568
+ * @param opts `quiet` suppresses the per-key success list server-side.
569
+ */
570
+ async deleteObjects(keys, opts = {}) {
571
+ const deleted = [];
572
+ const errors = [];
573
+ for (let i = 0; i < keys.length; i += MAX_DELETE_OBJECTS_PER_REQUEST) {
574
+ const xml = buildDeleteObjectsXml(keys.slice(i, i + MAX_DELETE_OBJECTS_PER_REQUEST), opts.quiet ?? false);
575
+ const resp = await this._s3Request("POST", "", {
576
+ query: { delete: "" },
577
+ body: xml,
578
+ contentType: "application/xml"
579
+ });
580
+ if (!resp.ok) throw parseS3Error("DeleteObjects", resp.status, resp.statusText, decodeText(resp.body));
581
+ const parsed = parseDeleteObjectsResult(decodeText(resp.body));
582
+ deleted.push(...parsed.deleted);
583
+ errors.push(...parsed.errors);
584
+ }
585
+ return {
586
+ deleted,
587
+ errors
588
+ };
589
+ }
590
+ /**
591
+ * The advanced, opt-in multipart-upload API. Drive the raw lifecycle
592
+ * yourself `create` `uploadPart` `complete` (or `abort`), plus
593
+ * `listParts` / `listUploads`. Most callers don't need this: {@link putObject}
594
+ * runs the whole lifecycle automatically for large bodies. Reach for it only
595
+ * when you need manual control (e.g. uploading parts from separate processes),
596
+ * and note you then own part-size, memory, and concurrency management.
597
+ */
598
+ get multipart() {
599
+ return this._multipart ??= new DiskMultipart(this.id, this._s3Request.bind(this));
600
+ }
601
+ /**
602
+ * Send a single request to the disk's S3-compatible endpoint. This reuses the
603
+ * control-plane client purely for its credential and transport — the same
604
+ * `Authorization` header is sent and verified by the same code server-side —
605
+ * pointed at the S3 host. Returns the response status and fully-buffered body
606
+ * so callers can inspect both regardless of the verb used.
607
+ *
608
+ * The S3 routes (`/{diskId}/{key}` for objects, `/{diskId}` for the bucket)
609
+ * are not part of the typed control-plane API, so the path and per-request
610
+ * options are passed untyped. An empty `key` targets the bucket itself (used
611
+ * by listObjects).
612
+ *
613
+ * @internal
614
+ */
615
+ async _s3Request(method, key, opts = {}) {
616
+ if (!this._s3BaseUrl) throw new Error("S3 base URL not configured. Pass s3BaseUrl to new Archil({...}) or set ARCHIL_S3_BASE_URL.");
617
+ const call = this._client[method];
618
+ const encodedKey = key.replace(/^\//, "").split("/").map(encodeURIComponent).join("/");
619
+ const path = encodedKey ? `/${this.id}/${encodedKey}` : `/${this.id}`;
620
+ const init = {
621
+ baseUrl: this._s3BaseUrl,
622
+ parseAs: "stream",
623
+ ...opts.query ? { params: { query: opts.query } } : {},
624
+ ...opts.body !== void 0 ? {
625
+ body: opts.body,
626
+ bodySerializer: (b) => b
627
+ } : {},
628
+ ...opts.contentType ? { headers: { "Content-Type": opts.contentType } } : {}
629
+ };
630
+ const hasBody = method === "GET" || method === "POST";
631
+ const maxRetries = opts.retry === false ? 0 : MAX_S3_RETRIES;
632
+ for (let attempt = 0;; attempt++) {
633
+ let error;
634
+ let response;
635
+ try {
636
+ ({error, response} = await call(path, init));
637
+ } catch (transportError) {
638
+ if (attempt < maxRetries) {
639
+ await sleep(s3RetryDelayMs(attempt));
640
+ continue;
641
+ }
642
+ throw transportError;
643
+ }
644
+ if (!response.ok) {
645
+ if (isTransientS3Status(response.status) && attempt < maxRetries) {
646
+ await response.body?.cancel().catch(() => {});
647
+ await sleep(s3RetryDelayMs(attempt));
648
+ continue;
649
+ }
650
+ const message = typeof error === "string" ? error : error ? JSON.stringify(error) : "";
651
+ return {
652
+ ok: false,
653
+ status: response.status,
654
+ statusText: response.statusText,
655
+ headers: response.headers,
656
+ body: new TextEncoder().encode(message)
657
+ };
658
+ }
659
+ const bytes = hasBody ? new Uint8Array(await response.arrayBuffer()) : /* @__PURE__ */ new Uint8Array(0);
660
+ return {
661
+ ok: true,
662
+ status: response.status,
663
+ statusText: response.statusText,
664
+ headers: response.headers,
665
+ body: bytes
666
+ };
667
+ }
668
+ }
669
+ /**
670
+ * Connect to this disk's data plane via the native ArchilClient.
671
+ *
672
+ * Requires the native module to be available (platform-specific .node binary).
673
+ */
674
+ async mount(opts) {
675
+ let ArchilClient;
676
+ try {
677
+ const native = await import("@archildata/native");
678
+ ArchilClient = native.ArchilClient ?? native.default?.ArchilClient;
679
+ if (!ArchilClient) throw new Error("@archildata/native did not export ArchilClient");
680
+ } catch {
681
+ throw new Error("Native client not available. Install @archildata/native (platform-specific binary) or use ArchilClient.connect() directly. mount() is not supported in browsers.");
682
+ }
683
+ return ArchilClient.connect({
684
+ region: this._archilRegion,
685
+ diskName: `${this.organization}/${this.name}`,
686
+ authToken: opts?.authToken,
687
+ logLevel: opts?.logLevel,
688
+ serverAddress: opts?.serverAddress,
689
+ insecure: opts?.insecure
690
+ });
691
+ }
774
692
  };
693
+ /**
694
+ * The advanced, opt-in multipart-upload namespace, reached via {@link Disk.multipart}.
695
+ * Drives the raw S3 multipart lifecycle — `create` → `uploadPart` → `complete`
696
+ * (or `abort`), plus `listParts` / `listUploads`. Prefer {@link Disk.putObject},
697
+ * which runs this lifecycle automatically for large bodies; use this only when
698
+ * you need manual control, in which case you own part-size, memory, and
699
+ * concurrency management.
700
+ */
775
701
  var DiskMultipart = class {
776
- /** @internal */
777
- constructor(diskId, s3Request) {
778
- this.diskId = diskId;
779
- this.s3Request = s3Request;
780
- }
781
- diskId;
782
- s3Request;
783
- /**
784
- * Start a multipart upload (CreateMultipartUpload) and return its `uploadId`.
785
- *
786
- * @param key Path on the disk the finished object will live at.
787
- * @param contentType MIME type to store the object with.
788
- */
789
- async create(key, contentType) {
790
- const resp = await this.s3Request("POST", key, { query: { uploads: "" }, contentType });
791
- if (!resp.ok) {
792
- throw parseS3Error("CreateMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
793
- }
794
- const root = parseXml(decodeText(resp.body)).InitiateMultipartUploadResult ?? {};
795
- const uploadId = optionalString(root.UploadId);
796
- if (!uploadId) {
797
- throw new ArchilS3Error({
798
- operation: "CreateMultipartUpload",
799
- statusCode: resp.status,
800
- message: "response did not contain an UploadId",
801
- raw: decodeText(resp.body)
802
- });
803
- }
804
- return {
805
- uploadId,
806
- key: optionalString(root.Key) ?? key,
807
- bucket: optionalString(root.Bucket) ?? this.diskId
808
- };
809
- }
810
- /**
811
- * Upload one part (UploadPart) and return its entity tag, which you must
812
- * collect (with its part number) and pass to {@link complete}. Every part
813
- * except the last must be at least 5 MiB.
814
- *
815
- * @param key The upload's object key.
816
- * @param uploadId The id from {@link create}.
817
- * @param partNumber 1-based part number (1..=10000).
818
- * @param body Part contents as a string, Uint8Array/Buffer, or ArrayBuffer.
819
- */
820
- async uploadPart(key, uploadId, partNumber, body) {
821
- const resp = await this.s3Request("PUT", key, { query: { uploadId, partNumber }, body });
822
- if (!resp.ok) {
823
- throw parseS3Error("UploadPart", resp.status, resp.statusText, decodeText(resp.body));
824
- }
825
- return { partNumber, etag: resp.headers.get("etag") ?? "" };
826
- }
827
- /**
828
- * Finish a multipart upload (CompleteMultipartUpload), assembling the listed
829
- * parts into one object. Parts are sorted by part number before submission
830
- * (the server requires strictly-increasing order).
831
- *
832
- * Unlike the other operations this is NOT auto-retried on a transient error:
833
- * the gateway isn't idempotent for completion, so a retry after a
834
- * successful-but-unacknowledged complete would return a spurious NoSuchUpload.
835
- * On a transient failure, re-drive completion yourself only after confirming
836
- * the object isn't already present.
837
- *
838
- * @param key The upload's object key.
839
- * @param uploadId The id from {@link create}.
840
- * @param parts The `{ partNumber, etag }` pairs from {@link uploadPart}.
841
- */
842
- async complete(key, uploadId, parts) {
843
- const sorted = [...parts].sort((a, b) => a.partNumber - b.partNumber);
844
- const xml = buildCompleteMultipartUploadXml(sorted);
845
- const resp = await this.s3Request("POST", key, {
846
- query: { uploadId },
847
- body: xml,
848
- contentType: "application/xml",
849
- retry: false
850
- });
851
- if (!resp.ok) {
852
- throw parseS3Error("CompleteMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
853
- }
854
- const root = parseXml(decodeText(resp.body)).CompleteMultipartUploadResult ?? {};
855
- return {
856
- etag: optionalString(root.ETag),
857
- location: optionalString(root.Location),
858
- bucket: optionalString(root.Bucket),
859
- key: optionalString(root.Key)
860
- };
861
- }
862
- /**
863
- * Abort a multipart upload (AbortMultipartUpload), discarding every staged
864
- * part. Idempotent against an upload that's already gone (404 / NoSuchUpload
865
- * resolves successfully).
866
- *
867
- * @param key The upload's object key.
868
- * @param uploadId The id from {@link create}.
869
- */
870
- async abort(key, uploadId) {
871
- const resp = await this.s3Request("DELETE", key, { query: { uploadId } });
872
- if (!resp.ok && resp.status !== 404) {
873
- throw parseS3Error("AbortMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
874
- }
875
- }
876
- /**
877
- * List the parts already uploaded for an in-progress upload (ListParts).
878
- * Returns a single page; follow `nextPartNumberMarker` (when `isTruncated`)
879
- * to page through the rest.
880
- *
881
- * @param key The upload's object key.
882
- * @param uploadId The id from {@link create}.
883
- * @param opts `maxParts` / `partNumberMarker` pagination controls.
884
- */
885
- async listParts(key, uploadId, opts = {}) {
886
- const query = { uploadId };
887
- if (opts.maxParts !== void 0) query["max-parts"] = opts.maxParts;
888
- if (opts.partNumberMarker !== void 0) query["part-number-marker"] = opts.partNumberMarker;
889
- const resp = await this.s3Request("GET", key, { query });
890
- if (!resp.ok) {
891
- throw parseS3Error("ListParts", resp.status, resp.statusText, decodeText(resp.body));
892
- }
893
- return parseListPartsResult(decodeText(resp.body));
894
- }
895
- /**
896
- * List in-progress multipart uploads on the disk (ListMultipartUploads).
897
- * Returns a single page; follow `nextKeyMarker` / `nextUploadIdMarker` (when
898
- * `isTruncated`) for the rest.
899
- *
900
- * @param opts Prefix/delimiter filter and pagination markers.
901
- */
902
- async listUploads(opts = {}) {
903
- const query = { uploads: "" };
904
- if (opts.prefix !== void 0) query.prefix = opts.prefix;
905
- if (opts.delimiter !== void 0) query.delimiter = opts.delimiter;
906
- if (opts.keyMarker !== void 0) query["key-marker"] = opts.keyMarker;
907
- if (opts.uploadIdMarker !== void 0) query["upload-id-marker"] = opts.uploadIdMarker;
908
- if (opts.maxUploads !== void 0) query["max-uploads"] = opts.maxUploads;
909
- const resp = await this.s3Request("GET", "", { query });
910
- if (!resp.ok) {
911
- throw parseS3Error("ListMultipartUploads", resp.status, resp.statusText, decodeText(resp.body));
912
- }
913
- return parseListMultipartUploadsResult(decodeText(resp.body));
914
- }
702
+ diskId;
703
+ s3Request;
704
+ /** @internal */
705
+ constructor(diskId, s3Request) {
706
+ this.diskId = diskId;
707
+ this.s3Request = s3Request;
708
+ }
709
+ /**
710
+ * Start a multipart upload (CreateMultipartUpload) and return its `uploadId`.
711
+ *
712
+ * @param key Path on the disk the finished object will live at.
713
+ * @param contentType MIME type to store the object with.
714
+ */
715
+ async create(key, contentType) {
716
+ const resp = await this.s3Request("POST", key, {
717
+ query: { uploads: "" },
718
+ contentType
719
+ });
720
+ if (!resp.ok) throw parseS3Error("CreateMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
721
+ const root = parseXml(decodeText(resp.body)).InitiateMultipartUploadResult ?? {};
722
+ const uploadId = optionalString(root.UploadId);
723
+ if (!uploadId) throw new ArchilS3Error({
724
+ operation: "CreateMultipartUpload",
725
+ statusCode: resp.status,
726
+ message: "response did not contain an UploadId",
727
+ raw: decodeText(resp.body)
728
+ });
729
+ return {
730
+ uploadId,
731
+ key: optionalString(root.Key) ?? key,
732
+ bucket: optionalString(root.Bucket) ?? this.diskId
733
+ };
734
+ }
735
+ /**
736
+ * Upload one part (UploadPart) and return its entity tag, which you must
737
+ * collect (with its part number) and pass to {@link complete}. Every part
738
+ * except the last must be at least 5 MiB.
739
+ *
740
+ * @param key The upload's object key.
741
+ * @param uploadId The id from {@link create}.
742
+ * @param partNumber 1-based part number (1..=10000).
743
+ * @param body Part contents as a string, Uint8Array/Buffer, or ArrayBuffer.
744
+ */
745
+ async uploadPart(key, uploadId, partNumber, body) {
746
+ const resp = await this.s3Request("PUT", key, {
747
+ query: {
748
+ uploadId,
749
+ partNumber
750
+ },
751
+ body
752
+ });
753
+ if (!resp.ok) throw parseS3Error("UploadPart", resp.status, resp.statusText, decodeText(resp.body));
754
+ return {
755
+ partNumber,
756
+ etag: resp.headers.get("etag") ?? ""
757
+ };
758
+ }
759
+ /**
760
+ * Finish a multipart upload (CompleteMultipartUpload), assembling the listed
761
+ * parts into one object. Parts are sorted by part number before submission
762
+ * (the server requires strictly-increasing order).
763
+ *
764
+ * Unlike the other operations this is NOT auto-retried on a transient error:
765
+ * the gateway isn't idempotent for completion, so a retry after a
766
+ * successful-but-unacknowledged complete would return a spurious NoSuchUpload.
767
+ * On a transient failure, re-drive completion yourself only after confirming
768
+ * the object isn't already present.
769
+ *
770
+ * @param key The upload's object key.
771
+ * @param uploadId The id from {@link create}.
772
+ * @param parts The `{ partNumber, etag }` pairs from {@link uploadPart}.
773
+ */
774
+ async complete(key, uploadId, parts) {
775
+ const xml = buildCompleteMultipartUploadXml([...parts].sort((a, b) => a.partNumber - b.partNumber));
776
+ const resp = await this.s3Request("POST", key, {
777
+ query: { uploadId },
778
+ body: xml,
779
+ contentType: "application/xml",
780
+ retry: false
781
+ });
782
+ if (!resp.ok) throw parseS3Error("CompleteMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
783
+ const root = parseXml(decodeText(resp.body)).CompleteMultipartUploadResult ?? {};
784
+ return {
785
+ etag: optionalString(root.ETag),
786
+ location: optionalString(root.Location),
787
+ bucket: optionalString(root.Bucket),
788
+ key: optionalString(root.Key)
789
+ };
790
+ }
791
+ /**
792
+ * Abort a multipart upload (AbortMultipartUpload), discarding every staged
793
+ * part. Idempotent against an upload that's already gone (404 / NoSuchUpload
794
+ * resolves successfully).
795
+ *
796
+ * @param key The upload's object key.
797
+ * @param uploadId The id from {@link create}.
798
+ */
799
+ async abort(key, uploadId) {
800
+ const resp = await this.s3Request("DELETE", key, { query: { uploadId } });
801
+ if (!resp.ok && resp.status !== 404) throw parseS3Error("AbortMultipartUpload", resp.status, resp.statusText, decodeText(resp.body));
802
+ }
803
+ /**
804
+ * List the parts already uploaded for an in-progress upload (ListParts).
805
+ * Returns a single page; follow `nextPartNumberMarker` (when `isTruncated`)
806
+ * to page through the rest.
807
+ *
808
+ * @param key The upload's object key.
809
+ * @param uploadId The id from {@link create}.
810
+ * @param opts `maxParts` / `partNumberMarker` pagination controls.
811
+ */
812
+ async listParts(key, uploadId, opts = {}) {
813
+ const query = { uploadId };
814
+ if (opts.maxParts !== void 0) query["max-parts"] = opts.maxParts;
815
+ if (opts.partNumberMarker !== void 0) query["part-number-marker"] = opts.partNumberMarker;
816
+ const resp = await this.s3Request("GET", key, { query });
817
+ if (!resp.ok) throw parseS3Error("ListParts", resp.status, resp.statusText, decodeText(resp.body));
818
+ return parseListPartsResult(decodeText(resp.body));
819
+ }
820
+ /**
821
+ * List in-progress multipart uploads on the disk (ListMultipartUploads).
822
+ * Returns a single page; follow `nextKeyMarker` / `nextUploadIdMarker` (when
823
+ * `isTruncated`) for the rest.
824
+ *
825
+ * @param opts Prefix/delimiter filter and pagination markers.
826
+ */
827
+ async listUploads(opts = {}) {
828
+ const query = { uploads: "" };
829
+ if (opts.prefix !== void 0) query.prefix = opts.prefix;
830
+ if (opts.delimiter !== void 0) query.delimiter = opts.delimiter;
831
+ if (opts.keyMarker !== void 0) query["key-marker"] = opts.keyMarker;
832
+ if (opts.uploadIdMarker !== void 0) query["upload-id-marker"] = opts.uploadIdMarker;
833
+ if (opts.maxUploads !== void 0) query["max-uploads"] = opts.maxUploads;
834
+ const resp = await this.s3Request("GET", "", { query });
835
+ if (!resp.ok) throw parseS3Error("ListMultipartUploads", resp.status, resp.statusText, decodeText(resp.body));
836
+ return parseListMultipartUploadsResult(decodeText(resp.body));
837
+ }
915
838
  };
916
- var MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
917
- var MAX_S3_RETRIES = 3;
918
- var S3_RETRY_BASE_MS = 100;
919
- var S3_RETRY_CAP_MS = 2e3;
839
+ /** S3's per-request cap on DeleteObjects keys; larger inputs are batched. */
840
+ const MAX_DELETE_OBJECTS_PER_REQUEST = 1e3;
841
+ /** Automatic retries for a transient S3 failure (5xx / 429 / network error). */
842
+ const MAX_S3_RETRIES = 3;
843
+ /** Base backoff for S3 retries (ms); grows exponentially, then full-jittered. */
844
+ const S3_RETRY_BASE_MS = 100;
845
+ /** Ceiling for a single retry backoff (ms). */
846
+ const S3_RETRY_CAP_MS = 2e3;
847
+ /**
848
+ * Statuses worth retrying: throttling (429) and the gateway's transient 5xx
849
+ * (e.g. a journal-commit timeout surfaced as 500). 4xx other than 429 are
850
+ * caller errors and never retried.
851
+ */
920
852
  function isTransientS3Status(status) {
921
- return status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
853
+ return status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
922
854
  }
855
+ /** Full-jittered exponential backoff for retry `attempt` (0-based). */
923
856
  function s3RetryDelayMs(attempt) {
924
- const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
925
- return Math.random() * ceiling;
857
+ const ceiling = Math.min(S3_RETRY_CAP_MS, S3_RETRY_BASE_MS * 2 ** attempt);
858
+ return Math.random() * ceiling;
926
859
  }
927
860
  function sleep(ms) {
928
- return new Promise((resolve) => setTimeout(resolve, ms));
861
+ return new Promise((resolve) => setTimeout(resolve, ms));
929
862
  }
930
- var MIN_PART_SIZE = 5 * 1024 * 1024;
931
- var DEFAULT_PART_SIZE = 16 * 1024 * 1024;
932
- var DEFAULT_UPLOAD_CONCURRENCY = 4;
933
- var MAX_PARTS_PER_UPLOAD = 1e4;
863
+ /** S3's minimum size for every multipart part but the last (5 MiB). */
864
+ const MIN_PART_SIZE = 5 * 1024 * 1024;
865
+ /** Default part size {@link Disk.putObject} uses on the multipart path (16 MiB). */
866
+ const DEFAULT_PART_SIZE = 16 * 1024 * 1024;
867
+ /** Default number of parts {@link Disk.putObject} uploads in parallel. */
868
+ const DEFAULT_UPLOAD_CONCURRENCY = 4;
869
+ /** The server's cap on parts in a single multipart upload (MAX_PARTS_PER_UPLOAD). */
870
+ const MAX_PARTS_PER_UPLOAD = 1e4;
871
+ /**
872
+ * Choose the part size for a `totalBytes` multipart upload. Returns
873
+ * `requestedPartSize` unless splitting at that size would exceed the server's
874
+ * 10,000-part cap, in which case it grows the part size (rounded up to a whole
875
+ * MiB) so the body fits in ≤ 10,000 parts — mirroring boto3's chunk-size
876
+ * adjustment. Parts only ever get larger, so they stay above the 5 MiB floor.
877
+ */
934
878
  function effectiveUploadPartSize(totalBytes, requestedPartSize) {
935
- if (Math.ceil(totalBytes / requestedPartSize) <= MAX_PARTS_PER_UPLOAD) {
936
- return requestedPartSize;
937
- }
938
- const MiB = 1024 * 1024;
939
- const needed = Math.ceil(totalBytes / MAX_PARTS_PER_UPLOAD);
940
- return Math.ceil(needed / MiB) * MiB;
879
+ if (Math.ceil(totalBytes / requestedPartSize) <= MAX_PARTS_PER_UPLOAD) return requestedPartSize;
880
+ const MiB = 1024 * 1024;
881
+ const needed = Math.ceil(totalBytes / MAX_PARTS_PER_UPLOAD);
882
+ return Math.ceil(needed / MiB) * MiB;
941
883
  }
884
+ /** Normalize an upload body to bytes so it can be sized and sliced into parts. */
942
885
  function toBytes(body) {
943
- if (typeof body === "string") return new TextEncoder().encode(body);
944
- if (body instanceof Uint8Array) return body;
945
- return new Uint8Array(body);
886
+ if (typeof body === "string") return new TextEncoder().encode(body);
887
+ if (body instanceof Uint8Array) return body;
888
+ return new Uint8Array(body);
946
889
  }
890
+ /** Escape text for safe inclusion in XML element content. */
947
891
  function escapeXml(value) {
948
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
892
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
949
893
  }
894
+ /** Build a `<Delete>` request body for the DeleteObjects API. */
950
895
  function buildDeleteObjectsXml(keys, quiet) {
951
- const objects = keys.map((k) => `<Object><Key>${escapeXml(k)}</Key></Object>`).join("");
952
- const quietTag = quiet ? "<Quiet>true</Quiet>" : "";
953
- return `<?xml version="1.0" encoding="UTF-8"?><Delete>${objects}${quietTag}</Delete>`;
896
+ return `<?xml version="1.0" encoding="UTF-8"?><Delete>${keys.map((k) => `<Object><Key>${escapeXml(k)}</Key></Object>`).join("")}${quiet ? "<Quiet>true</Quiet>" : ""}</Delete>`;
954
897
  }
898
+ /** Build a `<CompleteMultipartUpload>` request body from the uploaded parts. */
955
899
  function buildCompleteMultipartUploadXml(parts) {
956
- const body = parts.map(
957
- (p) => `<Part><PartNumber>${p.partNumber}</PartNumber><ETag>${escapeXml(p.etag)}</ETag></Part>`
958
- ).join("");
959
- return `<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${body}</CompleteMultipartUpload>`;
900
+ return `<?xml version="1.0" encoding="UTF-8"?><CompleteMultipartUpload>${parts.map((p) => `<Part><PartNumber>${p.partNumber}</PartNumber><ETag>${escapeXml(p.etag)}</ETag></Part>`).join("")}</CompleteMultipartUpload>`;
960
901
  }
902
+ /** Coerce a parser value that may be a single object or an array into an array. */
961
903
  function asArray(value) {
962
- if (value === void 0 || value === null) return [];
963
- return Array.isArray(value) ? value : [value];
904
+ if (value === void 0 || value === null) return [];
905
+ return Array.isArray(value) ? value : [value];
964
906
  }
965
907
  function optionalNumber(value) {
966
- return value === void 0 || value === null ? void 0 : Number(value);
908
+ return value === void 0 || value === null ? void 0 : Number(value);
967
909
  }
968
910
  function optionalString(value) {
969
- return value === void 0 || value === null ? void 0 : String(value);
911
+ return value === void 0 || value === null ? void 0 : String(value);
970
912
  }
971
913
  function optionalDate(value) {
972
- return value === void 0 || value === null ? void 0 : new Date(String(value));
914
+ return value === void 0 || value === null ? void 0 : new Date(String(value));
973
915
  }
916
+ /** Decode response bytes to a UTF-8 string (used for XML error/result bodies). */
974
917
  function decodeText(bytes) {
975
- return new TextDecoder().decode(bytes);
918
+ return new TextDecoder().decode(bytes);
976
919
  }
920
+ /** Parse an S3 ListObjectsV2 `<ListBucketResult>` XML document. */
977
921
  function parseListObjectsResult(xml) {
978
- const root = parseXml(xml).ListBucketResult ?? {};
979
- const contents = root.Contents ?? [];
980
- const objects = contents.map((c) => ({
981
- key: String(c.Key ?? ""),
982
- size: Number(c.Size ?? 0),
983
- etag: optionalString(c.ETag),
984
- lastModified: optionalDate(c.LastModified)
985
- }));
986
- const commonPrefixes = (root.CommonPrefixes ?? []).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0);
987
- return {
988
- objects,
989
- commonPrefixes,
990
- isTruncated: root.IsTruncated === "true" || root.IsTruncated === true,
991
- nextContinuationToken: optionalString(root.NextContinuationToken),
992
- keyCount: root.KeyCount !== void 0 ? Number(root.KeyCount) : objects.length,
993
- prefix: optionalString(root.Prefix)
994
- };
922
+ const root = parseXml(xml).ListBucketResult ?? {};
923
+ const objects = (root.Contents ?? []).map((c) => ({
924
+ key: String(c.Key ?? ""),
925
+ size: Number(c.Size ?? 0),
926
+ etag: optionalString(c.ETag),
927
+ lastModified: optionalDate(c.LastModified)
928
+ }));
929
+ return {
930
+ objects,
931
+ commonPrefixes: (root.CommonPrefixes ?? []).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0),
932
+ isTruncated: root.IsTruncated === "true" || root.IsTruncated === true,
933
+ nextContinuationToken: optionalString(root.NextContinuationToken),
934
+ keyCount: root.KeyCount !== void 0 ? Number(root.KeyCount) : objects.length,
935
+ prefix: optionalString(root.Prefix)
936
+ };
995
937
  }
996
938
  function xmlIsTruncated(value) {
997
- return value === "true" || value === true;
939
+ return value === "true" || value === true;
998
940
  }
941
+ /** Parse an S3 DeleteObjects `<DeleteResult>` XML document. */
999
942
  function parseDeleteObjectsResult(xml) {
1000
- const root = parseXml(xml).DeleteResult ?? {};
1001
- const deleted = asArray(root.Deleted).map((d) => optionalString(d.Key)).filter((k) => k !== void 0);
1002
- const errors = asArray(root.Error).map((e) => ({
1003
- key: String(e.Key ?? ""),
1004
- code: optionalString(e.Code),
1005
- message: optionalString(e.Message)
1006
- }));
1007
- return { deleted, errors };
943
+ const root = parseXml(xml).DeleteResult ?? {};
944
+ return {
945
+ deleted: asArray(root.Deleted).map((d) => optionalString(d.Key)).filter((k) => k !== void 0),
946
+ errors: asArray(root.Error).map((e) => ({
947
+ key: String(e.Key ?? ""),
948
+ code: optionalString(e.Code),
949
+ message: optionalString(e.Message)
950
+ }))
951
+ };
1008
952
  }
953
+ /** Parse an S3 `<ListPartsResult>` XML document. */
1009
954
  function parseListPartsResult(xml) {
1010
- const root = parseXml(xml).ListPartsResult ?? {};
1011
- const parts = asArray(root.Part).map((p) => ({
1012
- partNumber: Number(p.PartNumber ?? 0),
1013
- etag: optionalString(p.ETag),
1014
- size: Number(p.Size ?? 0),
1015
- lastModified: optionalDate(p.LastModified)
1016
- }));
1017
- return {
1018
- bucket: optionalString(root.Bucket),
1019
- key: optionalString(root.Key),
1020
- uploadId: optionalString(root.UploadId),
1021
- parts,
1022
- isTruncated: xmlIsTruncated(root.IsTruncated),
1023
- partNumberMarker: Number(root.PartNumberMarker ?? 0),
1024
- nextPartNumberMarker: optionalNumber(root.NextPartNumberMarker),
1025
- maxParts: Number(root.MaxParts ?? parts.length)
1026
- };
955
+ const root = parseXml(xml).ListPartsResult ?? {};
956
+ const parts = asArray(root.Part).map((p) => ({
957
+ partNumber: Number(p.PartNumber ?? 0),
958
+ etag: optionalString(p.ETag),
959
+ size: Number(p.Size ?? 0),
960
+ lastModified: optionalDate(p.LastModified)
961
+ }));
962
+ return {
963
+ bucket: optionalString(root.Bucket),
964
+ key: optionalString(root.Key),
965
+ uploadId: optionalString(root.UploadId),
966
+ parts,
967
+ isTruncated: xmlIsTruncated(root.IsTruncated),
968
+ partNumberMarker: Number(root.PartNumberMarker ?? 0),
969
+ nextPartNumberMarker: optionalNumber(root.NextPartNumberMarker),
970
+ maxParts: Number(root.MaxParts ?? parts.length)
971
+ };
1027
972
  }
973
+ /** Parse an S3 `<ListMultipartUploadsResult>` XML document. */
1028
974
  function parseListMultipartUploadsResult(xml) {
1029
- const root = parseXml(xml).ListMultipartUploadsResult ?? {};
1030
- const uploads = asArray(root.Upload).map((u) => ({
1031
- key: String(u.Key ?? ""),
1032
- uploadId: String(u.UploadId ?? ""),
1033
- initiated: optionalDate(u.Initiated)
1034
- }));
1035
- const commonPrefixes = asArray(root.CommonPrefixes).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0);
1036
- return {
1037
- bucket: optionalString(root.Bucket),
1038
- uploads,
1039
- commonPrefixes,
1040
- isTruncated: xmlIsTruncated(root.IsTruncated),
1041
- keyMarker: optionalString(root.KeyMarker),
1042
- uploadIdMarker: optionalString(root.UploadIdMarker),
1043
- nextKeyMarker: optionalString(root.NextKeyMarker),
1044
- nextUploadIdMarker: optionalString(root.NextUploadIdMarker),
1045
- prefix: optionalString(root.Prefix),
1046
- delimiter: optionalString(root.Delimiter),
1047
- maxUploads: optionalNumber(root.MaxUploads)
1048
- };
975
+ const root = parseXml(xml).ListMultipartUploadsResult ?? {};
976
+ const uploads = asArray(root.Upload).map((u) => ({
977
+ key: String(u.Key ?? ""),
978
+ uploadId: String(u.UploadId ?? ""),
979
+ initiated: optionalDate(u.Initiated)
980
+ }));
981
+ const commonPrefixes = asArray(root.CommonPrefixes).map((cp) => optionalString(cp.Prefix)).filter((p) => p !== void 0);
982
+ return {
983
+ bucket: optionalString(root.Bucket),
984
+ uploads,
985
+ commonPrefixes,
986
+ isTruncated: xmlIsTruncated(root.IsTruncated),
987
+ keyMarker: optionalString(root.KeyMarker),
988
+ uploadIdMarker: optionalString(root.UploadIdMarker),
989
+ nextKeyMarker: optionalString(root.NextKeyMarker),
990
+ nextUploadIdMarker: optionalString(root.NextUploadIdMarker),
991
+ prefix: optionalString(root.Prefix),
992
+ delimiter: optionalString(root.Delimiter),
993
+ maxUploads: optionalNumber(root.MaxUploads)
994
+ };
1049
995
  }
1050
-
1051
- // src/disks.ts
996
+ //#endregion
997
+ //#region src/disks.ts
1052
998
  var Disks = class {
1053
- /** @internal */
1054
- _client;
1055
- /** @internal */
1056
- _region;
1057
- /** @internal */
1058
- _s3BaseUrl;
1059
- /** @internal */
1060
- constructor(client, region, s3BaseUrl) {
1061
- this._client = client;
1062
- this._region = region;
1063
- this._s3BaseUrl = s3BaseUrl;
1064
- }
1065
- async list(opts) {
1066
- const data = await unwrap(
1067
- this._client.GET("/api/disks", {
1068
- params: { query: { limit: opts?.limit, cursor: opts?.cursor, name: opts?.name } }
1069
- })
1070
- );
1071
- return data.map(
1072
- (d) => new Disk(d, this._client, this._region, this._s3BaseUrl)
1073
- );
1074
- }
1075
- async get(id) {
1076
- const data = await unwrap(
1077
- this._client.GET("/api/disks/{id}", {
1078
- params: { path: { id } }
1079
- })
1080
- );
1081
- return new Disk(data, this._client, this._region, this._s3BaseUrl);
1082
- }
1083
- /**
1084
- * Create a new disk with an auto-generated mount token.
1085
- *
1086
- * Returns the Disk, the one-time token (save it — it cannot be retrieved
1087
- * again), and the token identifier for later management.
1088
- */
1089
- async create(req) {
1090
- const created = await unwrap(
1091
- this._client.POST("/api/disks", { body: req })
1092
- );
1093
- const resp = created;
1094
- if (!resp.diskId) {
1095
- throw new Error("API returned success but no diskId");
1096
- }
1097
- const authorizedUsers = resp.authorizedUsers ?? [];
1098
- const tokenUser = authorizedUsers.find((u) => u.token);
1099
- const disk = await this.get(resp.diskId);
1100
- return {
1101
- disk,
1102
- token: tokenUser?.token ?? null,
1103
- tokenIdentifier: tokenUser?.identifier ?? null,
1104
- authorizedUsers
1105
- };
1106
- }
999
+ /** @internal */
1000
+ _client;
1001
+ /** @internal */
1002
+ _region;
1003
+ /** @internal */
1004
+ _s3BaseUrl;
1005
+ /** @internal */
1006
+ constructor(client, region, s3BaseUrl) {
1007
+ this._client = client;
1008
+ this._region = region;
1009
+ this._s3BaseUrl = s3BaseUrl;
1010
+ }
1011
+ async list(opts) {
1012
+ return (await unwrap(this._client.GET("/api/disks", { params: { query: {
1013
+ limit: opts?.limit,
1014
+ cursor: opts?.cursor,
1015
+ name: opts?.name
1016
+ } } }))).map((d) => new Disk(d, this._client, this._region, this._s3BaseUrl));
1017
+ }
1018
+ async get(id) {
1019
+ return new Disk(await unwrap(this._client.GET("/api/disks/{id}", { params: { path: { id } } })), this._client, this._region, this._s3BaseUrl);
1020
+ }
1021
+ /**
1022
+ * Create a new disk with an auto-generated mount token.
1023
+ *
1024
+ * Returns the Disk, the one-time token (save it — it cannot be retrieved
1025
+ * again), and the token identifier for later management.
1026
+ */
1027
+ async create(req) {
1028
+ const resp = await unwrap(this._client.POST("/api/disks", { body: req }));
1029
+ if (!resp.diskId) throw new Error("API returned success but no diskId");
1030
+ const authorizedUsers = resp.authorizedUsers ?? [];
1031
+ const tokenUser = authorizedUsers.find((u) => u.token);
1032
+ return {
1033
+ disk: await this.get(resp.diskId),
1034
+ token: tokenUser?.token ?? null,
1035
+ tokenIdentifier: tokenUser?.identifier ?? null,
1036
+ authorizedUsers
1037
+ };
1038
+ }
1107
1039
  };
1108
-
1109
- // src/tokens.ts
1040
+ //#endregion
1041
+ //#region src/tokens.ts
1110
1042
  var Tokens = class {
1111
- /** @internal */
1112
- _client;
1113
- /** @internal */
1114
- constructor(client) {
1115
- this._client = client;
1116
- }
1117
- async list(opts) {
1118
- const data = await unwrap(
1119
- this._client.GET("/api/tokens", {
1120
- params: { query: { limit: opts?.limit, cursor: opts?.cursor } }
1121
- })
1122
- );
1123
- return data.tokens ?? [];
1124
- }
1125
- async create(req) {
1126
- const data = await unwrap(
1127
- this._client.POST("/api/tokens", { body: req })
1128
- );
1129
- return data;
1130
- }
1131
- async delete(id) {
1132
- await unwrapEmpty(
1133
- this._client.DELETE("/api/tokens/{id}", {
1134
- params: { path: { id } }
1135
- })
1136
- );
1137
- }
1043
+ /** @internal */
1044
+ _client;
1045
+ /** @internal */
1046
+ constructor(client) {
1047
+ this._client = client;
1048
+ }
1049
+ async list(opts) {
1050
+ return (await unwrap(this._client.GET("/api/tokens", { params: { query: {
1051
+ limit: opts?.limit,
1052
+ cursor: opts?.cursor
1053
+ } } }))).tokens ?? [];
1054
+ }
1055
+ async create(req) {
1056
+ return await unwrap(this._client.POST("/api/tokens", { body: req }));
1057
+ }
1058
+ async delete(id) {
1059
+ await unwrapEmpty(this._client.DELETE("/api/tokens/{id}", { params: { path: { id } } }));
1060
+ }
1061
+ };
1062
+ //#endregion
1063
+ //#region src/workspace.ts
1064
+ function isExecMountSpec$1(m) {
1065
+ return typeof m === "object" && m !== null && "disk" in m;
1066
+ }
1067
+ /**
1068
+ * A key-routed filesystem spanning several Archil disks. Each disk is mounted
1069
+ * under a name and addressed as the first segment of a key (`<name>/...`);
1070
+ * `getObject`, `putObject`, `deleteObject`, `listObjects`, and `grep` route to
1071
+ * the right disk by that segment (and `listObjects` / `grep` fan out across all
1072
+ * of them when the key/prefix doesn't name one). Implements the same
1073
+ * {@link FileSystem} surface as a single {@link Disk}, so it works anywhere a
1074
+ * disk does. Mounts can be changed at runtime with {@link addDisk} /
1075
+ * {@link removeDisk}.
1076
+ */
1077
+ var Workspace = class {
1078
+ client;
1079
+ mounts = /* @__PURE__ */ new Map();
1080
+ /** @internal Use `archil.workspace({ ... })`. */
1081
+ constructor(client, mounts) {
1082
+ this.client = client;
1083
+ for (const [name, value] of Object.entries(mounts)) this.addDisk(name, value);
1084
+ if (this.mounts.size === 0) throw new Error("workspace() needs at least one disk");
1085
+ }
1086
+ /** Mount (or replace) a disk at `name`; its objects are addressed as
1087
+ * `<name>/...`. Accepts a `Disk` or a mount spec (read-only / subdirectory /
1088
+ * conditional / delegation checkouts); a bare disk-id string is rejected —
1089
+ * fetch the disk first. */
1090
+ addDisk(name, disk) {
1091
+ const rel = name.replace(/^\/+|\/+$/g, "");
1092
+ if (!rel) throw new Error("workspace mount name must be non-empty");
1093
+ if (rel.includes("/")) throw new Error(`workspace mount name '${name}' must not contain '/'`);
1094
+ if (rel === "." || rel === "..") throw new Error(`workspace mount name '${name}' is reserved ('.' and '..' are path navigation, not disk names)`);
1095
+ let d;
1096
+ let readOnly = false;
1097
+ let subdirectory;
1098
+ let conditional = false;
1099
+ let queueMs;
1100
+ let checkoutPaths;
1101
+ if (isExecMountSpec$1(disk)) {
1102
+ d = disk.disk;
1103
+ readOnly = disk.readOnly ?? false;
1104
+ subdirectory = disk.subdirectory;
1105
+ conditional = disk.conditional ?? false;
1106
+ queueMs = disk.queueMs;
1107
+ checkoutPaths = disk.checkoutPaths;
1108
+ } else d = disk;
1109
+ if (typeof d === "string") throw new Error("workspace needs Disk objects, not disk-id strings; fetch with archil.getDisk(id) first");
1110
+ this.mounts.set(rel, {
1111
+ disk: d,
1112
+ readOnly,
1113
+ subdirectory,
1114
+ conditional,
1115
+ queueMs,
1116
+ checkoutPaths
1117
+ });
1118
+ return this;
1119
+ }
1120
+ /** Unmount the disk at `name`. Returns whether a disk was removed. Refuses to
1121
+ * remove the last disk — a workspace must always have at least one (the same
1122
+ * invariant the constructor enforces), else fan-out/exec would have nothing to
1123
+ * route to. */
1124
+ removeDisk(name) {
1125
+ const rel = name.replace(/^\/+|\/+$/g, "");
1126
+ if (this.mounts.has(rel) && this.mounts.size === 1) throw new Error("cannot remove the last disk from a workspace; a workspace must keep at least one");
1127
+ return this.mounts.delete(rel);
1128
+ }
1129
+ /** The names of the currently-mounted disks. */
1130
+ diskNames() {
1131
+ return [...this.mounts.keys()];
1132
+ }
1133
+ unknownDisk(name) {
1134
+ return /* @__PURE__ */ new Error(`No disk named '${name}'. Address objects by disk: ${this.diskNames().map((n) => `${n}/…`).join(", ")}`);
1135
+ }
1136
+ /** Resolve a workspace key (`<name>/...`) to the disk and the disk-relative key. */
1137
+ route(key) {
1138
+ const segs = require_paths.toSegments(key);
1139
+ if (segs.length === 0) throw new Error("that key is the workspace root, not an object; name a disk, e.g. data/file.txt");
1140
+ const entry = this.mounts.get(segs[0]);
1141
+ if (!entry) throw this.unknownDisk(segs[0]);
1142
+ return {
1143
+ entry,
1144
+ diskKey: this.diskKey(entry, segs.slice(1).join("/"))
1145
+ };
1146
+ }
1147
+ /** Mounts touched by a key prefix; an empty prefix fans out to all of them. */
1148
+ covered(prefix) {
1149
+ const segs = require_paths.toSegments(prefix);
1150
+ if (segs.length === 0) return [...this.mounts.entries()].map(([name, entry]) => ({
1151
+ name,
1152
+ entry,
1153
+ rel: this.diskKey(entry, "")
1154
+ }));
1155
+ const entry = this.mounts.get(segs[0]);
1156
+ if (!entry) throw this.unknownDisk(segs[0]);
1157
+ return [{
1158
+ name: segs[0],
1159
+ entry,
1160
+ rel: this.diskKey(entry, segs.slice(1).join("/"))
1161
+ }];
1162
+ }
1163
+ /** Map a workspace-relative key to the disk's key, applying the mount's subdirectory. */
1164
+ diskKey(entry, rel) {
1165
+ const trimmed = rel.replace(/^\/+/, "");
1166
+ const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
1167
+ if (!sub) return trimmed;
1168
+ return trimmed ? `${sub}/${trimmed}` : sub;
1169
+ }
1170
+ /** Map a disk key back to its workspace key (`<name>/...`), stripping the mount subdirectory. */
1171
+ abs(name, entry, diskKey) {
1172
+ const sub = (entry.subdirectory ?? "").replace(/^\/+|\/+$/g, "");
1173
+ let rel = diskKey;
1174
+ if (sub && diskKey.startsWith(sub + "/")) rel = diskKey.slice(sub.length + 1);
1175
+ else if (sub && diskKey === sub) rel = "";
1176
+ rel = rel.replace(/^\/+|\/+$/g, "");
1177
+ return rel ? `${name}/${rel}` : name;
1178
+ }
1179
+ async getObject(key) {
1180
+ const { entry, diskKey } = this.route(key);
1181
+ return entry.disk.getObject(diskKey);
1182
+ }
1183
+ async putObject(key, body, contentType) {
1184
+ const { entry, diskKey } = this.route(key);
1185
+ if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be written.`);
1186
+ return entry.disk.putObject(diskKey, body, contentType);
1187
+ }
1188
+ async deleteObject(key) {
1189
+ const { entry, diskKey } = this.route(key);
1190
+ if (entry.readOnly) throw new Error(`${key} is on a read-only disk and cannot be deleted.`);
1191
+ await entry.disk.deleteObject(diskKey);
1192
+ }
1193
+ async listObjects(prefix, opts = {}) {
1194
+ if (require_paths.toSegments(prefix ?? "").length === 0 && !opts.recursive) return {
1195
+ objects: [],
1196
+ commonPrefixes: this.diskNames().map((n) => `${n}/`).sort(),
1197
+ isTruncated: false,
1198
+ keyCount: 0
1199
+ };
1200
+ const covered = this.covered(prefix ?? "");
1201
+ const listings = await Promise.allSettled(covered.map(({ entry, rel }) => {
1202
+ const p = rel ? rel.endsWith("/") ? rel : `${rel}/` : void 0;
1203
+ return entry.disk.listObjects(p, { recursive: opts.recursive });
1204
+ }));
1205
+ const objects = [];
1206
+ const commonPrefixes = [];
1207
+ let isTruncated = false;
1208
+ let keyCount = 0;
1209
+ covered.forEach(({ name, entry }, i) => {
1210
+ const settled = listings[i];
1211
+ if (settled.status === "rejected") {
1212
+ isTruncated = true;
1213
+ return;
1214
+ }
1215
+ const listing = settled.value;
1216
+ for (const cp of listing.commonPrefixes) commonPrefixes.push(`${this.abs(name, entry, cp.replace(/\/+$/, ""))}/`);
1217
+ for (const obj of listing.objects) objects.push({
1218
+ ...obj,
1219
+ key: this.abs(name, entry, obj.key)
1220
+ });
1221
+ isTruncated = isTruncated || listing.isTruncated;
1222
+ keyCount += listing.keyCount;
1223
+ });
1224
+ objects.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
1225
+ commonPrefixes.sort();
1226
+ return {
1227
+ objects,
1228
+ commonPrefixes,
1229
+ isTruncated,
1230
+ keyCount
1231
+ };
1232
+ }
1233
+ async grep(opts) {
1234
+ const covered = this.covered(opts.directory ?? "");
1235
+ const results = await Promise.allSettled(covered.map(({ entry, rel }) => entry.disk.grep({
1236
+ ...opts,
1237
+ directory: rel
1238
+ })));
1239
+ const matches = [];
1240
+ let filesScanned = 0;
1241
+ let containersDispatched = 0;
1242
+ let computeSecondsUsed = 0;
1243
+ let durationMs = 0;
1244
+ let listingMs = 0;
1245
+ let grepMs = 0;
1246
+ const reasons = /* @__PURE__ */ new Set();
1247
+ covered.forEach(({ name, entry }, i) => {
1248
+ const settled = results[i];
1249
+ if (settled.status === "rejected") {
1250
+ reasons.add("list_failed");
1251
+ return;
1252
+ }
1253
+ const r = settled.value;
1254
+ filesScanned += r.filesScanned;
1255
+ containersDispatched += r.containersDispatched ?? 0;
1256
+ computeSecondsUsed += r.computeSecondsUsed ?? 0;
1257
+ durationMs = Math.max(durationMs, r.durationMs ?? 0);
1258
+ listingMs = Math.max(listingMs, r.listingMs ?? 0);
1259
+ grepMs = Math.max(grepMs, r.grepMs ?? 0);
1260
+ reasons.add(r.stoppedReason);
1261
+ for (const m of r.matches) matches.push({
1262
+ file: this.abs(name, entry, m.file),
1263
+ line: m.line,
1264
+ text: m.text
1265
+ });
1266
+ });
1267
+ const cap = opts.maxResults ?? 1e3;
1268
+ if (matches.length > cap) reasons.add("max_results");
1269
+ const priority = [
1270
+ "list_failed",
1271
+ "incomplete",
1272
+ "deadline",
1273
+ "max_results"
1274
+ ];
1275
+ const stoppedReason = [...reasons].every((x) => x === "completed") ? "completed" : priority.find((x) => reasons.has(x)) ?? "completed";
1276
+ return {
1277
+ matches: matches.slice(0, cap),
1278
+ stoppedReason,
1279
+ filesScanned,
1280
+ containersDispatched,
1281
+ computeSecondsUsed,
1282
+ durationMs,
1283
+ listingMs,
1284
+ grepMs
1285
+ };
1286
+ }
1287
+ exec(command) {
1288
+ const disks = {};
1289
+ for (const [name, entry] of this.mounts) disks[name] = entry.readOnly || entry.subdirectory || entry.conditional || entry.queueMs !== void 0 || entry.checkoutPaths !== void 0 ? {
1290
+ disk: entry.disk,
1291
+ subdirectory: entry.subdirectory,
1292
+ readOnly: entry.readOnly,
1293
+ conditional: entry.conditional,
1294
+ queueMs: entry.queueMs,
1295
+ checkoutPaths: entry.checkoutPaths
1296
+ } : entry.disk;
1297
+ return this.client.exec({
1298
+ disks,
1299
+ command
1300
+ });
1301
+ }
1138
1302
  };
1139
-
1140
- // src/archil.ts
1303
+ //#endregion
1304
+ //#region src/archil.ts
1305
+ /**
1306
+ * Read an environment variable in a way that is safe in browsers, where the
1307
+ * `process` global does not exist. Returns undefined when there is no process
1308
+ * environment, so the SDK can be bundled and run client-side as long as
1309
+ * credentials are passed explicitly to `new Archil({ ... })`.
1310
+ */
1141
1311
  function envVar(name) {
1142
- return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
1312
+ return typeof process !== "undefined" && process.env ? process.env[name] : void 0;
1143
1313
  }
1144
1314
  function isExecMountSpec(m) {
1145
- return typeof m === "object" && m !== null && "disk" in m;
1315
+ return typeof m === "object" && m !== null && "disk" in m;
1146
1316
  }
1147
1317
  function diskIdFromMount(m) {
1148
- return typeof m === "string" ? m : m.id;
1318
+ return typeof m === "string" ? m : m.id;
1149
1319
  }
1150
1320
  var Archil = class {
1151
- disks;
1152
- tokens;
1153
- /** @internal */
1154
- _client;
1155
- constructor(opts = {}) {
1156
- const apiKey = opts.apiKey ?? envVar("ARCHIL_API_KEY");
1157
- const region = opts.region ?? envVar("ARCHIL_REGION");
1158
- if (!apiKey) {
1159
- throw new Error("Missing API key: pass apiKey in options or set ARCHIL_API_KEY environment variable");
1160
- }
1161
- if (!region) {
1162
- throw new Error("Missing region: pass region in options or set ARCHIL_REGION environment variable");
1163
- }
1164
- const controlBaseUrl = opts.baseUrl ?? resolveBaseUrl(region);
1165
- const client = createApiClient({
1166
- apiKey,
1167
- region,
1168
- baseUrl: controlBaseUrl
1169
- });
1170
- const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
1171
- this._client = client;
1172
- this.disks = new Disks(client, region, s3BaseUrl);
1173
- this.tokens = new Tokens(client);
1174
- }
1175
- /**
1176
- * Run a command in a container with multiple disks mounted simultaneously,
1177
- * each at its own relative path under `/mnt/archil`. Blocks until the
1178
- * command completes and returns its stdout, stderr, exit code, and timing.
1179
- */
1180
- async exec(opts) {
1181
- const disks = {};
1182
- for (const [relPath, mount] of Object.entries(opts.disks)) {
1183
- if (isExecMountSpec(mount)) {
1184
- const entry = {
1185
- disk: diskIdFromMount(mount.disk),
1186
- readOnly: mount.readOnly ?? false
1187
- };
1188
- if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
1189
- disks[relPath] = entry;
1190
- } else {
1191
- disks[relPath] = diskIdFromMount(mount);
1192
- }
1193
- }
1194
- return unwrap(
1195
- this._client.POST("/api/exec", {
1196
- body: { disks, command: opts.command }
1197
- })
1198
- );
1199
- }
1321
+ disks;
1322
+ tokens;
1323
+ /** @internal */
1324
+ _client;
1325
+ constructor(opts = {}) {
1326
+ const apiKey = opts.apiKey ?? envVar("ARCHIL_API_KEY");
1327
+ const region = opts.region ?? envVar("ARCHIL_REGION");
1328
+ if (!apiKey) throw new Error("Missing API key: pass apiKey in options or set ARCHIL_API_KEY environment variable");
1329
+ if (!region) throw new Error("Missing region: pass region in options or set ARCHIL_REGION environment variable");
1330
+ const controlBaseUrl = opts.baseUrl ?? resolveBaseUrl(region);
1331
+ const client = createApiClient({
1332
+ apiKey,
1333
+ region,
1334
+ baseUrl: controlBaseUrl
1335
+ });
1336
+ const s3BaseUrl = opts.s3BaseUrl ?? envVar("ARCHIL_S3_BASE_URL") ?? deriveS3BaseUrl(controlBaseUrl);
1337
+ this._client = client;
1338
+ this.disks = new Disks(client, region, s3BaseUrl);
1339
+ this.tokens = new Tokens(client);
1340
+ }
1341
+ /**
1342
+ * Run a command in a container with multiple disks mounted simultaneously,
1343
+ * each at its own relative path under `/mnt/archil`. Blocks until the
1344
+ * command completes and returns its stdout, stderr, exit code, and timing.
1345
+ */
1346
+ async exec(opts) {
1347
+ const disks = {};
1348
+ for (const [relPath, mount] of Object.entries(opts.disks)) if (isExecMountSpec(mount)) {
1349
+ const entry = {
1350
+ disk: diskIdFromMount(mount.disk),
1351
+ readOnly: mount.readOnly ?? false,
1352
+ conditional: mount.conditional ?? false
1353
+ };
1354
+ if (mount.subdirectory !== void 0) entry.subdirectory = mount.subdirectory;
1355
+ if (mount.queueMs !== void 0) entry.queueMs = mount.queueMs;
1356
+ if (mount.checkoutPaths !== void 0) entry.checkoutPaths = mount.checkoutPaths;
1357
+ disks[relPath] = entry;
1358
+ } else disks[relPath] = diskIdFromMount(mount);
1359
+ return unwrap(this._client.POST("/api/exec", { body: {
1360
+ disks,
1361
+ command: opts.command
1362
+ } }));
1363
+ }
1364
+ /**
1365
+ * Build an agent filesystem toolset spanning several disks at once. `mounts`
1366
+ * maps a relative path to a disk (or `ExecMountSpec`), exactly like
1367
+ * {@link exec}; each disk appears under `/mnt/archil/<path>`. Hand the result
1368
+ * to a framework adapter (`createDiskTools(workspace)`) to get tools that route
1369
+ * file operations by path and fan `grep`/`list_files` out across the disks.
1370
+ */
1371
+ workspace(mounts) {
1372
+ return new Workspace(this, mounts);
1373
+ }
1200
1374
  };
1201
-
1202
- // src/index.ts
1203
- var _options;
1204
- var _instance;
1375
+ //#endregion
1376
+ //#region src/index.ts
1377
+ let _options;
1378
+ let _instance;
1205
1379
  function configure(options) {
1206
- _options = options;
1207
- _instance = void 0;
1380
+ _options = options;
1381
+ _instance = void 0;
1208
1382
  }
1209
1383
  function archil() {
1210
- if (!_instance) {
1211
- _instance = new Archil(_options);
1212
- }
1213
- return _instance;
1384
+ if (!_instance) _instance = new Archil(_options);
1385
+ return _instance;
1214
1386
  }
1215
1387
  function createDisk(req) {
1216
- return archil().disks.create(req);
1388
+ return archil().disks.create(req);
1217
1389
  }
1218
1390
  function listDisks(opts) {
1219
- return archil().disks.list(opts);
1391
+ return archil().disks.list(opts);
1220
1392
  }
1221
1393
  function getDisk(id) {
1222
- return archil().disks.get(id);
1394
+ return archil().disks.get(id);
1223
1395
  }
1224
1396
  function listApiKeys(opts) {
1225
- return archil().tokens.list(opts);
1397
+ return archil().tokens.list(opts);
1226
1398
  }
1227
1399
  function createApiKey(req) {
1228
- return archil().tokens.create(req);
1400
+ return archil().tokens.create(req);
1229
1401
  }
1230
1402
  function deleteApiKey(id) {
1231
- return archil().tokens.delete(id);
1403
+ return archil().tokens.delete(id);
1232
1404
  }
1405
+ /**
1406
+ * Run a command in a container with multiple disks mounted simultaneously,
1407
+ * each at its own relative path under `/mnt/archil`. Blocks until the
1408
+ * command completes and returns its stdout, stderr, exit code, and timing.
1409
+ */
1233
1410
  function exec(opts) {
1234
- return archil().exec(opts);
1411
+ return archil().exec(opts);
1235
1412
  }
1236
- // Annotate the CommonJS export names for ESM import in node:
1237
- 0 && (module.exports = {
1238
- Archil,
1239
- ArchilApiError,
1240
- ArchilError,
1241
- ArchilS3Error,
1242
- Disk,
1243
- DiskMultipart,
1244
- Disks,
1245
- Tokens,
1246
- USER_AGENT,
1247
- VERSION,
1248
- configure,
1249
- createApiKey,
1250
- createDisk,
1251
- deleteApiKey,
1252
- effectiveUploadPartSize,
1253
- exec,
1254
- getDisk,
1255
- listApiKeys,
1256
- listDisks
1257
- });
1413
+ /**
1414
+ * Build an agent filesystem toolset spanning several disks, using the
1415
+ * module-level client. See {@link Archil.workspace}.
1416
+ */
1417
+ function workspace(mounts) {
1418
+ return archil().workspace(mounts);
1419
+ }
1420
+ //#endregion
1421
+ exports.Archil = Archil;
1422
+ exports.ArchilApiError = ArchilApiError;
1423
+ exports.ArchilError = ArchilError;
1424
+ exports.ArchilS3Error = ArchilS3Error;
1425
+ exports.Disk = Disk;
1426
+ exports.DiskMultipart = DiskMultipart;
1427
+ exports.Disks = Disks;
1428
+ exports.Tokens = Tokens;
1429
+ exports.USER_AGENT = USER_AGENT;
1430
+ exports.VERSION = VERSION;
1431
+ exports.Workspace = Workspace;
1432
+ exports.configure = configure;
1433
+ exports.createApiKey = createApiKey;
1434
+ exports.createDisk = createDisk;
1435
+ exports.deleteApiKey = deleteApiKey;
1436
+ exports.effectiveUploadPartSize = effectiveUploadPartSize;
1437
+ exports.exec = exec;
1438
+ exports.getDisk = getDisk;
1439
+ exports.listApiKeys = listApiKeys;
1440
+ exports.listDisks = listDisks;
1441
+ exports.workspace = workspace;