@superdurable/connector-amazon-s3 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,71 @@
1
1
  import {
2
+ BucketSummarySchema,
2
3
  ConfigSchema,
3
4
  Connection,
4
5
  ConnectionNameProvider,
5
6
  ConnectorID,
7
+ CopiedObjectSchema,
8
+ CopyObjectBranch,
9
+ CopyObjectBranchCopied,
10
+ CopyObjectBranchDefect,
11
+ CopyObjectBranchProviderRejected,
12
+ CopyObjectBranchUncertain,
13
+ CopyObjectDefinition,
14
+ CopyObjectInputSchema,
15
+ CopyObjectMetadata,
16
+ CreateBucketBranch,
17
+ CreateBucketBranchCreated,
18
+ CreateBucketBranchDefect,
19
+ CreateBucketBranchProviderRejected,
20
+ CreateBucketBranchUncertain,
21
+ CreateBucketDefinition,
22
+ CreateBucketInputSchema,
23
+ CreateBucketMetadata,
24
+ CreateFolderBranch,
25
+ CreateFolderBranchCreated,
26
+ CreateFolderBranchDefect,
27
+ CreateFolderBranchProviderRejected,
28
+ CreateFolderDefinition,
29
+ CreateFolderInputSchema,
30
+ CreateFolderMetadata,
31
+ CreatedBucketSchema,
32
+ CreatedFolderSchema,
33
+ CredentialMaterialError,
34
+ DeleteBucketBranch,
35
+ DeleteBucketBranchDefect,
36
+ DeleteBucketBranchDeleted,
37
+ DeleteBucketBranchProviderRejected,
38
+ DeleteBucketDefinition,
39
+ DeleteBucketInputSchema,
40
+ DeleteBucketMetadata,
41
+ DeleteFolderBranch,
42
+ DeleteFolderBranchDefect,
43
+ DeleteFolderBranchDeleted,
44
+ DeleteFolderBranchInvalidResponse,
45
+ DeleteFolderBranchProviderRejected,
46
+ DeleteFolderDefinition,
47
+ DeleteFolderInputSchema,
48
+ DeleteFolderMetadata,
49
+ DeleteObjectBranch,
50
+ DeleteObjectBranchDefect,
51
+ DeleteObjectBranchDeleted,
52
+ DeleteObjectBranchProviderRejected,
53
+ DeleteObjectDefinition,
54
+ DeleteObjectInputSchema,
55
+ DeleteObjectMetadata,
56
+ DeletedBucketSchema,
57
+ DeletedFolderSchema,
58
+ DeletedObjectSchema,
59
+ GetObjectBytesBranch,
60
+ GetObjectBytesBranchDefect,
61
+ GetObjectBytesBranchInvalidResponse,
62
+ GetObjectBytesBranchNotFound,
63
+ GetObjectBytesBranchProviderRejected,
64
+ GetObjectBytesBranchRead,
65
+ GetObjectBytesBranchTooLarge,
66
+ GetObjectBytesDefinition,
67
+ GetObjectBytesInputSchema,
68
+ GetObjectBytesMetadata,
6
69
  GetObjectTextBranch,
7
70
  GetObjectTextBranchDefect,
8
71
  GetObjectTextBranchInvalidResponse,
@@ -23,6 +86,25 @@ import {
23
86
  HeadObjectDefinition,
24
87
  HeadObjectInputSchema,
25
88
  HeadObjectMetadata,
89
+ ListBucketsBranch,
90
+ ListBucketsBranchDefect,
91
+ ListBucketsBranchInvalidResponse,
92
+ ListBucketsBranchListed,
93
+ ListBucketsBranchProviderRejected,
94
+ ListBucketsDefinition,
95
+ ListBucketsInputSchema,
96
+ ListBucketsMetadata,
97
+ ListBucketsOutputSchema,
98
+ ListFoldersBranch,
99
+ ListFoldersBranchDefect,
100
+ ListFoldersBranchInvalidResponse,
101
+ ListFoldersBranchListed,
102
+ ListFoldersBranchNotFound,
103
+ ListFoldersBranchProviderRejected,
104
+ ListFoldersDefinition,
105
+ ListFoldersInputSchema,
106
+ ListFoldersMetadata,
107
+ ListFoldersOutputSchema,
26
108
  ListObjectsBranch,
27
109
  ListObjectsBranchDefect,
28
110
  ListObjectsBranchFound,
@@ -33,6 +115,7 @@ import {
33
115
  ListObjectsInputSchema,
34
116
  ListObjectsMetadata,
35
117
  ListObjectsOutputSchema,
118
+ ObjectBytesSchema,
36
119
  ObjectMetadataSchema,
37
120
  ObjectSummarySchema,
38
121
  ObjectTextSchema,
@@ -46,19 +129,27 @@ import {
46
129
  PutObjectInputSchema,
47
130
  PutObjectMetadata,
48
131
  StoredObjectSchema,
132
+ decodeCredentials,
133
+ decodeSignedInteger,
134
+ exactIntegerJSONCodec,
135
+ isCredentialMaterialError,
49
136
  newConnection,
50
- newConnectionWithOperations
51
- } from "./chunk-OCSVX3FX.js";
137
+ newConnectionWithOperations,
138
+ parseExactIntegerJSON,
139
+ parseJSONNumberTokens
140
+ } from "./chunk-6LKGFP44.js";
52
141
 
53
142
  // src/client.ts
54
143
  import { createHash as createHash2, createHmac } from "crypto";
55
144
  import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
145
+ import { ReauthorizationRequiredError } from "@superdurable/connectors-sdk";
146
+ import { ConnectionNotSelectedError, CredentialBrokerRejectedError, ObjectNotFoundError } from "@superdurable/connectors-sdk/projectconfig";
56
147
 
57
148
  // src/operations.ts
58
149
  import { createHash } from "crypto";
59
150
  import { XMLParser, XMLValidator } from "fast-xml-parser";
60
151
  import { newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
61
- var parser = new XMLParser({ ignoreAttributes: true, parseTagValue: false, processEntities: true });
152
+ var parser = new XMLParser({ ignoreAttributes: true, parseTagValue: false, processEntities: true, removeNSPrefix: true });
62
153
  var zeroList = { bucket: "", isTruncated: false };
63
154
  var zeroMetadata = { bucket: "", key: "", sizeBytes: 0 };
64
155
  var zeroText = { bucket: "", key: "", sizeBytes: 0 };
@@ -87,7 +178,8 @@ var ListObjectsOperation = class {
87
178
  }
88
179
  const maxKeys = input.maxKeys || this.client.listPageSize;
89
180
  if (!Number.isSafeInteger(maxKeys) || maxKeys < 1 || maxKeys > 1e3) return defectQuery(operation, zeroList, "maxKeys must be from 1 to 1000");
90
- const session = await this.client.startSession(call);
181
+ const session = await this.client["resolveSession"](call);
182
+ if (session === null) return newQueryRetry(credentialRetryFailure(operation));
91
183
  if (!session) return credentialDefectQuery(operation, zeroList);
92
184
  const query = { "list-type": "2", "encoding-type": "url", "max-keys": String(maxKeys) };
93
185
  if (input.prefix) query.prefix = input.prefix;
@@ -136,7 +228,8 @@ var HeadObjectOperation = class {
136
228
  } catch (error) {
137
229
  return defectQuery(operation, zeroMetadata, errorMessage(error));
138
230
  }
139
- const session = await this.client.startSession(call);
231
+ const session = await this.client["resolveSession"](call);
232
+ if (session === null) return newQueryRetry(credentialRetryFailure(operation));
140
233
  if (!session) return credentialDefectQuery(operation, zeroMetadata);
141
234
  const identity = { bucket, key: input.key, sizeBytes: 0 };
142
235
  let response;
@@ -173,7 +266,8 @@ var GetObjectTextOperation = class {
173
266
  } catch (error) {
174
267
  return defectQuery(operation, zeroText, errorMessage(error));
175
268
  }
176
- const session = await this.client.startSession(call);
269
+ const session = await this.client["resolveSession"](call);
270
+ if (session === null) return newQueryRetry(credentialRetryFailure(operation));
177
271
  if (!session) return credentialDefectQuery(operation, zeroText);
178
272
  const identity = { bucket, key: input.key, sizeBytes: 0 };
179
273
  let response;
@@ -243,7 +337,8 @@ var PutObjectOperation = class {
243
337
  } catch (error) {
244
338
  return defectMutation(zeroStored, errorMessage(error));
245
339
  }
246
- const session = await this.client.startSession(call);
340
+ const session = await this.client["resolveSession"](call);
341
+ if (session === null) return newMutationRetry(credentialRetryFailure(operation));
247
342
  if (!session) return newMutationBranch("defect", zeroStored, {}, failure(operation, "AUTHENTICATION", "S3 connection credentials are unavailable"));
248
343
  const requested = { bucket, key: input.key, sizeBytes: content.length, contentType: input.contentType };
249
344
  const headers = { "content-type": input.contentType, "content-md5": createHash("md5").update(content).digest("base64"), "x-amz-meta-dex-idempotency-key": call.id };
@@ -264,6 +359,8 @@ var PutObjectOperation = class {
264
359
  if (input.isCreateOnly && response.status === 412) return this.readExisting(call, session, requested);
265
360
  const classified = classify(operation, "object write", response, session, false, this.client.currentTime());
266
361
  if (classified.retry) return newMutationRetry(classified.failure, classified.retryAfterMs);
362
+ if (!definiteWriteRefusalStatuses.has(response.status))
363
+ return newMutationRetry(failure(operation, "AVAILABILITY", "S3 answered the object write ambiguously"));
267
364
  return newMutationBranch("providerRejected", requested, receipt, classified.failure);
268
365
  }
269
366
  async readExisting(call, session, requested) {
@@ -291,6 +388,7 @@ var PutObjectOperation = class {
291
388
  return newMutationBranch("alreadyExists", stored, receipt, failure("putObject", "CONFLICT", "another object already exists"));
292
389
  }
293
390
  };
391
+ var definiteWriteRefusalStatuses = /* @__PURE__ */ new Set([301, 400, 401, 403, 404, 411, 413, 414, 415, 422, 501]);
294
392
  function failure(operation, kind, message) {
295
393
  return { provider: "amazon-s3", operation, kind, message };
296
394
  }
@@ -300,6 +398,9 @@ function errorMessage(error) {
300
398
  function defectQuery(operation, value, message) {
301
399
  return newQueryBranch("defect", value, {}, failure(operation, "VALIDATION", message));
302
400
  }
401
+ function credentialRetryFailure(operation) {
402
+ return failure(operation, "AVAILABILITY", "S3 connection credentials are temporarily unavailable; nothing was sent");
403
+ }
303
404
  function credentialDefectQuery(operation, value) {
304
405
  return newQueryBranch("defect", value, {}, failure(operation, "AUTHENTICATION", "S3 connection credentials are unavailable"));
305
406
  }
@@ -373,11 +474,15 @@ function decodeMetadata(response, session, bucket, key) {
373
474
  return output;
374
475
  }
375
476
  function decodeListPage(xml, bucket, prefix, delimiter) {
376
- if (XMLValidator.validate(xml) !== true) throw new TypeError("invalid XML");
477
+ if (/<!DOCTYPE/i.test(xml) || XMLValidator.validate(xml) !== true) throw new TypeError("invalid XML");
377
478
  const document = parser.parse(xml);
378
- const page = document.ListBucketResult;
379
- if (!page) throw new TypeError("missing ListBucketResult");
380
- const isTruncated = page.IsTruncated === "true";
479
+ const rawPage = document.ListBucketResult;
480
+ if (rawPage === void 0) throw new TypeError("missing ListBucketResult");
481
+ const page = typeof rawPage === "string" ? {} : rawPage;
482
+ const truncated = page.IsTruncated ?? "";
483
+ if (typeof truncated !== "string" || !["", "0", "1", "f", "F", "false", "False", "FALSE", "t", "T", "true", "True", "TRUE"].includes(truncated))
484
+ throw new TypeError("invalid truncation flag");
485
+ const isTruncated = ["1", "t", "T", "true", "True", "TRUE"].includes(truncated);
381
486
  const nextContinuationToken = typeof page.NextContinuationToken === "string" ? page.NextContinuationToken : "";
382
487
  if (isTruncated && !nextContinuationToken) throw new TypeError("missing continuation token");
383
488
  if (nextContinuationToken && (Buffer.byteLength(nextContinuationToken) > 4096 || !/^[!-~]+$/.test(nextContinuationToken))) throw new TypeError("invalid continuation token");
@@ -423,7 +528,590 @@ function validatePutHeaders(input) {
423
528
  if (metadataBytes > 2048) throw new TypeError("user metadata exceeds 2048 bytes");
424
529
  }
425
530
 
531
+ // src/management.ts
532
+ import { MIMEType } from "util";
533
+ import {
534
+ definitionMaxSends,
535
+ newMutationUncertain,
536
+ newMutationBranch as newMutationBranch2,
537
+ newMutationRetry as newMutationRetry2,
538
+ newQueryBranch as newQueryBranch2,
539
+ newQueryRetry as newQueryRetry2
540
+ } from "@superdurable/connectors-sdk";
541
+ import { CheckpointError, DispatchNotAllowedError, InsufficientTimeError, newFence } from "@superdurable/connectors-sdk/singledispatch";
542
+ import { XMLParser as XMLParser2, XMLValidator as XMLValidator2 } from "fast-xml-parser";
543
+ var xmlParser = new XMLParser2({ ignoreAttributes: true, parseTagValue: false, processEntities: true, removeNSPrefix: true });
544
+ var credentialMessage = "S3 connection credentials are unavailable";
545
+ var transientCredentialMessage = "S3 connection credentials are temporarily unavailable; nothing was sent";
546
+ var S3Query = class {
547
+ /** Bind the provider client. */
548
+ constructor(client) {
549
+ this.client = client;
550
+ }
551
+ client;
552
+ /** Return the generated Query contract. */
553
+ definition() {
554
+ return this.contract;
555
+ }
556
+ };
557
+ var S3Mutation = class {
558
+ /** Bind the provider client. */
559
+ constructor(client) {
560
+ this.client = client;
561
+ }
562
+ client;
563
+ /** Return the generated Mutation contract. */
564
+ definition() {
565
+ return this.contract;
566
+ }
567
+ /** Return the stable invocation key shared by retries. */
568
+ idempotencyKey(callID) {
569
+ return callID;
570
+ }
571
+ };
572
+ var ListBucketsOperation = class extends S3Query {
573
+ contract = ListBucketsDefinition;
574
+ /** Return names, creation dates, and available Regions. */
575
+ async invoke(call, input) {
576
+ const empty = { buckets: [] };
577
+ const count = input.maxBuckets || 100;
578
+ if (!Number.isInteger(count) || count < 1 || count > 1e4 || Buffer.byteLength(input.prefix ?? "") > 63 || Buffer.byteLength(input.continuationToken ?? "") > 1024)
579
+ return newQueryBranch2("defect", empty, {}, failure2(call, "VALIDATION", "bucket listing parameters are invalid"));
580
+ const query = {
581
+ "max-buckets": String(count),
582
+ ...input.prefix ? { prefix: input.prefix } : {},
583
+ ...input.continuationToken ? { "continuation-token": input.continuationToken } : {}
584
+ };
585
+ return read(this.client, call, empty, empty, { method: "GET", bucket: "", query }, "bucket listing", (response, session, receipt) => {
586
+ if (response.isTooLarge) return newQueryBranch2(
587
+ "invalidResponse",
588
+ empty,
589
+ {},
590
+ failure2(call, "RESPONSE_TOO_LARGE", "S3 bucket list exceeds maxResponseBytes")
591
+ );
592
+ try {
593
+ return newQueryBranch2("listed", bucketPage(bodyText(response, session), count), receipt);
594
+ } catch {
595
+ return newQueryBranch2("invalidResponse", empty, {}, failure2(call, "PROTOCOL", "S3 returned an invalid bucket list"));
596
+ }
597
+ });
598
+ }
599
+ };
600
+ var ListFoldersOperation = class extends S3Query {
601
+ contract = ListFoldersDefinition;
602
+ /** Return complete child prefixes with the continuation token. */
603
+ async invoke(call, input) {
604
+ const empty = { bucket: "", isTruncated: false };
605
+ const prefix = input.parentPrefix ?? "";
606
+ const token = input.continuationToken ?? "";
607
+ const count = input.maxKeys || this.client.listPageSize;
608
+ let bucket;
609
+ try {
610
+ bucket = this.client.bucket(input.bucket);
611
+ validateKey(prefix, "parentPrefix", true);
612
+ if (prefix && !prefix.endsWith("/")) throw new TypeError("parentPrefix must end with a slash");
613
+ if (Buffer.byteLength(token) > 4096 || !/^[!-~]*(?![\s\S])/.test(token)) throw new TypeError("continuation token is invalid");
614
+ if (!Number.isInteger(count) || count < 1 || count > 1e3) throw new TypeError("maxKeys must be 1 to 1000");
615
+ } catch (error) {
616
+ return newQueryBranch2("defect", empty, {}, failure2(call, "VALIDATION", inputError(error)));
617
+ }
618
+ const identity = { bucket, isTruncated: false, ...prefix ? { parentPrefix: prefix } : {} };
619
+ const query = { ...folderQuery(prefix, count), delimiter: "/", ...token ? { "continuation-token": token } : {} };
620
+ return read(this.client, call, empty, identity, { method: "GET", bucket, query }, "folder listing", (response, session, receipt) => {
621
+ if (response.isTooLarge) return newQueryBranch2(
622
+ "invalidResponse",
623
+ identity,
624
+ receipt,
625
+ failure2(call, "RESPONSE_TOO_LARGE", "S3 folder list exceeds maxResponseBytes")
626
+ );
627
+ let page;
628
+ try {
629
+ page = decodeListPage(bodyText(response, session), bucket, prefix, "/");
630
+ } catch {
631
+ return newQueryBranch2("invalidResponse", identity, receipt, failure2(call, "PROTOCOL", "S3 returned an invalid folder list"));
632
+ }
633
+ const folders = page.commonPrefixes ?? [];
634
+ const value = {
635
+ ...identity,
636
+ isTruncated: page.isTruncated,
637
+ ...folders.length ? { folders } : {},
638
+ ...page.nextContinuationToken ? { nextContinuationToken: page.nextContinuationToken } : {}
639
+ };
640
+ if (folders.some((folder) => !folder.startsWith(prefix) || !folder.endsWith("/")))
641
+ return newQueryBranch2("invalidResponse", value, receipt, failure2(call, "PROTOCOL", "S3 returned a folder outside the parent prefix"));
642
+ if (!folders.length && !page.isTruncated)
643
+ return newQueryBranch2("notFound", value, receipt, failure2(call, "NOT_FOUND", "no child folder matched the parent prefix"));
644
+ return newQueryBranch2("listed", value, receipt);
645
+ });
646
+ }
647
+ };
648
+ var GetObjectBytesOperation = class extends S3Query {
649
+ contract = GetObjectBytesDefinition;
650
+ /** Return bounded bytes and selected metadata. */
651
+ async invoke(call, input) {
652
+ const empty = { bucket: "", key: "", sizeBytes: 0 };
653
+ let bucket;
654
+ try {
655
+ bucket = this.client.bucket(input.bucket);
656
+ validateKey(input.key);
657
+ } catch (error) {
658
+ return newQueryBranch2("defect", empty, {}, failure2(call, "VALIDATION", inputError(error)));
659
+ }
660
+ const identity = { bucket, key: input.key, sizeBytes: 0 };
661
+ const maxBytes = this.client.maxResponseBytes;
662
+ return read(
663
+ this.client,
664
+ call,
665
+ empty,
666
+ identity,
667
+ { method: "GET", bucket, key: input.key, maxBytes },
668
+ "object bytes read",
669
+ (response, session, receipt) => {
670
+ const value = objectHeaders(response, session, identity);
671
+ const length = contentLength(header(response, "content-length"));
672
+ const oversized = length !== void 0 && length > BigInt(maxBytes);
673
+ if (response.isTooLarge || oversized || response.body.length > maxBytes) {
674
+ if (oversized) value.sizeBytes = exactLength(length);
675
+ return newQueryBranch2("tooLarge", value, receipt, failure2(call, "RESPONSE_TOO_LARGE", "object exceeds maxResponseBytes"));
676
+ }
677
+ if (length !== void 0 && length !== BigInt(response.body.length))
678
+ return newQueryBranch2("invalidResponse", value, receipt, failure2(call, "PROTOCOL", "S3 returned an incomplete object"));
679
+ const body = Buffer.from(response.body);
680
+ if ([session.secretAccessKey, session.sessionToken].some((secret) => secret && body.includes(secret)))
681
+ return newQueryBranch2("invalidResponse", value, receipt, failure2(call, "PROTOCOL", "object contains connection credentials"));
682
+ return newQueryBranch2("read", { ...value, sizeBytes: body.length, ...body.length ? { bytes: body.toString("base64") } : {} }, receipt);
683
+ }
684
+ );
685
+ }
686
+ };
687
+ var DeleteBucketOperation = class extends S3Mutation {
688
+ contract = DeleteBucketDefinition;
689
+ /** Treat an explicit NoSuchBucket response as an absent bucket. */
690
+ async invoke(call, input) {
691
+ const empty = { bucket: "" };
692
+ let bucket;
693
+ try {
694
+ bucket = this.client.bucket(input.bucket);
695
+ } catch (error) {
696
+ return defect(call, empty, inputError(error));
697
+ }
698
+ return write(this.client, call, empty, { bucket }, { method: "DELETE", bucket }, "bucket deletion", "deleted", true);
699
+ }
700
+ };
701
+ var CreateFolderOperation = class extends S3Mutation {
702
+ contract = CreateFolderDefinition;
703
+ /** Store an empty marker under the slash-terminated prefix. */
704
+ async invoke(call, input) {
705
+ const empty = { bucket: "", prefix: "" };
706
+ let bucket;
707
+ let prefix;
708
+ try {
709
+ [bucket, prefix] = folderLocation(this.client, input.bucket, input.prefix);
710
+ } catch (error) {
711
+ return defect(call, empty, inputError(error));
712
+ }
713
+ const request = {
714
+ method: "PUT",
715
+ bucket,
716
+ key: prefix,
717
+ headers: { "content-type": "application/x-directory" },
718
+ body: new Uint8Array()
719
+ };
720
+ return write(this.client, call, empty, { bucket, prefix }, request, "folder marker write", "created");
721
+ }
722
+ };
723
+ var DeleteObjectOperation = class extends S3Mutation {
724
+ contract = DeleteObjectDefinition;
725
+ /** Return the bucket and key acknowledged by S3. */
726
+ async invoke(call, input) {
727
+ const empty = { bucket: "", key: "" };
728
+ let bucket;
729
+ try {
730
+ bucket = this.client.bucket(input.bucket);
731
+ validateKey(input.key);
732
+ } catch (error) {
733
+ return defect(call, empty, inputError(error));
734
+ }
735
+ return write(
736
+ this.client,
737
+ call,
738
+ empty,
739
+ { bucket, key: input.key },
740
+ { method: "DELETE", bucket, key: input.key },
741
+ "object deletion",
742
+ "deleted"
743
+ );
744
+ }
745
+ };
746
+ var DeleteFolderOperation = class extends S3Mutation {
747
+ contract = DeleteFolderDefinition;
748
+ /** Re-list after each batch so retries converge on current provider state. */
749
+ async invoke(call, input) {
750
+ const empty = { bucket: "", prefix: "" };
751
+ let bucket;
752
+ let prefix;
753
+ try {
754
+ [bucket, prefix] = folderLocation(this.client, input.bucket, input.prefix);
755
+ } catch (error) {
756
+ return defect(call, empty, inputError(error));
757
+ }
758
+ const session = await this.client.resolveSession(call);
759
+ if (session === null) return newMutationRetry2(failure2(call, "AVAILABILITY", transientCredentialMessage));
760
+ if (!session) return newMutationBranch2("defect", empty, {}, failure2(call, "AUTHENTICATION", credentialMessage));
761
+ const signal = AbortSignal.any([call.context.cancellationSignal, AbortSignal.timeout(12e3)]);
762
+ return this.deletePages(call, session, signal, bucket, prefix);
763
+ }
764
+ async deletePages(call, session, signal, bucket, prefix) {
765
+ const value = { bucket, prefix };
766
+ let hasDeleted = false;
767
+ while (!signal.aborted) {
768
+ let response;
769
+ try {
770
+ response = await this.client.exchange(call, session, { method: "GET", bucket, query: folderQuery(prefix, 100) }, signal);
771
+ } catch {
772
+ return newMutationRetry2(transportFailure(call, "folder listing"));
773
+ }
774
+ const receipt = this.client.receipt(call, response, bucket, prefix);
775
+ if (!isSuccess(response)) return writeFailure(this.client, call, response, session, value, receipt, "folder listing", false);
776
+ let page;
777
+ try {
778
+ if (response.isTooLarge) throw new TypeError("S3 folder listing exceeds configured size");
779
+ page = decodeListPage(bodyText(response, session), bucket, prefix, "/");
780
+ if (!page.objects?.length && page.isTruncated) throw new TypeError("S3 folder listing is incomplete");
781
+ for (const object of page.objects ?? []) {
782
+ if (!object.key.startsWith(prefix)) throw new TypeError("S3 returned an object outside the folder prefix");
783
+ validateKey(object.key);
784
+ }
785
+ } catch {
786
+ const error = failure2(call, "PROTOCOL", "S3 returned an invalid folder listing");
787
+ return !hasDeleted && (call.context.attempt ?? 1) === 1 ? newMutationBranch2("invalidResponse", value, receipt, error) : newMutationRetry2(error);
788
+ }
789
+ if (!page.objects?.length) return newMutationBranch2("deleted", value, receipt);
790
+ for (const object of page.objects) {
791
+ let deleted;
792
+ try {
793
+ deleted = await this.client.exchange(call, session, { method: "DELETE", bucket, key: object.key }, signal);
794
+ } catch {
795
+ return newMutationRetry2(transportFailure(call, "folder object deletion"));
796
+ }
797
+ if (!isSuccess(deleted)) return writeFailure(
798
+ this.client,
799
+ call,
800
+ deleted,
801
+ session,
802
+ value,
803
+ this.client.receipt(call, deleted, bucket, object.key),
804
+ "folder object deletion",
805
+ true
806
+ );
807
+ hasDeleted = true;
808
+ }
809
+ }
810
+ return newMutationRetry2(transportFailure(call, "folder deletion"));
811
+ }
812
+ };
813
+ async function read(client, call, empty, identity, request, subject, decode) {
814
+ const session = await client.resolveSession(call);
815
+ if (session === null) return newQueryRetry2(failure2(call, "AVAILABILITY", transientCredentialMessage));
816
+ if (!session) return newQueryBranch2("defect", empty, {}, failure2(call, "AUTHENTICATION", credentialMessage));
817
+ let response;
818
+ try {
819
+ response = await client.exchange(call, session, request);
820
+ } catch {
821
+ return newQueryRetry2(transportFailure(call, subject));
822
+ }
823
+ const receipt = client.receipt(call, response, request.bucket, request.key);
824
+ if (isSuccess(response)) return decode(response, session, receipt);
825
+ const result = classify(call.operation.operationId, subject, response, session, request.key !== void 0, client.currentTime());
826
+ if (result.retry) return newQueryRetry2(result.failure, result.retryAfterMs);
827
+ return newQueryBranch2(result.notFound ? "notFound" : "providerRejected", identity, receipt, result.failure);
828
+ }
829
+ async function write(client, call, empty, value, request, subject, branch, absentBucket = false) {
830
+ const session = await client.resolveSession(call);
831
+ if (session === null) return newMutationRetry2(failure2(call, "AVAILABILITY", transientCredentialMessage));
832
+ if (!session) return newMutationBranch2("defect", empty, {}, failure2(call, "AUTHENTICATION", credentialMessage));
833
+ let response;
834
+ try {
835
+ response = await client.exchange(call, session, request);
836
+ } catch {
837
+ return newMutationRetry2(transportFailure(call, subject));
838
+ }
839
+ const receipt = client.receipt(call, response, request.bucket, request.key);
840
+ if (isSuccess(response) || absentBucket && response.status === 404 && errorCode(response.body, session) === "NoSuchBucket")
841
+ return newMutationBranch2(branch, value, receipt);
842
+ return writeFailure(client, call, response, session, value, receipt, subject, request.key !== void 0);
843
+ }
844
+ function writeFailure(client, call, response, session, value, receipt, subject, isObject) {
845
+ const result = classify(call.operation.operationId, subject, response, session, isObject, client.currentTime());
846
+ if (result.retry || (call.context.attempt ?? 1) > 1 || !definiteRefusal(response, session))
847
+ return newMutationRetry2(result.failure, result.retryAfterMs);
848
+ return newMutationBranch2("providerRejected", value, receipt, result.failure);
849
+ }
850
+ function definiteRefusal(response, session) {
851
+ const code = errorCode(response.body, session);
852
+ if ([400, 401, 403, 404, 411, 413, 414, 415, 422].includes(response.status)) return Boolean(code);
853
+ return code === (/* @__PURE__ */ new Map([[301, "PermanentRedirect"], [409, "BucketNotEmpty"], [501, "NotImplemented"]])).get(response.status);
854
+ }
855
+ function folderLocation(client, bucket, value) {
856
+ if (!value) throw new TypeError("folder prefix is required");
857
+ const prefix = value.endsWith("/") ? value : value + "/";
858
+ validateKey(prefix);
859
+ return [client.bucket(bucket), prefix];
860
+ }
861
+ function folderQuery(prefix, maxKeys) {
862
+ return { "list-type": "2", "encoding-type": "url", "max-keys": String(maxKeys), ...prefix ? { prefix } : {} };
863
+ }
864
+ function bodyText(response, session) {
865
+ const xml = new TextDecoder("utf-8", { fatal: true }).decode(response.body);
866
+ if (containsCredential(xml, session, true) || /<!DOCTYPE/i.test(xml))
867
+ throw new TypeError("S3 response contains unsupported XML or credentials");
868
+ return xml;
869
+ }
870
+ function bucketPage(xml, maximum) {
871
+ if (XMLValidator2.validate(xml) !== true) throw new TypeError("invalid bucket XML");
872
+ const parsed = xmlParser.parse(xml);
873
+ const result = parsed.ListAllMyBucketsResult;
874
+ if (result === "") return { buckets: [] };
875
+ if (result === void 0 || typeof result !== "object") throw new TypeError("missing ListAllMyBucketsResult");
876
+ const entries = result.Buckets?.Bucket === void 0 ? [] : Array.isArray(result.Buckets.Bucket) ? result.Buckets.Bucket : [result.Buckets.Bucket];
877
+ const token = result.ContinuationToken ?? "";
878
+ if (entries.length > maximum || typeof token !== "string" || Buffer.byteLength(token) > 1024)
879
+ throw new TypeError("invalid bucket page");
880
+ const buckets = entries.map((entry) => {
881
+ if (!entry || typeof entry !== "object") throw new TypeError("invalid bucket entry");
882
+ const { Name, CreationDate, BucketRegion } = entry;
883
+ if (typeof Name !== "string" || typeof CreationDate !== "string") throw new TypeError("invalid bucket metadata");
884
+ validateBucket(Name);
885
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(CreationDate) || !parseDate(CreationDate) || CreationDate === "0001-01-01T00:00:00Z") throw new TypeError("invalid bucket creation time");
886
+ if (BucketRegion !== void 0 && (typeof BucketRegion !== "string" || BucketRegion && !/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(BucketRegion))) throw new TypeError("invalid bucket Region");
887
+ const creationDate = CreationDate.replace(/(\.\d*?[1-9])0+(?=Z|[+-])|\.0+(?=Z|[+-])/g, "$1").replace(/\+00:00$/, "Z");
888
+ return { name: Name, creationDate, ...BucketRegion ? { region: BucketRegion } : {} };
889
+ });
890
+ return { buckets, ...token ? { nextContinuationToken: token } : {} };
891
+ }
892
+ function contentLength(value) {
893
+ if (!/^\d{1,19}$/.test(value)) return void 0;
894
+ const size = BigInt(value);
895
+ return size <= (1n << 63n) - 1n ? size : void 0;
896
+ }
897
+ function exactLength(size) {
898
+ if (size <= BigInt(Number.MAX_SAFE_INTEGER)) return Number(size);
899
+ const nativeJSON = JSON;
900
+ return decodeSignedInteger(nativeJSON.rawJSON(String(size)));
901
+ }
902
+ function objectHeaders(response, session, identity) {
903
+ const contentType = safeHeader(response, "content-type", session);
904
+ const eTag = safeHeader(response, "etag", session);
905
+ const versionId = safeHeader(response, "x-amz-version-id", session);
906
+ const lastModified = parseDate(header(response, "last-modified"));
907
+ return {
908
+ ...identity,
909
+ ...contentType ? { contentType } : {},
910
+ ...eTag ? { eTag } : {},
911
+ ...versionId ? { versionId } : {},
912
+ ...lastModified ? { lastModified } : {}
913
+ };
914
+ }
915
+ function isSuccess(response) {
916
+ return response.status >= 200 && response.status < 300;
917
+ }
918
+ function inputError(error) {
919
+ return error instanceof Error ? error.message : "S3 input is invalid";
920
+ }
921
+ function failure2(call, kind, message) {
922
+ return { provider: "amazon-s3", operation: call.operation.operationId, kind, message };
923
+ }
924
+ function transportFailure(call, subject) {
925
+ return failure2(call, "TRANSPORT", `S3 ${subject} request failed`);
926
+ }
927
+ function defect(call, value, message) {
928
+ return newMutationBranch2("defect", value, {}, failure2(call, "VALIDATION", message));
929
+ }
930
+ var CreateBucketOperation = class extends S3Mutation {
931
+ contract = CreateBucketDefinition;
932
+ /** Create the bucket while protecting existing us-east-1 ACLs. */
933
+ async invoke(call, input) {
934
+ try {
935
+ validateBucket(input.bucket);
936
+ } catch (error) {
937
+ return defect(call, { bucket: "", region: "" }, inputError(error));
938
+ }
939
+ const region = this.client.region;
940
+ const value = { bucket: input.bucket, region };
941
+ const request = { method: "PUT", bucket: input.bucket };
942
+ if (region !== "us-east-1" && region !== "auto") {
943
+ request.headers = { "content-type": "application/xml" };
944
+ request.body = Buffer.from(`<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>${region}</LocationConstraint></CreateBucketConfiguration>`);
945
+ }
946
+ const refusesExisting = async () => region === "us-east-1" && (call.context.attempt ?? 1) === 1 && (await probe(this.client, call, input.bucket))?.response.status === 200;
947
+ return limitedWrite(
948
+ this.client,
949
+ call,
950
+ this.contract,
951
+ request,
952
+ "bucket creation",
953
+ "created",
954
+ value,
955
+ () => value,
956
+ { refusesExisting }
957
+ );
958
+ }
959
+ };
960
+ var CopyObjectOperation = class extends S3Mutation {
961
+ contract = CopyObjectDefinition;
962
+ /** Return the copy acknowledged by S3 or confirmed by its destination marker. */
963
+ async invoke(call, input) {
964
+ const empty = { sourceBucket: "", sourceKey: "", destinationBucket: "", destinationKey: "" };
965
+ const marker = call.idempotencyKey ?? "";
966
+ let sourceBucket;
967
+ let destinationBucket;
968
+ try {
969
+ sourceBucket = this.client.bucket(input.sourceBucket);
970
+ destinationBucket = this.client.bucket(input.destinationBucket);
971
+ validateKey(input.sourceKey);
972
+ validateKey(input.destinationKey);
973
+ validateCopyHeaders(input, marker);
974
+ } catch (error) {
975
+ return defect(call, empty, inputError(error));
976
+ }
977
+ const value = {
978
+ sourceBucket,
979
+ sourceKey: input.sourceKey,
980
+ destinationBucket,
981
+ destinationKey: input.destinationKey
982
+ };
983
+ const headers = {
984
+ "content-type": input.contentType,
985
+ "x-amz-copy-source": escapeS3Path(`/${sourceBucket}/${input.sourceKey}`),
986
+ "x-amz-metadata-directive": "REPLACE",
987
+ "x-amz-meta-dex-idempotency-key": marker,
988
+ ...input.sourceETag ? { "x-amz-copy-source-if-match": input.sourceETag } : {},
989
+ ...Object.fromEntries(Object.entries(input.metadata ?? {}).map(([name, text]) => ["x-amz-meta-" + name, text]))
990
+ };
991
+ const request = { method: "PUT", bucket: destinationBucket, key: input.destinationKey, headers, maxBytes: 65536 };
992
+ const readBack = async () => {
993
+ const result = await probe(this.client, call, destinationBucket, input.destinationKey);
994
+ if (!result || !isSuccess(result.response)) return void 0;
995
+ const metadata = decodeMetadata(result.response, result.session, destinationBucket, input.destinationKey);
996
+ if (metadata?.metadata?.["dex-idempotency-key"] !== marker) return void 0;
997
+ return {
998
+ ...value,
999
+ isFromEarlierAttempt: true,
1000
+ ...metadata.eTag ? { eTag: metadata.eTag } : {},
1001
+ ...metadata.versionId ? { versionId: metadata.versionId } : {}
1002
+ };
1003
+ };
1004
+ const decode = (response, session) => {
1005
+ if (response.isTooLarge || response.body.length > 65536) throw new TypeError("invalid copy response");
1006
+ const xml = bodyText(response, session);
1007
+ if (XMLValidator2.validate(xml) !== true) throw new TypeError("invalid copy response");
1008
+ const parsed = xmlParser.parse(xml);
1009
+ const eTag = parsed.CopyObjectResult?.ETag;
1010
+ if (typeof eTag !== "string" || !eTag || Buffer.byteLength(eTag) > 128) throw new TypeError("invalid copy ETag");
1011
+ const versionId = safeHeader(response, "x-amz-version-id", session);
1012
+ return { ...value, eTag, ...versionId ? { versionId } : {} };
1013
+ };
1014
+ return limitedWrite(this.client, call, this.contract, request, "object copy", "copied", value, decode, { readBack });
1015
+ }
1016
+ };
1017
+ async function limitedWrite(client, call, contract, request, subject, branch, value, decode, options) {
1018
+ const maxSends = call.maxSendsOverride ?? definitionMaxSends(contract);
1019
+ let fence;
1020
+ try {
1021
+ fence = newFence(call, contract.stepDefaults.executeMethodTimeoutMs, { maxSends });
1022
+ } catch {
1023
+ return newMutationBranch2("defect", value, {}, failure2(call, "LOCAL_DEFECT", `S3 ${subject} fence could not be initialized`));
1024
+ }
1025
+ const decision = await fence.decide();
1026
+ if (decision.kind === "failClosed") return newMutationRetry2(failure2(call, "AVAILABILITY", `S3 ${subject} checkpoint is unavailable`));
1027
+ if (options.readBack && (decision.kind === "readBackRequired" || decision.kind === "readBackThenResendAllowed")) {
1028
+ const confirmed = await options.readBack();
1029
+ const emptyResponse = { status: 200, headers: {}, body: new Uint8Array(), isTooLarge: false };
1030
+ if (confirmed !== void 0)
1031
+ return newMutationBranch2(branch, confirmed, client.receipt(call, emptyResponse, request.bucket, request.key));
1032
+ }
1033
+ if (decision.kind === "readBackRequired")
1034
+ return newMutationUncertain(value, failure2(call, "TRANSPORT", `S3 ${subject} could not be confirmed after the send cap`));
1035
+ if (options.refusesExisting && await options.refusesExisting())
1036
+ return newMutationBranch2(
1037
+ "providerRejected",
1038
+ value,
1039
+ {},
1040
+ failure2(call, "CONFLICT", "S3 bucket already exists; recreating it in us-east-1 can reset its ACL")
1041
+ );
1042
+ const session = await client.resolveSession(call);
1043
+ if (session === null) return newMutationRetry2(failure2(call, "AVAILABILITY", transientCredentialMessage));
1044
+ const priorSends = decision.priorSendUpperBound ?? 0;
1045
+ if (!session) {
1046
+ try {
1047
+ await fence.recordNotSent();
1048
+ } catch {
1049
+ return newMutationRetry2(failure2(call, "AVAILABILITY", "S3 unsent checkpoint could not be recorded"));
1050
+ }
1051
+ const error = failure2(call, "AUTHENTICATION", credentialMessage);
1052
+ return priorSends ? newMutationRetry2(error) : newMutationBranch2("defect", value, {}, error);
1053
+ }
1054
+ const unknown = (error) => priorSends + 1 >= maxSends ? newMutationUncertain(value, error) : newMutationRetry2(error);
1055
+ let response;
1056
+ try {
1057
+ response = await fence.dispatch((signal) => client.exchange(call, session, request, signal));
1058
+ } catch (error) {
1059
+ if (error instanceof CheckpointError || error instanceof DispatchNotAllowedError || error instanceof InsufficientTimeError)
1060
+ return newMutationRetry2(failure2(call, "AVAILABILITY", `S3 ${subject} dispatch checkpoint is unavailable`));
1061
+ return unknown(transportFailure(call, subject));
1062
+ }
1063
+ const receipt = client.receipt(call, response, request.bucket, request.key);
1064
+ if (isSuccess(response)) {
1065
+ try {
1066
+ return newMutationBranch2(branch, decode(response, session), receipt);
1067
+ } catch {
1068
+ return unknown(failure2(call, "PROTOCOL", `S3 ${subject} response could not be verified`));
1069
+ }
1070
+ }
1071
+ const result = classify(call.operation.operationId, subject, response, session, false, client.currentTime());
1072
+ const retry = result.retry && (response.status === 429 || response.status === 503);
1073
+ const refused = !result.retry && !priorSends && definiteRefusal(response, session);
1074
+ if (!retry && !refused) return unknown(result.failure);
1075
+ try {
1076
+ await fence.recordCanResend();
1077
+ } catch {
1078
+ return newMutationRetry2(failure2(call, "AVAILABILITY", "S3 resend checkpoint could not be recorded"));
1079
+ }
1080
+ return retry ? newMutationRetry2(result.failure, result.retryAfterMs) : newMutationBranch2("providerRejected", value, receipt, result.failure);
1081
+ }
1082
+ async function probe(client, call, bucket, key) {
1083
+ const session = await client.resolveSession(call);
1084
+ if (!session) return void 0;
1085
+ try {
1086
+ const response = await client.exchange(call, session, { method: "HEAD", bucket, ...key !== void 0 ? { key } : {} });
1087
+ return { session, response };
1088
+ } catch {
1089
+ return void 0;
1090
+ }
1091
+ }
1092
+ function validateCopyHeaders(input, marker) {
1093
+ if (!input.contentType || Buffer.byteLength(input.contentType) > 256 || !printable(input.contentType))
1094
+ throw new TypeError("contentType is invalid");
1095
+ new MIMEType(input.contentType);
1096
+ const etag = input.sourceETag;
1097
+ if (etag && (!printable(etag) || Buffer.byteLength(etag) > 128 || !etag.startsWith('"') || !etag.endsWith('"')))
1098
+ throw new TypeError("sourceETag must be a quoted S3 ETag");
1099
+ if (!/^[!-~]{1,128}(?![\s\S])/.test(marker)) throw new TypeError("idempotency key is missing or not header-safe");
1100
+ let bytes = "x-amz-meta-dex-idempotency-key".length + 128;
1101
+ for (const [name, value] of Object.entries(input.metadata ?? {})) {
1102
+ if (!/^[a-z0-9][a-z0-9._-]{0,127}(?![\s\S])/.test(name) || name === "dex-idempotency-key" || !value || !printable(value) || value.trim() !== value) throw new TypeError("metadata is invalid");
1103
+ bytes += "x-amz-meta-".length + name.length + value.length;
1104
+ }
1105
+ if (bytes > 2048) throw new TypeError("metadata exceeds S3 limit");
1106
+ }
1107
+ function printable(value) {
1108
+ return /^[ -~]*(?![\s\S])/.test(value);
1109
+ }
1110
+
426
1111
  // src/client.ts
1112
+ function isTerminalCredentialError(error) {
1113
+ return isCredentialMaterialError(error) || error instanceof ReauthorizationRequiredError || error instanceof ObjectNotFoundError || error instanceof ConnectionNotSelectedError || error instanceof CredentialBrokerRejectedError;
1114
+ }
427
1115
  var emptyHash = createHash2("sha256").update("").digest("hex");
428
1116
  var encoder = new TextEncoder();
429
1117
  var S3Client = class {
@@ -480,10 +1168,55 @@ var S3Client = class {
480
1168
  putObject() {
481
1169
  return new PutObjectOperation(this);
482
1170
  }
1171
+ /** Bind the S3 list buckets operation. */
1172
+ listBuckets() {
1173
+ return new ListBucketsOperation(this);
1174
+ }
1175
+ /** Bind the S3 delete bucket operation. */
1176
+ deleteBucket() {
1177
+ return new DeleteBucketOperation(this);
1178
+ }
1179
+ /** Bind the S3 create folder operation. */
1180
+ createFolder() {
1181
+ return new CreateFolderOperation(this);
1182
+ }
1183
+ /** Bind the S3 delete folder operation. */
1184
+ deleteFolder() {
1185
+ return new DeleteFolderOperation(this);
1186
+ }
1187
+ /** Bind the S3 list folders operation. */
1188
+ listFolders() {
1189
+ return new ListFoldersOperation(this);
1190
+ }
1191
+ /** Bind the S3 get object bytes operation. */
1192
+ getObjectBytes() {
1193
+ return new GetObjectBytesOperation(this);
1194
+ }
1195
+ /** Bind the S3 delete object operation. */
1196
+ deleteObject() {
1197
+ return new DeleteObjectOperation(this);
1198
+ }
1199
+ /** Bind bounded bucket creation. */
1200
+ createBucket() {
1201
+ return new CreateBucketOperation(this);
1202
+ }
1203
+ /** Bind bounded object copying. */
1204
+ copyObject() {
1205
+ return new CopyObjectOperation(this);
1206
+ }
483
1207
  /** Resolve current credentials once per Invoke without exposing secret-bearing errors. */
484
1208
  async startSession(call) {
1209
+ return await this.resolveSession(call) ?? void 0;
1210
+ }
1211
+ /** Return null for a transient credential failure and undefined for a terminal or invalid one. */
1212
+ async resolveSession(call) {
1213
+ let credentials;
1214
+ try {
1215
+ credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
1216
+ } catch (error) {
1217
+ return isTerminalCredentialError(error) ? void 0 : null;
1218
+ }
485
1219
  try {
486
- const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
487
1220
  const accessKeyId = credentials.accessKeyId.reveal();
488
1221
  const secretAccessKey = credentials.secretAccessKey.reveal();
489
1222
  const sessionToken = credentials.sessionToken?.reveal() ?? "";
@@ -504,14 +1237,14 @@ var S3Client = class {
504
1237
  return bucket;
505
1238
  }
506
1239
  /** Send a SigV4 request once; Dex owns operation retries. */
507
- async exchange(call, session, request) {
1240
+ async exchange(call, session, request, signal = call.context.cancellationSignal) {
508
1241
  const target = this.requestURL(request);
509
1242
  const now = this.now();
510
1243
  const amzDate = now.toISOString().replace(/[-:]|\.\d{3}/g, "");
511
1244
  const body = request.body;
512
1245
  const payloadHash = body ? createHash2("sha256").update(body).digest("hex") : emptyHash;
513
1246
  const headers = { ...request.headers, "x-amz-content-sha256": payloadHash, "x-amz-date": amzDate };
514
- if (body) headers["content-length"] = String(body.length);
1247
+ if (body?.length) headers["content-length"] = String(body.length);
515
1248
  if (session.sessionToken) headers["x-amz-security-token"] = session.sessionToken;
516
1249
  const signed = { host: target.host.toLowerCase() };
517
1250
  for (const [name, value] of Object.entries(headers)) signed[name.toLowerCase()] = value.trim().replace(/\s+/g, " ");
@@ -531,7 +1264,7 @@ ${createHash2("sha256").update(canonicalRequest).digest("hex")}`;
531
1264
  const remaining = call.context.deadline ? call.context.deadline.getTime() - Date.now() : 12e3;
532
1265
  const timeoutMs = Math.max(1, Math.min(12e3, remaining));
533
1266
  try {
534
- const response = await this.send({ url: target.toString(), method: request.method, headers, ...body ? { body } : {}, maxResponseBytes: request.maxBytes ?? this.maxResponseBytes, addressPolicy: this.isAmazonEndpoint ? "publicHTTPS" : "privateNetworkHTTP", timeoutMs, signal: call.context.cancellationSignal });
1267
+ const response = await this.send({ url: target.toString(), method: request.method, headers, ...body ? { body } : {}, maxResponseBytes: request.maxBytes ?? this.maxResponseBytes, addressPolicy: this.isAmazonEndpoint ? "publicHTTPS" : "privateNetworkHTTP", timeoutMs, signal });
535
1268
  return { ...response, isTooLarge: false };
536
1269
  } catch (error) {
537
1270
  if (error instanceof BodyTooLargeError && error.status !== void 0) return { status: error.status, headers: error.headers ?? {}, body: new Uint8Array(), isTooLarge: true };
@@ -551,13 +1284,14 @@ ${createHash2("sha256").update(canonicalRequest).digest("hex")}`;
551
1284
  const target = new URL(this.endpoint);
552
1285
  const basePath = target.pathname.replace(/\/$/, "");
553
1286
  const usePath = this.addressingStyle === "path" || this.addressingStyle === "auto" && (!this.isAmazonEndpoint || request.bucket.includes("."));
554
- if (usePath) target.pathname = escapeS3Path(`${basePath}/${request.bucket}${request.key === void 0 ? "" : `/${request.key}`}`);
1287
+ if (!request.bucket) target.pathname = escapeS3Path(basePath + "/");
1288
+ else if (usePath) target.pathname = escapeS3Path(`${basePath}/${request.bucket}${request.key === void 0 ? "" : `/${request.key}`}`);
555
1289
  else {
556
1290
  target.hostname = `${request.bucket}.${target.hostname}`;
557
1291
  target.pathname = escapeS3Path(`${basePath}/${request.key ?? ""}`);
558
1292
  }
559
1293
  const query = Object.entries(request.query ?? {}).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
560
- target.search = query.map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(value)}`).join("&");
1294
+ target.search = query.map(([name, value]) => `${escapeS3Path(name).replaceAll("/", "%2F")}=${escapeS3Path(value).replaceAll("/", "%2F")}`).join("&");
561
1295
  return target;
562
1296
  }
563
1297
  };
@@ -612,56 +1346,216 @@ function newProjectConnection(project, connectionName, options = {}) {
612
1346
 
613
1347
  // src/generated/steps.ts
614
1348
  import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
1349
+ function newListBucketsStep(configuration) {
1350
+ const { connection, connectionName, listed, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
1351
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1352
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listBuckets(), connection: connection.reference, branches: [
1353
+ goToBranch("listed", listed),
1354
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1355
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1356
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1357
+ ] });
1358
+ }
1359
+ function newCreateBucketStep(configuration) {
1360
+ const { connection, connectionName, created, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
1361
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1362
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createBucket(), connection: connection.reference, branches: [
1363
+ goToBranch("created", created),
1364
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1365
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
1366
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
1367
+ ] });
1368
+ }
1369
+ function newDeleteBucketStep(configuration) {
1370
+ const { connection, connectionName, deleted, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
1371
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1372
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteBucket(), connection: connection.reference, branches: [
1373
+ goToBranch("deleted", deleted),
1374
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1375
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1376
+ ] });
1377
+ }
1378
+ function newCreateFolderStep(configuration) {
1379
+ const { connection, connectionName, created, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
1380
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1381
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.createFolder(), connection: connection.reference, branches: [
1382
+ goToBranch("created", created),
1383
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1384
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1385
+ ] });
1386
+ }
1387
+ function newDeleteFolderStep(configuration) {
1388
+ const { connection, connectionName, deleted, providerRejected, invalidResponse, defect: defect2, maxSends, ...stepConfiguration } = configuration;
1389
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1390
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteFolder(), connection: connection.reference, branches: [
1391
+ goToBranch("deleted", deleted),
1392
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1393
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1394
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1395
+ ] });
1396
+ }
1397
+ function newListFoldersStep(configuration) {
1398
+ const { connection, connectionName, listed, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
1399
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1400
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.listFolders(), connection: connection.reference, branches: [
1401
+ goToBranch("listed", listed),
1402
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
1403
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1404
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1405
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1406
+ ] });
1407
+ }
615
1408
  function newListObjectsStep(configuration) {
616
- const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
1409
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
617
1410
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
618
1411
  return newQueryStep({ ...stepConfiguration, operation: connection.operations.listObjects(), connection: connection.reference, branches: [
619
1412
  goToBranch("found", found),
620
1413
  ...notFound ? [goToBranch("notFound", notFound)] : [],
621
1414
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
622
1415
  ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
623
- ...defect ? [goToBranch("defect", defect)] : []
1416
+ ...defect2 ? [goToBranch("defect", defect2)] : []
624
1417
  ] });
625
1418
  }
626
1419
  function newHeadObjectStep(configuration) {
627
- const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
1420
+ const { connection, connectionName, found, notFound, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
628
1421
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
629
1422
  return newQueryStep({ ...stepConfiguration, operation: connection.operations.headObject(), connection: connection.reference, branches: [
630
1423
  goToBranch("found", found),
631
1424
  ...notFound ? [goToBranch("notFound", notFound)] : [],
632
1425
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
633
1426
  ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
634
- ...defect ? [goToBranch("defect", defect)] : []
1427
+ ...defect2 ? [goToBranch("defect", defect2)] : []
635
1428
  ] });
636
1429
  }
637
1430
  function newGetObjectTextStep(configuration) {
638
- const { connection, connectionName, read, notFound, unsupportedContent, tooLarge, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
1431
+ const { connection, connectionName, read: read2, notFound, unsupportedContent, tooLarge, providerRejected, invalidResponse, defect: defect2, ...stepConfiguration } = configuration;
639
1432
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
640
1433
  return newQueryStep({ ...stepConfiguration, operation: connection.operations.getObjectText(), connection: connection.reference, branches: [
641
- goToBranch("read", read),
1434
+ goToBranch("read", read2),
642
1435
  ...notFound ? [goToBranch("notFound", notFound)] : [],
643
1436
  ...unsupportedContent ? [goToBranch("unsupportedContent", unsupportedContent)] : [],
644
1437
  ...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
645
1438
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
646
1439
  ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
647
- ...defect ? [goToBranch("defect", defect)] : []
1440
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1441
+ ] });
1442
+ }
1443
+ function newGetObjectBytesStep(configuration) {
1444
+ const { connection, connectionName, read: read2, notFound, tooLarge, invalidResponse, providerRejected, defect: defect2, ...stepConfiguration } = configuration;
1445
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1446
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getObjectBytes(), connection: connection.reference, branches: [
1447
+ goToBranch("read", read2),
1448
+ ...notFound ? [goToBranch("notFound", notFound)] : [],
1449
+ ...tooLarge ? [goToBranch("tooLarge", tooLarge)] : [],
1450
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
1451
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1452
+ ...defect2 ? [goToBranch("defect", defect2)] : []
648
1453
  ] });
649
1454
  }
650
1455
  function newPutObjectStep(configuration) {
651
- const { connection, connectionName, stored, alreadyExists, providerRejected, defect, ...stepConfiguration } = configuration;
1456
+ const { connection, connectionName, stored, alreadyExists, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
652
1457
  if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
653
1458
  return newMutationStep({ ...stepConfiguration, operation: connection.operations.putObject(), connection: connection.reference, branches: [
654
1459
  goToBranch("stored", stored),
655
1460
  ...alreadyExists ? [goToBranch("alreadyExists", alreadyExists)] : [],
656
1461
  ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
657
- ...defect ? [goToBranch("defect", defect)] : []
1462
+ ...defect2 ? [goToBranch("defect", defect2)] : []
1463
+ ] });
1464
+ }
1465
+ function newCopyObjectStep(configuration) {
1466
+ const { connection, connectionName, copied, providerRejected, defect: defect2, uncertain, ...stepConfiguration } = configuration;
1467
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1468
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.copyObject(), connection: connection.reference, branches: [
1469
+ goToBranch("copied", copied),
1470
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1471
+ ...defect2 ? [goToBranch("defect", defect2)] : [],
1472
+ ...uncertain ? [goToBranch("uncertain", uncertain)] : []
1473
+ ] });
1474
+ }
1475
+ function newDeleteObjectStep(configuration) {
1476
+ const { connection, connectionName, deleted, providerRejected, defect: defect2, maxSends, ...stepConfiguration } = configuration;
1477
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
1478
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteObject(), connection: connection.reference, branches: [
1479
+ goToBranch("deleted", deleted),
1480
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
1481
+ ...defect2 ? [goToBranch("defect", defect2)] : []
658
1482
  ] });
659
1483
  }
660
1484
  export {
1485
+ BucketSummarySchema,
661
1486
  ConfigSchema,
662
1487
  Connection,
663
1488
  ConnectionNameProvider,
664
1489
  ConnectorID,
1490
+ CopiedObjectSchema,
1491
+ CopyObjectBranch,
1492
+ CopyObjectBranchCopied,
1493
+ CopyObjectBranchDefect,
1494
+ CopyObjectBranchProviderRejected,
1495
+ CopyObjectBranchUncertain,
1496
+ CopyObjectDefinition,
1497
+ CopyObjectInputSchema,
1498
+ CopyObjectMetadata,
1499
+ CopyObjectOperation,
1500
+ CreateBucketBranch,
1501
+ CreateBucketBranchCreated,
1502
+ CreateBucketBranchDefect,
1503
+ CreateBucketBranchProviderRejected,
1504
+ CreateBucketBranchUncertain,
1505
+ CreateBucketDefinition,
1506
+ CreateBucketInputSchema,
1507
+ CreateBucketMetadata,
1508
+ CreateBucketOperation,
1509
+ CreateFolderBranch,
1510
+ CreateFolderBranchCreated,
1511
+ CreateFolderBranchDefect,
1512
+ CreateFolderBranchProviderRejected,
1513
+ CreateFolderDefinition,
1514
+ CreateFolderInputSchema,
1515
+ CreateFolderMetadata,
1516
+ CreateFolderOperation,
1517
+ CreatedBucketSchema,
1518
+ CreatedFolderSchema,
1519
+ CredentialMaterialError,
1520
+ DeleteBucketBranch,
1521
+ DeleteBucketBranchDefect,
1522
+ DeleteBucketBranchDeleted,
1523
+ DeleteBucketBranchProviderRejected,
1524
+ DeleteBucketDefinition,
1525
+ DeleteBucketInputSchema,
1526
+ DeleteBucketMetadata,
1527
+ DeleteBucketOperation,
1528
+ DeleteFolderBranch,
1529
+ DeleteFolderBranchDefect,
1530
+ DeleteFolderBranchDeleted,
1531
+ DeleteFolderBranchInvalidResponse,
1532
+ DeleteFolderBranchProviderRejected,
1533
+ DeleteFolderDefinition,
1534
+ DeleteFolderInputSchema,
1535
+ DeleteFolderMetadata,
1536
+ DeleteFolderOperation,
1537
+ DeleteObjectBranch,
1538
+ DeleteObjectBranchDefect,
1539
+ DeleteObjectBranchDeleted,
1540
+ DeleteObjectBranchProviderRejected,
1541
+ DeleteObjectDefinition,
1542
+ DeleteObjectInputSchema,
1543
+ DeleteObjectMetadata,
1544
+ DeleteObjectOperation,
1545
+ DeletedBucketSchema,
1546
+ DeletedFolderSchema,
1547
+ DeletedObjectSchema,
1548
+ GetObjectBytesBranch,
1549
+ GetObjectBytesBranchDefect,
1550
+ GetObjectBytesBranchInvalidResponse,
1551
+ GetObjectBytesBranchNotFound,
1552
+ GetObjectBytesBranchProviderRejected,
1553
+ GetObjectBytesBranchRead,
1554
+ GetObjectBytesBranchTooLarge,
1555
+ GetObjectBytesDefinition,
1556
+ GetObjectBytesInputSchema,
1557
+ GetObjectBytesMetadata,
1558
+ GetObjectBytesOperation,
665
1559
  GetObjectTextBranch,
666
1560
  GetObjectTextBranchDefect,
667
1561
  GetObjectTextBranchInvalidResponse,
@@ -684,6 +1578,27 @@ export {
684
1578
  HeadObjectInputSchema,
685
1579
  HeadObjectMetadata,
686
1580
  HeadObjectOperation,
1581
+ ListBucketsBranch,
1582
+ ListBucketsBranchDefect,
1583
+ ListBucketsBranchInvalidResponse,
1584
+ ListBucketsBranchListed,
1585
+ ListBucketsBranchProviderRejected,
1586
+ ListBucketsDefinition,
1587
+ ListBucketsInputSchema,
1588
+ ListBucketsMetadata,
1589
+ ListBucketsOperation,
1590
+ ListBucketsOutputSchema,
1591
+ ListFoldersBranch,
1592
+ ListFoldersBranchDefect,
1593
+ ListFoldersBranchInvalidResponse,
1594
+ ListFoldersBranchListed,
1595
+ ListFoldersBranchNotFound,
1596
+ ListFoldersBranchProviderRejected,
1597
+ ListFoldersDefinition,
1598
+ ListFoldersInputSchema,
1599
+ ListFoldersMetadata,
1600
+ ListFoldersOperation,
1601
+ ListFoldersOutputSchema,
687
1602
  ListObjectsBranch,
688
1603
  ListObjectsBranchDefect,
689
1604
  ListObjectsBranchFound,
@@ -695,6 +1610,7 @@ export {
695
1610
  ListObjectsMetadata,
696
1611
  ListObjectsOperation,
697
1612
  ListObjectsOutputSchema,
1613
+ ObjectBytesSchema,
698
1614
  ObjectMetadataSchema,
699
1615
  ObjectSummarySchema,
700
1616
  ObjectTextSchema,
@@ -711,14 +1627,30 @@ export {
711
1627
  S3Client,
712
1628
  StoredObjectSchema,
713
1629
  containsCredential,
1630
+ decodeCredentials,
1631
+ decodeSignedInteger,
1632
+ escapeS3Path,
1633
+ exactIntegerJSONCodec,
714
1634
  header,
1635
+ isCredentialMaterialError,
715
1636
  newConnection,
716
1637
  newConnectionWithOperations,
1638
+ newCopyObjectStep,
1639
+ newCreateBucketStep,
1640
+ newCreateFolderStep,
1641
+ newDeleteBucketStep,
1642
+ newDeleteFolderStep,
1643
+ newDeleteObjectStep,
1644
+ newGetObjectBytesStep,
717
1645
  newGetObjectTextStep,
718
1646
  newHeadObjectStep,
1647
+ newListBucketsStep,
1648
+ newListFoldersStep,
719
1649
  newListObjectsStep,
720
1650
  newProjectConnection,
721
1651
  newPutObjectStep,
1652
+ parseExactIntegerJSON,
1653
+ parseJSONNumberTokens,
722
1654
  retryAfter,
723
1655
  safeHeader,
724
1656
  validateBucket,