@backblaze-labs/b2-sdk 0.3.0 → 0.4.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/CHANGELOG.md +45 -1
- package/README.md +18 -5
- package/dist/_virtual/_b2-sdk-version-json.cjs +1 -1
- package/dist/_virtual/_b2-sdk-version-json.js +1 -1
- package/dist/auth/reauth-coalescer.cjs +65 -0
- package/dist/auth/reauth-coalescer.cjs.map +1 -0
- package/dist/auth/reauth-coalescer.d.cts +34 -0
- package/dist/auth/reauth-coalescer.d.cts.map +1 -0
- package/dist/auth/reauth-coalescer.d.ts +34 -0
- package/dist/auth/reauth-coalescer.d.ts.map +1 -0
- package/dist/auth/reauth-coalescer.js +65 -0
- package/dist/auth/reauth-coalescer.js.map +1 -0
- package/dist/backup/raw.cjs +37 -15
- package/dist/backup/raw.cjs.map +1 -1
- package/dist/backup/raw.d.cts +2 -2
- package/dist/backup/raw.d.cts.map +1 -1
- package/dist/backup/raw.d.ts +2 -2
- package/dist/backup/raw.d.ts.map +1 -1
- package/dist/backup/raw.js +37 -15
- package/dist/backup/raw.js.map +1 -1
- package/dist/bucket-validation.cjs +111 -0
- package/dist/bucket-validation.cjs.map +1 -0
- package/dist/bucket-validation.d.cts +27 -0
- package/dist/bucket-validation.d.cts.map +1 -0
- package/dist/bucket-validation.d.ts +27 -0
- package/dist/bucket-validation.d.ts.map +1 -0
- package/dist/bucket-validation.js +109 -0
- package/dist/bucket-validation.js.map +1 -0
- package/dist/bucket.cjs +123 -73
- package/dist/bucket.cjs.map +1 -1
- package/dist/bucket.d.cts +156 -61
- package/dist/bucket.d.cts.map +1 -1
- package/dist/bucket.d.ts +156 -61
- package/dist/bucket.d.ts.map +1 -1
- package/dist/bucket.js +123 -73
- package/dist/bucket.js.map +1 -1
- package/dist/client.cjs +29 -8
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +30 -9
- package/dist/client.d.cts.map +1 -1
- package/dist/client.d.ts +30 -9
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +29 -8
- package/dist/client.js.map +1 -1
- package/dist/download/single.cjs +38 -13
- package/dist/download/single.cjs.map +1 -1
- package/dist/download/single.d.cts +10 -4
- package/dist/download/single.d.cts.map +1 -1
- package/dist/download/single.d.ts +10 -4
- package/dist/download/single.d.ts.map +1 -1
- package/dist/download/single.js +38 -13
- package/dist/download/single.js.map +1 -1
- package/dist/errors/index.cjs +27 -4
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts +15 -0
- package/dist/errors/index.d.cts.map +1 -1
- package/dist/errors/index.d.ts +15 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +27 -5
- package/dist/errors/index.js.map +1 -1
- package/dist/http/non-idempotent-mutations.cjs +38 -0
- package/dist/http/non-idempotent-mutations.cjs.map +1 -0
- package/dist/http/non-idempotent-mutations.d.cts +25 -0
- package/dist/http/non-idempotent-mutations.d.cts.map +1 -0
- package/dist/http/non-idempotent-mutations.d.ts +25 -0
- package/dist/http/non-idempotent-mutations.d.ts.map +1 -0
- package/dist/http/non-idempotent-mutations.js +35 -0
- package/dist/http/non-idempotent-mutations.js.map +1 -0
- package/dist/http/transport.cjs +9 -8
- package/dist/http/transport.cjs.map +1 -1
- package/dist/http/transport.d.cts +5 -0
- package/dist/http/transport.d.cts.map +1 -1
- package/dist/http/transport.d.ts +5 -0
- package/dist/http/transport.d.ts.map +1 -1
- package/dist/http/transport.js +9 -8
- package/dist/http/transport.js.map +1 -1
- package/dist/http/user-agent.cjs +12 -1
- package/dist/http/user-agent.cjs.map +1 -1
- package/dist/http/user-agent.d.cts +8 -0
- package/dist/http/user-agent.d.cts.map +1 -1
- package/dist/http/user-agent.d.ts +8 -0
- package/dist/http/user-agent.d.ts.map +1 -1
- package/dist/http/user-agent.js +13 -3
- package/dist/http/user-agent.js.map +1 -1
- package/dist/index.cjs +25 -0
- package/dist/index.d.cts +10 -9
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +10 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/notifications/index.cjs +3 -0
- package/dist/notifications/index.d.cts +2 -0
- package/dist/notifications/index.d.cts.map +1 -1
- package/dist/notifications/index.d.ts +2 -0
- package/dist/notifications/index.d.ts.map +1 -1
- package/dist/notifications/index.js +2 -1
- package/dist/object.cjs +12 -1
- package/dist/object.cjs.map +1 -1
- package/dist/object.d.cts +7 -1
- package/dist/object.d.cts.map +1 -1
- package/dist/object.d.ts +7 -1
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +12 -1
- package/dist/object.js.map +1 -1
- package/dist/partner/auth-core.cjs +4 -23
- package/dist/partner/auth-core.cjs.map +1 -1
- package/dist/partner/auth-core.d.cts +1 -1
- package/dist/partner/auth-core.d.cts.map +1 -1
- package/dist/partner/auth-core.d.ts +1 -1
- package/dist/partner/auth-core.d.ts.map +1 -1
- package/dist/partner/auth-core.js +5 -24
- package/dist/partner/auth-core.js.map +1 -1
- package/dist/partner/client.cjs +25 -10
- package/dist/partner/client.cjs.map +1 -1
- package/dist/partner/client.d.cts +32 -10
- package/dist/partner/client.d.cts.map +1 -1
- package/dist/partner/client.d.ts +32 -10
- package/dist/partner/client.d.ts.map +1 -1
- package/dist/partner/client.js +25 -10
- package/dist/partner/client.js.map +1 -1
- package/dist/partner/endpoint-url.cjs +1 -0
- package/dist/partner/endpoint-url.cjs.map +1 -1
- package/dist/partner/endpoint-url.d.cts +2 -0
- package/dist/partner/endpoint-url.d.cts.map +1 -1
- package/dist/partner/endpoint-url.d.ts +2 -0
- package/dist/partner/endpoint-url.d.ts.map +1 -1
- package/dist/partner/endpoint-url.js +1 -0
- package/dist/partner/endpoint-url.js.map +1 -1
- package/dist/partner/in-memory.cjs.map +1 -1
- package/dist/partner/in-memory.js.map +1 -1
- package/dist/partner/index.cjs +9 -0
- package/dist/partner/index.d.cts +11 -2
- package/dist/partner/index.d.cts.map +1 -1
- package/dist/partner/index.d.ts +11 -2
- package/dist/partner/index.d.ts.map +1 -1
- package/dist/partner/index.js +3 -1
- package/dist/partner/raw.cjs +52 -44
- package/dist/partner/raw.cjs.map +1 -1
- package/dist/partner/raw.d.cts +16 -19
- package/dist/partner/raw.d.cts.map +1 -1
- package/dist/partner/raw.d.ts +16 -19
- package/dist/partner/raw.d.ts.map +1 -1
- package/dist/partner/raw.js +52 -44
- package/dist/partner/raw.js.map +1 -1
- package/dist/partner/redaction.cjs +133 -108
- package/dist/partner/redaction.cjs.map +1 -1
- package/dist/partner/redaction.d.cts +47 -13
- package/dist/partner/redaction.d.cts.map +1 -1
- package/dist/partner/redaction.d.ts +47 -13
- package/dist/partner/redaction.d.ts.map +1 -1
- package/dist/partner/redaction.js +133 -109
- package/dist/partner/redaction.js.map +1 -1
- package/dist/raw/encoding.cjs +29 -10
- package/dist/raw/encoding.cjs.map +1 -1
- package/dist/raw/encoding.d.cts +3 -2
- package/dist/raw/encoding.d.cts.map +1 -1
- package/dist/raw/encoding.d.ts +3 -2
- package/dist/raw/encoding.d.ts.map +1 -1
- package/dist/raw/encoding.js +29 -10
- package/dist/raw/encoding.js.map +1 -1
- package/dist/raw/index.cjs +64 -39
- package/dist/raw/index.cjs.map +1 -1
- package/dist/raw/index.d.cts +21 -19
- package/dist/raw/index.d.cts.map +1 -1
- package/dist/raw/index.d.ts +21 -19
- package/dist/raw/index.d.ts.map +1 -1
- package/dist/raw/index.js +47 -40
- package/dist/raw/index.js.map +1 -1
- package/dist/raw/url.cjs.map +1 -1
- package/dist/raw/url.d.cts +3 -3
- package/dist/raw/url.d.ts +3 -3
- package/dist/raw/url.js.map +1 -1
- package/dist/simulator/index.cjs +456 -125
- package/dist/simulator/index.cjs.map +1 -1
- package/dist/simulator/index.d.cts +16 -1
- package/dist/simulator/index.d.cts.map +1 -1
- package/dist/simulator/index.d.ts +16 -1
- package/dist/simulator/index.d.ts.map +1 -1
- package/dist/simulator/index.js +449 -130
- package/dist/simulator/index.js.map +1 -1
- package/dist/simulator/partner-capabilities.cjs +77 -0
- package/dist/simulator/partner-capabilities.cjs.map +1 -0
- package/dist/simulator/partner-capabilities.d.cts +53 -0
- package/dist/simulator/partner-capabilities.d.cts.map +1 -0
- package/dist/simulator/partner-capabilities.d.ts +53 -0
- package/dist/simulator/partner-capabilities.d.ts.map +1 -0
- package/dist/simulator/partner-capabilities.js +73 -0
- package/dist/simulator/partner-capabilities.js.map +1 -0
- package/dist/simulator/partner.cjs +55 -61
- package/dist/simulator/partner.cjs.map +1 -1
- package/dist/simulator/partner.d.cts +5 -2
- package/dist/simulator/partner.d.cts.map +1 -1
- package/dist/simulator/partner.d.ts +5 -2
- package/dist/simulator/partner.d.ts.map +1 -1
- package/dist/simulator/partner.js +56 -61
- package/dist/simulator/partner.js.map +1 -1
- package/dist/simulator/validation.cjs +160 -30
- package/dist/simulator/validation.cjs.map +1 -1
- package/dist/simulator/validation.d.cts +28 -6
- package/dist/simulator/validation.d.cts.map +1 -1
- package/dist/simulator/validation.d.ts +28 -6
- package/dist/simulator/validation.d.ts.map +1 -1
- package/dist/simulator/validation.js +148 -31
- package/dist/simulator/validation.js.map +1 -1
- package/dist/streams/file-source.cjs +1 -1
- package/dist/streams/file-source.cjs.map +1 -1
- package/dist/streams/file-source.js +1 -1
- package/dist/streams/file-source.js.map +1 -1
- package/dist/streams/hash.cjs +246 -13
- package/dist/streams/hash.cjs.map +1 -1
- package/dist/streams/hash.d.cts +37 -12
- package/dist/streams/hash.d.cts.map +1 -1
- package/dist/streams/hash.d.ts +37 -12
- package/dist/streams/hash.d.ts.map +1 -1
- package/dist/streams/hash.js +246 -15
- package/dist/streams/hash.js.map +1 -1
- package/dist/streams/index.cjs +2 -0
- package/dist/streams/index.d.cts +1 -1
- package/dist/streams/index.d.cts.map +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.d.ts.map +1 -1
- package/dist/streams/index.js +2 -2
- package/dist/streams/progress.cjs +63 -4
- package/dist/streams/progress.cjs.map +1 -1
- package/dist/streams/progress.d.cts +28 -2
- package/dist/streams/progress.d.cts.map +1 -1
- package/dist/streams/progress.d.ts +28 -2
- package/dist/streams/progress.d.ts.map +1 -1
- package/dist/streams/progress.js +63 -4
- package/dist/streams/progress.js.map +1 -1
- package/dist/sync/download-staging.cjs +147 -35
- package/dist/sync/download-staging.cjs.map +1 -1
- package/dist/sync/download-staging.d.cts +25 -2
- package/dist/sync/download-staging.d.cts.map +1 -1
- package/dist/sync/download-staging.d.ts +25 -2
- package/dist/sync/download-staging.d.ts.map +1 -1
- package/dist/sync/download-staging.js +146 -36
- package/dist/sync/download-staging.js.map +1 -1
- package/dist/sync/index.d.cts +1 -1
- package/dist/sync/index.d.cts.map +1 -1
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/local-file-io.cjs +5 -1
- package/dist/sync/local-file-io.cjs.map +1 -1
- package/dist/sync/local-file-io.d.cts +2 -0
- package/dist/sync/local-file-io.d.cts.map +1 -1
- package/dist/sync/local-file-io.d.ts +2 -0
- package/dist/sync/local-file-io.d.ts.map +1 -1
- package/dist/sync/local-file-io.js +5 -1
- package/dist/sync/local-file-io.js.map +1 -1
- package/dist/sync/pairing.cjs +1 -0
- package/dist/sync/pairing.cjs.map +1 -1
- package/dist/sync/pairing.js +1 -0
- package/dist/sync/pairing.js.map +1 -1
- package/dist/sync/scanners/b2.cjs +2 -0
- package/dist/sync/scanners/b2.cjs.map +1 -1
- package/dist/sync/scanners/b2.d.cts.map +1 -1
- package/dist/sync/scanners/b2.d.ts.map +1 -1
- package/dist/sync/scanners/b2.js +2 -0
- package/dist/sync/scanners/b2.js.map +1 -1
- package/dist/sync/scanners/local.cjs +150 -33
- package/dist/sync/scanners/local.cjs.map +1 -1
- package/dist/sync/scanners/local.d.cts +6 -0
- package/dist/sync/scanners/local.d.cts.map +1 -1
- package/dist/sync/scanners/local.d.ts +6 -0
- package/dist/sync/scanners/local.d.ts.map +1 -1
- package/dist/sync/scanners/local.js +150 -33
- package/dist/sync/scanners/local.js.map +1 -1
- package/dist/sync/synchronizer.cjs +76 -29
- package/dist/sync/synchronizer.cjs.map +1 -1
- package/dist/sync/synchronizer.d.cts +1 -0
- package/dist/sync/synchronizer.d.cts.map +1 -1
- package/dist/sync/synchronizer.d.ts +1 -0
- package/dist/sync/synchronizer.d.ts.map +1 -1
- package/dist/sync/synchronizer.js +76 -29
- package/dist/sync/synchronizer.js.map +1 -1
- package/dist/sync/types.d.cts +19 -3
- package/dist/sync/types.d.cts.map +1 -1
- package/dist/sync/types.d.ts +19 -3
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/types/backup.d.cts +6 -1
- package/dist/types/backup.d.cts.map +1 -1
- package/dist/types/backup.d.ts +6 -1
- package/dist/types/backup.d.ts.map +1 -1
- package/dist/types/bucket.cjs +81 -11
- package/dist/types/bucket.cjs.map +1 -1
- package/dist/types/bucket.d.cts +190 -39
- package/dist/types/bucket.d.cts.map +1 -1
- package/dist/types/bucket.d.ts +190 -39
- package/dist/types/bucket.d.ts.map +1 -1
- package/dist/types/bucket.js +67 -12
- package/dist/types/bucket.js.map +1 -1
- package/dist/types/download.cjs.map +1 -1
- package/dist/types/download.d.cts +3 -17
- package/dist/types/download.d.cts.map +1 -1
- package/dist/types/download.d.ts +3 -17
- package/dist/types/download.d.ts.map +1 -1
- package/dist/types/download.js.map +1 -1
- package/dist/types/encryption.cjs +18 -0
- package/dist/types/encryption.cjs.map +1 -1
- package/dist/types/encryption.d.cts +21 -11
- package/dist/types/encryption.d.cts.map +1 -1
- package/dist/types/encryption.d.ts +21 -11
- package/dist/types/encryption.d.ts.map +1 -1
- package/dist/types/encryption.js +18 -0
- package/dist/types/encryption.js.map +1 -1
- package/dist/types/file.cjs +3 -0
- package/dist/types/file.cjs.map +1 -1
- package/dist/types/file.d.cts +125 -16
- package/dist/types/file.d.cts.map +1 -1
- package/dist/types/file.d.ts +125 -16
- package/dist/types/file.d.ts.map +1 -1
- package/dist/types/file.js +3 -1
- package/dist/types/file.js.map +1 -1
- package/dist/types/index.d.cts +7 -7
- package/dist/types/index.d.cts.map +1 -1
- package/dist/types/index.d.ts +7 -7
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/key.d.cts +4 -3
- package/dist/types/key.d.cts.map +1 -1
- package/dist/types/key.d.ts +4 -3
- package/dist/types/key.d.ts.map +1 -1
- package/dist/types/notifications.cjs +30 -0
- package/dist/types/notifications.cjs.map +1 -1
- package/dist/types/notifications.d.cts +26 -1
- package/dist/types/notifications.d.cts.map +1 -1
- package/dist/types/notifications.d.ts +26 -1
- package/dist/types/notifications.d.ts.map +1 -1
- package/dist/types/notifications.js +29 -1
- package/dist/types/notifications.js.map +1 -1
- package/dist/types/partner.cjs.map +1 -1
- package/dist/types/partner.d.cts +28 -36
- package/dist/types/partner.d.cts.map +1 -1
- package/dist/types/partner.d.ts +28 -36
- package/dist/types/partner.d.ts.map +1 -1
- package/dist/types/partner.js.map +1 -1
- package/dist/types/upload.d.cts +4 -0
- package/dist/types/upload.d.cts.map +1 -1
- package/dist/types/upload.d.ts +4 -0
- package/dist/types/upload.d.ts.map +1 -1
- package/dist/upload/large.cjs +10 -7
- package/dist/upload/large.cjs.map +1 -1
- package/dist/upload/large.d.cts +15 -6
- package/dist/upload/large.d.cts.map +1 -1
- package/dist/upload/large.d.ts +15 -6
- package/dist/upload/large.d.ts.map +1 -1
- package/dist/upload/large.js +10 -7
- package/dist/upload/large.js.map +1 -1
- package/dist/upload/options.cjs.map +1 -1
- package/dist/upload/options.d.cts +12 -0
- package/dist/upload/options.d.cts.map +1 -1
- package/dist/upload/options.d.ts +12 -0
- package/dist/upload/options.d.ts.map +1 -1
- package/dist/upload/options.js.map +1 -1
- package/dist/upload/resume.cjs +4 -3
- package/dist/upload/resume.cjs.map +1 -1
- package/dist/upload/resume.d.cts +6 -4
- package/dist/upload/resume.d.cts.map +1 -1
- package/dist/upload/resume.d.ts +6 -4
- package/dist/upload/resume.d.ts.map +1 -1
- package/dist/upload/resume.js +4 -3
- package/dist/upload/resume.js.map +1 -1
- package/dist/upload/retry.cjs +17 -10
- package/dist/upload/retry.cjs.map +1 -1
- package/dist/upload/retry.d.cts.map +1 -1
- package/dist/upload/retry.d.ts.map +1 -1
- package/dist/upload/retry.js +17 -10
- package/dist/upload/retry.js.map +1 -1
- package/dist/upload/single.cjs +35 -31
- package/dist/upload/single.cjs.map +1 -1
- package/dist/upload/single.d.cts +6 -0
- package/dist/upload/single.d.cts.map +1 -1
- package/dist/upload/single.d.ts +6 -0
- package/dist/upload/single.d.ts.map +1 -1
- package/dist/upload/single.js +35 -31
- package/dist/upload/single.js.map +1 -1
- package/dist/upload/stream.cjs +12 -1
- package/dist/upload/stream.cjs.map +1 -1
- package/dist/upload/stream.d.cts +6 -0
- package/dist/upload/stream.d.cts.map +1 -1
- package/dist/upload/stream.d.ts +6 -0
- package/dist/upload/stream.d.ts.map +1 -1
- package/dist/upload/stream.js +12 -1
- package/dist/upload/stream.js.map +1 -1
- package/dist/version.cjs +56 -4
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.cts +53 -4
- package/dist/version.d.cts.map +1 -1
- package/dist/version.d.ts +53 -4
- package/dist/version.d.ts.map +1 -1
- package/dist/version.js +52 -5
- package/dist/version.js.map +1 -1
- package/package.json +11 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"single.d.ts","sourceRoot":"","sources":["../../src/upload/single.js"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAEhD,OAAO,EAAE,KAAK,gBAAgB,EAAmB,MAAM,wBAAwB,CAAA;AAC/E,OAAO,EAAE,KAAK,aAAa,EAAwB,MAAM,sBAAsB,CAAA;AAC/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAk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CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;IACpC;;;;OAIG;IACH,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAA;IACvC,qDAAqD;IACrD,QAAQ,CAAC,UAAU,CAAC,EAAE,gBAAgB,CAAA;IACtC;;;;OAIG;IACH,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAA;IACxC,kCAAkC;IAClC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAC9B;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,eAAe,CACnC,GAAG,EAAE,SAAS,EACd,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,WAAW,CAAC,CA4EtB"}
|
package/dist/upload/single.js
CHANGED
|
@@ -26,38 +26,42 @@ async function uploadSmallFile(raw, accountInfo, options) {
|
|
|
26
26
|
const sha1 = new IncrementalSha1();
|
|
27
27
|
await sha1.update(data);
|
|
28
28
|
const sha1Hex = await sha1.digest();
|
|
29
|
-
const tracker = new ProgressTracker(options.onProgress, data.byteLength, 1);
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
partNumber: null,
|
|
33
|
-
retry: options.retry,
|
|
34
|
-
signal: options.signal,
|
|
35
|
-
onUploadRetry: options.onUploadRetry,
|
|
36
|
-
retryResponseBodyFailures: resolveRetryResponseBodyFailures(options.retryResponseBodyFailures),
|
|
37
|
-
checkout: () => accountInfo.checkoutUploadUrl(options.bucketId),
|
|
38
|
-
fetchFresh: () => fetchFreshUploadUrl(raw, accountInfo, options.bucketId, options.signal),
|
|
39
|
-
returnEntry: (entry) => accountInfo.returnUploadUrl(options.bucketId, entry),
|
|
40
|
-
evictEntry: (entry) => accountInfo.evictUploadUrl(options.bucketId, entry),
|
|
41
|
-
upload: (entry) => raw.uploadFile(entry.uploadUrl, {
|
|
42
|
-
authorization: entry.authorizationToken,
|
|
29
|
+
const tracker = new ProgressTracker(options.onProgress, data.byteLength, 1, { ...options.progressIntervalMillis !== void 0 ? { minIntervalMs: options.progressIntervalMillis } : {} });
|
|
30
|
+
try {
|
|
31
|
+
const result = await withFreshUploadUrlRetry({
|
|
43
32
|
fileName: options.fileName,
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
33
|
+
partNumber: null,
|
|
34
|
+
retry: options.retry,
|
|
35
|
+
signal: options.signal,
|
|
36
|
+
onUploadRetry: options.onUploadRetry,
|
|
37
|
+
retryResponseBodyFailures: resolveRetryResponseBodyFailures(options.retryResponseBodyFailures),
|
|
38
|
+
checkout: () => accountInfo.checkoutUploadUrl(options.bucketId),
|
|
39
|
+
fetchFresh: () => fetchFreshUploadUrl(raw, accountInfo, options.bucketId, options.signal),
|
|
40
|
+
returnEntry: (entry) => accountInfo.returnUploadUrl(options.bucketId, entry),
|
|
41
|
+
evictEntry: (entry) => accountInfo.evictUploadUrl(options.bucketId, entry),
|
|
42
|
+
upload: (entry) => raw.uploadFile(entry.uploadUrl, {
|
|
43
|
+
authorization: entry.authorizationToken,
|
|
44
|
+
fileName: options.fileName,
|
|
45
|
+
contentType: options.contentType ?? "b2/x-auto",
|
|
46
|
+
contentLength: data.byteLength,
|
|
47
|
+
contentSha1: sha1Hex,
|
|
48
|
+
...options.fileInfo !== void 0 ? { fileInfo: options.fileInfo } : {},
|
|
49
|
+
...options.serverSideEncryption !== void 0 ? { serverSideEncryption: options.serverSideEncryption } : {},
|
|
50
|
+
...options.fileRetention !== void 0 ? { fileRetention: options.fileRetention } : {},
|
|
51
|
+
...options.legalHold !== void 0 ? { legalHold: options.legalHold } : {},
|
|
52
|
+
...options.lastModifiedMillis !== void 0 ? { lastModifiedMillis: options.lastModifiedMillis } : {},
|
|
53
|
+
...options.customUploadTimestamp !== void 0 ? { customUploadTimestamp: options.customUploadTimestamp } : {}
|
|
54
|
+
}, data, {
|
|
55
|
+
...options.signal !== void 0 ? { signal: options.signal } : {},
|
|
56
|
+
...options.retry !== void 0 ? { retry: options.retry } : {}
|
|
57
|
+
})
|
|
58
|
+
});
|
|
59
|
+
tracker.addBytes(data.byteLength);
|
|
60
|
+
tracker.completePart();
|
|
61
|
+
return result;
|
|
62
|
+
} finally {
|
|
63
|
+
tracker.dispose();
|
|
64
|
+
}
|
|
61
65
|
}
|
|
62
66
|
async function readSmallFileSource(source, signal) {
|
|
63
67
|
signal?.throwIfAborted();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"single.js","names":[],"sources":["../../src/upload/single.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport { type ProgressListener, ProgressTracker } from '../streams/progress.ts'\nimport { type ContentSource, collectStreamExactly } from '../streams/source.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId } from '../types/ids.ts'\nimport type { FileRetentionValue, LegalHoldValue } from '../types/lock.ts'\nimport { DEFAULT_CONTENT_TYPE } from '../util/defaults.ts'\nimport {\n fetchFreshUploadUrl,\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n withFreshUploadUrlRetry,\n} from './retry.ts'\n\n/** Options for uploading a small file in a single HTTP request. */\nexport interface UploadFileOptions extends UploadRetryOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Full B2 file name including any path prefix. */\n readonly fileName: string\n /** Content to upload. */\n readonly source: ContentSource\n /** MIME type. Defaults to `b2/x-auto` for server-side detection. */\n readonly contentType?: string\n /** Custom file info key/value pairs stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption settings. */\n readonly serverSideEncryption?: EncryptionSetting\n /** File retention policy applied at upload time. */\n readonly fileRetention?: FileRetentionValue\n /** Legal hold status applied at upload time. */\n readonly legalHold?: LegalHoldValue\n /** Override the last-modified timestamp (epoch millis). */\n readonly lastModifiedMillis?: number\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `lastModifiedMillis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /** Callback invoked with upload progress updates. */\n readonly onProgress?: ProgressListener\n /** Signal to abort the upload. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Uploads a file in a single HTTP request (suitable for files up to ~100 MB).\n *\n * The entire file content is read into memory, SHA-1 hashed, and sent in one\n * `b2_upload_file` call. For files larger than the recommended part size, use\n * {@link uploadLargeFile} which splits the file into parts uploaded in parallel.\n *\n * Upload URLs are pooled via {@link AccountInfo} and recycled on success or\n * evicted on failure.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, upload URL pool).\n * @param options - Upload parameters.\n *\n * @returns The resulting {@link FileVersion} metadata.\n */\nexport async function uploadSmallFile(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: UploadFileOptions,\n): Promise<FileVersion> {\n const data = await readSmallFileSource(options.source, options.signal)\n if (data.byteLength !== options.source.size) {\n throw new Error(\n `uploadSmallFile: source byte count does not match advertised size ` +\n `(expected ${options.source.size} bytes, got ${data.byteLength} bytes).`,\n )\n }\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n\n // Single-request uploads send the whole payload in one shot, so the\n // tracker reports a single \"part\" worth of progress: one byte burst at\n // completion and a parts-completed transition from 0 → 1. The tracker\n // is created (rather than calling the listener directly) so consumers\n // see the same {bytesTransferred, totalBytes, partsCompleted,\n // totalParts, elapsedMs} shape they get from `uploadLargeFile`.\n const tracker = new ProgressTracker(options.onProgress, data.byteLength, 1)\n\n const result = await withFreshUploadUrlRetry({\n
|
|
1
|
+
{"version":3,"file":"single.js","names":[],"sources":["../../src/upload/single.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport { type ProgressListener, ProgressTracker } from '../streams/progress.ts'\nimport { type ContentSource, collectStreamExactly } from '../streams/source.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId } from '../types/ids.ts'\nimport type { FileRetentionValue, LegalHoldValue } from '../types/lock.ts'\nimport { DEFAULT_CONTENT_TYPE } from '../util/defaults.ts'\nimport {\n fetchFreshUploadUrl,\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n withFreshUploadUrlRetry,\n} from './retry.ts'\n\n/** Options for uploading a small file in a single HTTP request. */\nexport interface UploadFileOptions extends UploadRetryOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Full B2 file name including any path prefix. */\n readonly fileName: string\n /** Content to upload. */\n readonly source: ContentSource\n /** MIME type. Defaults to `b2/x-auto` for server-side detection. */\n readonly contentType?: string\n /** Custom file info key/value pairs stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption settings. */\n readonly serverSideEncryption?: EncryptionSetting\n /** File retention policy applied at upload time. */\n readonly fileRetention?: FileRetentionValue\n /** Legal hold status applied at upload time. */\n readonly legalHold?: LegalHoldValue\n /** Override the last-modified timestamp (epoch millis). */\n readonly lastModifiedMillis?: number\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `lastModifiedMillis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /** Callback invoked with upload progress updates. */\n readonly onProgress?: ProgressListener\n /**\n * Minimum milliseconds between byte-only progress callbacks. Defaults to\n * the SDK's 100 ms progress interval; set to 0 for per-chunk callbacks.\n * Part-completion progress callbacks are always emitted immediately.\n */\n readonly progressIntervalMillis?: number\n /** Signal to abort the upload. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Uploads a file in a single HTTP request (suitable for files up to ~100 MB).\n *\n * The entire file content is read into memory, SHA-1 hashed, and sent in one\n * `b2_upload_file` call. For files larger than the recommended part size, use\n * {@link uploadLargeFile} which splits the file into parts uploaded in parallel.\n *\n * Upload URLs are pooled via {@link AccountInfo} and recycled on success or\n * evicted on failure.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, upload URL pool).\n * @param options - Upload parameters.\n *\n * @returns The resulting {@link FileVersion} metadata.\n */\nexport async function uploadSmallFile(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: UploadFileOptions,\n): Promise<FileVersion> {\n const data = await readSmallFileSource(options.source, options.signal)\n if (data.byteLength !== options.source.size) {\n throw new Error(\n `uploadSmallFile: source byte count does not match advertised size ` +\n `(expected ${options.source.size} bytes, got ${data.byteLength} bytes).`,\n )\n }\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n\n // Single-request uploads send the whole payload in one shot, so the\n // tracker reports a single \"part\" worth of progress: one byte burst at\n // completion and a parts-completed transition from 0 → 1. The tracker\n // is created (rather than calling the listener directly) so consumers\n // see the same {bytesTransferred, totalBytes, partsCompleted,\n // totalParts, elapsedMs} shape they get from `uploadLargeFile`.\n const tracker = new ProgressTracker(options.onProgress, data.byteLength, 1, {\n ...(options.progressIntervalMillis !== undefined\n ? { minIntervalMs: options.progressIntervalMillis }\n : {}),\n })\n\n try {\n const result = await withFreshUploadUrlRetry({\n fileName: options.fileName,\n partNumber: null,\n retry: options.retry,\n signal: options.signal,\n onUploadRetry: options.onUploadRetry,\n retryResponseBodyFailures: resolveRetryResponseBodyFailures(\n options.retryResponseBodyFailures,\n ),\n checkout: () => accountInfo.checkoutUploadUrl(options.bucketId),\n fetchFresh: () => fetchFreshUploadUrl(raw, accountInfo, options.bucketId, options.signal),\n returnEntry: (entry) => accountInfo.returnUploadUrl(options.bucketId, entry),\n evictEntry: (entry) => accountInfo.evictUploadUrl(options.bucketId, entry),\n upload: (entry) =>\n raw.uploadFile(\n entry.uploadUrl,\n {\n authorization: entry.authorizationToken,\n fileName: options.fileName,\n contentType: options.contentType ?? DEFAULT_CONTENT_TYPE,\n contentLength: data.byteLength,\n contentSha1: sha1Hex,\n ...(options.fileInfo !== undefined ? { fileInfo: options.fileInfo } : {}),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n ...(options.fileRetention !== undefined\n ? { fileRetention: options.fileRetention }\n : {}),\n ...(options.legalHold !== undefined ? { legalHold: options.legalHold } : {}),\n ...(options.lastModifiedMillis !== undefined\n ? { lastModifiedMillis: options.lastModifiedMillis }\n : {}),\n ...(options.customUploadTimestamp !== undefined\n ? { customUploadTimestamp: options.customUploadTimestamp }\n : {}),\n },\n data,\n {\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n },\n ),\n })\n\n tracker.addBytes(data.byteLength)\n tracker.completePart()\n return result\n } finally {\n tracker.dispose()\n }\n}\n\nasync function readSmallFileSource(\n source: ContentSource,\n signal: AbortSignal | undefined,\n): Promise<Uint8Array<ArrayBuffer>> {\n signal?.throwIfAborted()\n if (!source.canSlice) {\n return collectStreamExactly(source.stream(), source.size, signal)\n }\n const data = new Uint8Array(\n await (signal === undefined ? source.toArrayBuffer() : source.toArrayBuffer({ signal })),\n )\n signal?.throwIfAborted()\n return data\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuEA,eAAsB,gBACpB,KACA,aACA,SACsB;CACtB,MAAM,OAAO,MAAM,oBAAoB,QAAQ,QAAQ,QAAQ,MAAM;CACrE,IAAI,KAAK,eAAe,QAAQ,OAAO,MACrC,MAAM,IAAI,MACR,+EACe,QAAQ,OAAO,KAAK,cAAc,KAAK,WAAW,SACnE;CAEF,MAAM,OAAO,IAAI,gBAAgB;CACjC,MAAM,KAAK,OAAO,IAAI;CAC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Q,OAAO,IAAI,CAAC;IACjE,GAAI,QAAQ,UAAU,KAAA,IAAY,EAAE,OAAO,QAAQ,MAAM,IAAI,CAAC;GAChE,CACF;EACJ,CAAC;EAED,QAAQ,SAAS,KAAK,UAAU;EAChC,QAAQ,aAAa;EACrB,OAAO;CACT,UAAU;EACR,QAAQ,QAAQ;CAClB;AACF;AAEA,eAAe,oBACb,QACA,QACkC;CAClC,QAAQ,eAAe;CACvB,IAAI,CAAC,OAAO,UACV,OAAO,qBAAqB,OAAO,OAAO,GAAG,OAAO,MAAM,MAAM;CAElE,MAAM,OAAO,IAAI,WACf,OAAO,WAAW,KAAA,IAAY,OAAO,cAAc,IAAI,OAAO,cAAc,EAAE,OAAO,CAAC,EACxF;CACA,QAAQ,eAAe;CACvB,OAAO;AACT"}
|
package/dist/upload/stream.cjs
CHANGED
|
@@ -30,7 +30,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
30
30
|
const recommendedPartSize = accountInfo.getRecommendedPartSize();
|
|
31
31
|
const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize);
|
|
32
32
|
const concurrency = options.concurrency ?? 4;
|
|
33
|
-
const tracker = new require_progress.ProgressTracker(options.onProgress, null, null);
|
|
33
|
+
const tracker = new require_progress.ProgressTracker(options.onProgress, null, null, { ...options.progressIntervalMillis !== void 0 ? { minIntervalMs: options.progressIntervalMillis } : {} });
|
|
34
34
|
const sem = new require_concurrency.Semaphore(concurrency);
|
|
35
35
|
const abortScope = require_abort_scope.createAbortScope(options.signal);
|
|
36
36
|
let largeFileId = null;
|
|
@@ -96,6 +96,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
96
96
|
function markErrored(err) {
|
|
97
97
|
const error = require_to_error.toError(err);
|
|
98
98
|
errored = error;
|
|
99
|
+
tracker.dispose();
|
|
99
100
|
abortScope.abort(error);
|
|
100
101
|
return error;
|
|
101
102
|
}
|
|
@@ -150,6 +151,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
async function waitForInflightPartsToSettle(timeoutMs = require_cancel.DEFAULT_CLEANUP_TIMEOUT_MS) {
|
|
154
|
+
/* v8 ignore next -- only called after a large file exists, which requires at least one part */
|
|
153
155
|
if (inflight.length === 0) return;
|
|
154
156
|
let timeout;
|
|
155
157
|
try {
|
|
@@ -157,15 +159,18 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
157
159
|
timeout = setTimeout(resolve, timeoutMs);
|
|
158
160
|
})]);
|
|
159
161
|
} finally {
|
|
162
|
+
/* v8 ignore next -- setTimeout is assigned synchronously when the race promise is built */
|
|
160
163
|
if (timeout !== void 0) clearTimeout(timeout);
|
|
161
164
|
}
|
|
162
165
|
}
|
|
163
166
|
async function dispatchPart() {
|
|
167
|
+
/* v8 ignore next -- callers guard on pendingBytes before dispatching the final part */
|
|
164
168
|
if (pending.length === 0) return;
|
|
165
169
|
await acquirePartSlot();
|
|
166
170
|
let data;
|
|
167
171
|
if (pending.length === 1) {
|
|
168
172
|
const head = pending[0];
|
|
173
|
+
/* v8 ignore next -- pending is never sparse; this narrows noUncheckedIndexedAccess */
|
|
169
174
|
if (!head) {
|
|
170
175
|
sem.release();
|
|
171
176
|
return;
|
|
@@ -222,11 +227,13 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
222
227
|
signal: abortScope.signal,
|
|
223
228
|
...options.retry !== void 0 ? { retry: options.retry } : {}
|
|
224
229
|
});
|
|
230
|
+
tracker.dispose();
|
|
225
231
|
abortScope.dispose();
|
|
226
232
|
resolveDone(result);
|
|
227
233
|
} catch (err) {
|
|
228
234
|
const closeError = require_to_error.toError(err);
|
|
229
235
|
if (errored === null) errored = closeError;
|
|
236
|
+
tracker.dispose();
|
|
230
237
|
abortScope.abort(errored);
|
|
231
238
|
const observedError = errored;
|
|
232
239
|
const fileIdToCancel = largeFileId;
|
|
@@ -260,6 +267,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
260
267
|
await waitForInflightPartsToSettle();
|
|
261
268
|
await require_cancel.cancelLargeFileBestEffort(raw, accountInfo, fileIdToCancel, cleanupWriteStreamOptions(options));
|
|
262
269
|
}
|
|
270
|
+
tracker.dispose();
|
|
263
271
|
abortScope.dispose();
|
|
264
272
|
rejectDone(abortError);
|
|
265
273
|
}
|
|
@@ -288,6 +296,7 @@ function carveExact(chunks, size) {
|
|
|
288
296
|
let written = 0;
|
|
289
297
|
while (written < size && chunks.length > 0) {
|
|
290
298
|
const head = chunks[0];
|
|
299
|
+
/* v8 ignore next -- chunks is never sparse; this narrows noUncheckedIndexedAccess */
|
|
291
300
|
if (!head) break;
|
|
292
301
|
const need = size - written;
|
|
293
302
|
if (head.byteLength <= need) {
|
|
@@ -303,6 +312,7 @@ function carveExact(chunks, size) {
|
|
|
303
312
|
return out;
|
|
304
313
|
}
|
|
305
314
|
function waitForAbort(signal) {
|
|
315
|
+
/* v8 ignore next -- callers check abort before entering the start/close wait race */
|
|
306
316
|
if (signal.aborted) return {
|
|
307
317
|
promise: Promise.resolve(require_abort.abortReason(signal)),
|
|
308
318
|
dispose() {}
|
|
@@ -314,6 +324,7 @@ function waitForAbort(signal) {
|
|
|
314
324
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
315
325
|
}),
|
|
316
326
|
dispose() {
|
|
327
|
+
/* v8 ignore next -- listener is assigned synchronously with promise construction */
|
|
317
328
|
if (onAbort !== void 0) signal.removeEventListener("abort", onAbort);
|
|
318
329
|
}
|
|
319
330
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.cjs","names":[],"sources":["../../src/upload/stream.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport type { ProgressListener } from '../streams/progress.ts'\nimport { ProgressTracker } from '../streams/progress.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId, LargeFileId } from '../types/ids.ts'\nimport { abortReason, raceWithAbort } from '../util/abort.ts'\nimport { DEFAULT_CONTENT_TYPE, DEFAULT_TRANSFER_CONCURRENCY } from '../util/defaults.ts'\nimport { toError } from '../util/to-error.ts'\nimport { createAbortScope } from './abort-scope.ts'\nimport {\n type CleanupFailureOptions,\n cancelLargeFileBestEffort,\n DEFAULT_CLEANUP_TIMEOUT_MS,\n resolveLargeFileErrorAfterCleanup,\n} from './cancel.ts'\nimport { Semaphore } from './concurrency.ts'\nimport { finishLargeFileWithAbortReconciliation } from './finish.ts'\nimport {\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n uploadPartWithFreshUrl,\n} from './retry.ts'\n\n/** Options for creating a streaming multipart upload sink. */\nexport interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFailureOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Destination file name in the bucket. */\n readonly fileName: string\n /** MIME type. Defaults to `b2/x-auto`. */\n readonly contentType?: string\n /** Custom file info stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption applied to each part. */\n readonly serverSideEncryption?: EncryptionSetting\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `src_last_modified_millis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /**\n * Target part size in bytes. The stream buffers writes until this many bytes\n * are accumulated, then ships a part. Must be at least the account's\n * absolute minimum part size; the implementation will raise it if too small.\n */\n readonly partSize?: number\n /** Maximum number of parts uploaded in parallel. Defaults to 4. */\n readonly concurrency?: number\n /** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */\n readonly onProgress?: ProgressListener\n /** Aborts the upload and cancels the unfinished large file. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Handle returned by `B2Object.createWriteStream`: the Web `WritableStream` to\n * pipe data into, plus a promise that resolves with the finished\n * {@link FileVersion} once the stream is closed and all parts have been\n * uploaded.\n */\nexport interface UploadWriteHandle {\n /** Web `WritableStream` sink to pipe data into. */\n readonly writable: WritableStream<Uint8Array>\n /** Resolves with the finalized file version when the stream closes successfully. */\n readonly done: Promise<FileVersion>\n}\n\n/**\n * Creates a {@link WritableStream} that streams data into a B2 multipart upload.\n *\n * Buffers incoming chunks until `partSize` bytes are accumulated, ships each\n * complete part through the standard multipart engine, and finalizes the file\n * once the stream is closed. Honours backpressure via the queue's bounded\n * concurrency. Streaming uploads do not support resume because the total size\n * and per-part hashes aren't known in advance; use {@link uploadLargeFile} with\n * a buffered source when resume is required.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, part URL pool).\n * @param options - Streaming upload parameters.\n *\n * @returns A {@link UploadWriteHandle} with the writable sink and a completion promise.\n */\nexport function createWriteStream(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: CreateWriteStreamOptions,\n): UploadWriteHandle {\n const minPartSize = accountInfo.getAbsoluteMinimumPartSize()\n const recommendedPartSize = accountInfo.getRecommendedPartSize()\n const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize)\n const concurrency = options.concurrency ?? DEFAULT_TRANSFER_CONCURRENCY\n const tracker = new ProgressTracker(options.onProgress, null, null)\n const sem = new Semaphore(concurrency)\n const abortScope = createAbortScope(options.signal)\n\n let largeFileId: LargeFileId | null = null\n let startPromise: Promise<LargeFileId> | null = null\n let cancelAfterStartScheduled = false\n let nextPartNumber = 1\n let pendingBytes = 0\n const pending: Uint8Array[] = []\n const partSha1s: string[] = []\n const inflight: Promise<void>[] = []\n let errored: Error | null = null\n\n // ES2024 `Promise.withResolvers()` exposes the resolve/reject pair as\n // properties of the returned object, avoiding the `let resolve!:` /\n // `let reject!:` non-null-assertion pattern needed before this API\n // existed. Available in Node 22 (our minimum), Bun, Deno, modern\n // browsers, and Cloudflare Workers.\n const {\n promise: done,\n resolve: resolveDone,\n reject: rejectDone,\n } = Promise.withResolvers<FileVersion>()\n // Attach a no-op rejection handler so a `done` that rejects before the\n // caller observes it never surfaces as a process-level unhandled rejection.\n // The error is not swallowed: `close()`/`abort()` also reject the writable\n // (so `pipeTo`/`getWriter().close()` throw), and any later `await done` /\n // `done.then(onRejected)` the caller attaches still sees the rejection —\n // extra handlers on the same promise all fire. Mirrors the\n // `task.catch(() => {})` pattern used for inflight part uploads below, and\n // keeps the engine well-behaved under Bun and Node's strict\n // unhandled-rejection mode.\n done.catch(() => {})\n\n function ensureStarted(): Promise<LargeFileId> {\n if (largeFileId !== null) return Promise.resolve(largeFileId)\n if (startPromise === null) {\n const rawStart = raw.startLargeFile(\n accountInfo.getApiUrl(),\n accountInfo.getAuthToken(),\n {\n bucketId: options.bucketId,\n fileName: options.fileName,\n contentType: options.contentType ?? DEFAULT_CONTENT_TYPE,\n fileInfo: options.fileInfo ?? {},\n ...(options.customUploadTimestamp !== undefined\n ? { customUploadTimestamp: String(options.customUploadTimestamp) }\n : {}),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n },\n {\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n },\n )\n startPromise = rawStart.then((resp) => {\n largeFileId = resp.fileId\n if (abortScope.signal.aborted || errored !== null) {\n cancelStartedLargeFile(largeFileId)\n }\n return largeFileId\n })\n }\n const started = startPromise\n return raceWithAbort(started, abortScope.signal).catch((err) => {\n if (abortScope.signal.aborted) scheduleCancelLargeFileAfterStart(started)\n throw err\n })\n }\n\n async function shipPart(data: Uint8Array, partNumber: number): Promise<void> {\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n const fileId = await ensureStarted()\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n abortScope.signal.throwIfAborted()\n\n const result = await uploadPartWithFreshUrl(raw, accountInfo, fileId, {\n fileName: options.fileName,\n partNumber,\n data: data as BodyInit,\n contentLength: data.byteLength,\n contentSha1: sha1Hex,\n retry: options.retry,\n signal: abortScope.signal,\n onUploadRetry: options.onUploadRetry,\n retryResponseBodyFailures: resolveRetryResponseBodyFailures(\n options.retryResponseBodyFailures,\n ),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n })\n partSha1s[partNumber - 1] = result.contentSha1\n tracker.addBytes(data.byteLength)\n tracker.completePart()\n }\n\n function markErrored(err: unknown): Error {\n const error = toError(err)\n errored = error\n abortScope.abort(error)\n return error\n }\n\n function cancelStartedLargeFile(fileId: LargeFileId): void {\n if (cancelAfterStartScheduled) return\n cancelAfterStartScheduled = true\n void cancelLargeFileBestEffort(raw, accountInfo, fileId, cleanupWriteStreamOptions(options))\n }\n\n function scheduleCancelLargeFileAfterStart(started: Promise<LargeFileId>): void {\n void started\n .then((fileId) => cancelStartedLargeFile(fileId))\n .catch(() => {\n // If start failed, no file ID is available to cancel.\n })\n }\n\n async function settleInflightForClose(): Promise<PromiseSettledResult<void>[]> {\n const settled = Promise.allSettled(inflight)\n if (startPromise === null || largeFileId !== null) return await settled\n\n const abortWaiter = waitForAbort(abortScope.signal)\n try {\n const first = await Promise.race([\n settled.then(() => 'settled' as const),\n startPromise.then(\n () => 'start-settled' as const,\n () => 'start-settled' as const,\n ),\n abortWaiter.promise.then(() => 'aborted' as const),\n ])\n if (first === 'aborted' && largeFileId === null) {\n throw abortReason(abortScope.signal)\n }\n return await settled\n } finally {\n abortWaiter.dispose()\n }\n }\n\n function startPartWithAcquiredSlot(data: Uint8Array, partNumber: number): void {\n const task = (async () => {\n try {\n await shipPart(data, partNumber)\n } catch (err) {\n markErrored(err)\n throw err\n } finally {\n sem.release()\n }\n })()\n inflight.push(task)\n // Swallow rejection here; we check `errored` later.\n task.catch(() => {})\n }\n\n async function acquirePartSlot(): Promise<void> {\n await sem.acquire()\n if (errored !== null) {\n sem.release()\n throw errored\n }\n try {\n abortScope.signal.throwIfAborted()\n } catch (err) {\n sem.release()\n throw err\n }\n }\n\n async function waitForInflightPartsToSettle(\n timeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS,\n ): Promise<void> {\n if (inflight.length === 0) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.allSettled(inflight).then(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async function dispatchPart(): Promise<void> {\n if (pending.length === 0) return\n await acquirePartSlot()\n let data: Uint8Array\n if (pending.length === 1) {\n const head = pending[0]\n if (!head) {\n sem.release()\n return\n }\n data = head\n } else {\n const total = pending.reduce((sum, chunk) => sum + chunk.byteLength, 0)\n data = new Uint8Array(total)\n let offset = 0\n for (const chunk of pending) {\n data.set(chunk, offset)\n offset += chunk.byteLength\n }\n }\n pending.length = 0\n pendingBytes = 0\n const partNumber = nextPartNumber++\n startPartWithAcquiredSlot(data, partNumber)\n }\n\n const writable = new WritableStream<Uint8Array>({\n async write(chunk: Uint8Array): Promise<void> {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n if (chunk.byteLength === 0) return\n\n pending.push(chunk)\n pendingBytes += chunk.byteLength\n while (pendingBytes >= partSize) {\n await acquirePartSlot()\n if (errored) {\n sem.release()\n throw errored\n }\n // Pull exactly partSize bytes off the front\n const carved = carveExact(pending, partSize)\n const partNumber = nextPartNumber++\n pendingBytes -= partSize\n startPartWithAcquiredSlot(carved, partNumber)\n }\n },\n\n async close(): Promise<void> {\n try {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n\n // Ship any remaining bytes as the last part. If the total fit in one\n // single buffered batch (no parts shipped yet), we have to use the\n // multipart path anyway since we already called startLargeFile lazily.\n if (pendingBytes > 0) {\n await dispatchPart()\n }\n\n const settled = await settleInflightForClose()\n const rejected = settled.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (rejected !== undefined && errored === null) {\n markErrored(rejected.reason)\n }\n if (errored) throw errored\n\n if (largeFileId === null) {\n // Stream closed before any data was written. Start an empty large\n // file? B2 requires at least 2 parts. Reject — callers shouldn't\n // close an empty stream.\n throw new Error('createWriteStream closed without any data written.')\n }\n\n const result = await finishLargeFileWithAbortReconciliation(raw, accountInfo, {\n fileId: largeFileId,\n bucketId: options.bucketId,\n fileName: options.fileName,\n partSha1s,\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n })\n abortScope.dispose()\n resolveDone(result)\n } catch (err) {\n const closeError = toError(err)\n if (errored === null) errored = closeError\n abortScope.abort(errored)\n const observedError = errored\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Mirror writer.abort(): close() must not wait for non-abortable\n // b2_start_large_file. If a file ID arrives later, cancel it in the\n // background.\n scheduleCancelLargeFileAfterStart(startPromise)\n abortScope.dispose()\n rejectDone(observedError)\n throw observedError\n }\n await Promise.allSettled(inflight)\n // Capture into a const so the cancel closure sees a non-null\n // `fileId`; closures don't observe the outer `!== null` narrowing\n // because the variable is mutable across the lambda boundary.\n let finalError: unknown = observedError\n if (fileIdToCancel !== null) {\n finalError = await resolveLargeFileErrorAfterCleanup(observedError, raw, accountInfo, {\n fileId: fileIdToCancel,\n bucketId: options.bucketId,\n fileName: options.fileName,\n signal: options.signal,\n onCleanupFailure: options.onCleanupFailure,\n })\n }\n abortScope.dispose()\n rejectDone(finalError)\n throw finalError\n }\n },\n\n async abort(reason: unknown): Promise<void> {\n const abortError = markErrored(reason)\n pending.length = 0\n pendingBytes = 0\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Do not await an in-flight start request here. A stalled\n // b2_start_large_file must not make writer.abort() hang; if it later\n // returns a file ID, cancel it best-effort in the background.\n scheduleCancelLargeFileAfterStart(startPromise)\n }\n if (fileIdToCancel !== null) {\n await waitForInflightPartsToSettle()\n await cancelLargeFileBestEffort(\n raw,\n accountInfo,\n fileIdToCancel,\n cleanupWriteStreamOptions(options),\n )\n }\n abortScope.dispose()\n rejectDone(abortError)\n },\n })\n\n return { writable, done }\n}\n\nfunction cleanupWriteStreamOptions(options: CreateWriteStreamOptions): {\n readonly signal?: AbortSignal\n} & CleanupFailureOptions {\n return {\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onCleanupFailure !== undefined\n ? { onCleanupFailure: options.onCleanupFailure }\n : {}),\n }\n}\n\n/**\n * Removes exactly `size` bytes from the front of `chunks` (mutates) and returns\n * them as a contiguous Uint8Array. Any trailing remainder of the last chunk\n * stays at the front of `chunks` for the next part.\n *\n * @param chunks - Queue of pending chunks. Modified in place.\n * @param size - Number of bytes to carve off the front.\n *\n * @returns A new Uint8Array containing exactly `size` bytes.\n */\nfunction carveExact(chunks: Uint8Array[], size: number): Uint8Array {\n const out = new Uint8Array(size)\n let written = 0\n while (written < size && chunks.length > 0) {\n const head = chunks[0]\n if (!head) break\n const need = size - written\n if (head.byteLength <= need) {\n out.set(head, written)\n written += head.byteLength\n chunks.shift()\n } else {\n out.set(head.subarray(0, need), written)\n chunks[0] = head.subarray(need)\n written += need\n }\n }\n return out\n}\n\nfunction waitForAbort(signal: AbortSignal): {\n readonly promise: Promise<unknown>\n dispose(): void\n} {\n if (signal.aborted) {\n return {\n promise: Promise.resolve(abortReason(signal)),\n dispose() {},\n }\n }\n\n let onAbort: (() => void) | undefined\n const promise = new Promise<unknown>((resolve) => {\n onAbort = () => resolve(abortReason(signal))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n\n return {\n promise,\n dispose() {\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,SAAgB,kBACd,KACA,aACA,SACmB;CACnB,MAAM,cAAc,YAAY,2BAA2B;CAC3D,MAAM,sBAAsB,YAAY,uBAAuB;CAC/D,MAAM,WAAW,KAAK,IAAI,QAAQ,YAAY,qBAAqB,WAAW;CAC9E,MAAM,cAAc,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AAsB,MAA0B;CAClE,MAAM,MAAM,IAAI,WAAW,IAAI;CAC/B,IAAI,UAAU;CACd,OAAO,UAAU,QAAQ,OAAO,SAAS,GAAG;EAC1C,MAAM,OAAO,OAAO;EACpB,IAAI,CAAC,MAAM;EACX,MAAM,OAAO,OAAO;EACpB,IAAI,KAAK,cAAc,MAAM;GAC3B,IAAI,IAAI,MAAM,OAAO;GACrB,WAAW,KAAK;GAChB,OAAO,MAAM;EACf,OAAO;GACL,IAAI,IAAI,KAAK,SAAS,GAAG,IAAI,GAAG,OAAO;GACvC,OAAO,KAAK,KAAK,SAAS,IAAI;GAC9B,WAAW;EACb;CACF;CACA,OAAO;AACT;AAEA,SAAS,aAAa,QAGpB;CACA,IAAI,OAAO,SACT,OAAO;EACL,SAAS,QAAQ,QAAQ,cAAA,YAAY,MAAM,CAAC;EAC5C,UAAU,CAAC;CACb;CAGF,IAAI;CAMJ,OAAO;EACL,SAAA,IANkB,SAAkB,YAAY;GAChD,gBAAgB,QAAQ,cAAA,YAAY,MAAM,CAAC;GAC3C,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D,CAGE;EACA,UAAU;GACR,IAAI,YAAY,KAAA,GAAW,OAAO,oBAAoB,SAAS,OAAO;EACxE;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"stream.cjs","names":[],"sources":["../../src/upload/stream.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport type { ProgressListener } from '../streams/progress.ts'\nimport { ProgressTracker } from '../streams/progress.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId, LargeFileId } from '../types/ids.ts'\nimport { abortReason, raceWithAbort } from '../util/abort.ts'\nimport { DEFAULT_CONTENT_TYPE, DEFAULT_TRANSFER_CONCURRENCY } from '../util/defaults.ts'\nimport { toError } from '../util/to-error.ts'\nimport { createAbortScope } from './abort-scope.ts'\nimport {\n type CleanupFailureOptions,\n cancelLargeFileBestEffort,\n DEFAULT_CLEANUP_TIMEOUT_MS,\n resolveLargeFileErrorAfterCleanup,\n} from './cancel.ts'\nimport { Semaphore } from './concurrency.ts'\nimport { finishLargeFileWithAbortReconciliation } from './finish.ts'\nimport {\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n uploadPartWithFreshUrl,\n} from './retry.ts'\n\n/** Options for creating a streaming multipart upload sink. */\nexport interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFailureOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Destination file name in the bucket. */\n readonly fileName: string\n /** MIME type. Defaults to `b2/x-auto`. */\n readonly contentType?: string\n /** Custom file info stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption applied to each part. */\n readonly serverSideEncryption?: EncryptionSetting\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `src_last_modified_millis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /**\n * Target part size in bytes. The stream buffers writes until this many bytes\n * are accumulated, then ships a part. Must be at least the account's\n * absolute minimum part size; the implementation will raise it if too small.\n */\n readonly partSize?: number\n /** Maximum number of parts uploaded in parallel. Defaults to 4. */\n readonly concurrency?: number\n /** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */\n readonly onProgress?: ProgressListener\n /**\n * Minimum milliseconds between byte-only progress callbacks. Defaults to\n * the SDK's 100 ms progress interval; set to 0 for per-chunk callbacks.\n * Part-completion progress callbacks are always emitted immediately.\n */\n readonly progressIntervalMillis?: number\n /** Aborts the upload and cancels the unfinished large file. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Handle returned by `B2Object.createWriteStream`: the Web `WritableStream` to\n * pipe data into, plus a promise that resolves with the finished\n * {@link FileVersion} once the stream is closed and all parts have been\n * uploaded.\n */\nexport interface UploadWriteHandle {\n /** Web `WritableStream` sink to pipe data into. */\n readonly writable: WritableStream<Uint8Array>\n /** Resolves with the finalized file version when the stream closes successfully. */\n readonly done: Promise<FileVersion>\n}\n\n/**\n * Creates a {@link WritableStream} that streams data into a B2 multipart upload.\n *\n * Buffers incoming chunks until `partSize` bytes are accumulated, ships each\n * complete part through the standard multipart engine, and finalizes the file\n * once the stream is closed. Honours backpressure via the queue's bounded\n * concurrency. Streaming uploads do not support resume because the total size\n * and per-part hashes aren't known in advance; use {@link uploadLargeFile} with\n * a buffered source when resume is required.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, part URL pool).\n * @param options - Streaming upload parameters.\n *\n * @returns A {@link UploadWriteHandle} with the writable sink and a completion promise.\n */\nexport function createWriteStream(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: CreateWriteStreamOptions,\n): UploadWriteHandle {\n const minPartSize = accountInfo.getAbsoluteMinimumPartSize()\n const recommendedPartSize = accountInfo.getRecommendedPartSize()\n const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize)\n const concurrency = options.concurrency ?? DEFAULT_TRANSFER_CONCURRENCY\n const tracker = new ProgressTracker(options.onProgress, null, null, {\n ...(options.progressIntervalMillis !== undefined\n ? { minIntervalMs: options.progressIntervalMillis }\n : {}),\n })\n const sem = new Semaphore(concurrency)\n const abortScope = createAbortScope(options.signal)\n\n let largeFileId: LargeFileId | null = null\n let startPromise: Promise<LargeFileId> | null = null\n let cancelAfterStartScheduled = false\n let nextPartNumber = 1\n let pendingBytes = 0\n const pending: Uint8Array[] = []\n const partSha1s: string[] = []\n const inflight: Promise<void>[] = []\n let errored: Error | null = null\n\n // ES2024 `Promise.withResolvers()` exposes the resolve/reject pair as\n // properties of the returned object, avoiding the `let resolve!:` /\n // `let reject!:` non-null-assertion pattern needed before this API\n // existed. Available in Node 22 (our minimum), Bun, Deno, modern\n // browsers, and Cloudflare Workers.\n const {\n promise: done,\n resolve: resolveDone,\n reject: rejectDone,\n } = Promise.withResolvers<FileVersion>()\n // Attach a no-op rejection handler so a `done` that rejects before the\n // caller observes it never surfaces as a process-level unhandled rejection.\n // The error is not swallowed: `close()`/`abort()` also reject the writable\n // (so `pipeTo`/`getWriter().close()` throw), and any later `await done` /\n // `done.then(onRejected)` the caller attaches still sees the rejection —\n // extra handlers on the same promise all fire. Mirrors the\n // `task.catch(() => {})` pattern used for inflight part uploads below, and\n // keeps the engine well-behaved under Bun and Node's strict\n // unhandled-rejection mode.\n done.catch(() => {})\n\n function ensureStarted(): Promise<LargeFileId> {\n if (largeFileId !== null) return Promise.resolve(largeFileId)\n if (startPromise === null) {\n const rawStart = raw.startLargeFile(\n accountInfo.getApiUrl(),\n accountInfo.getAuthToken(),\n {\n bucketId: options.bucketId,\n fileName: options.fileName,\n contentType: options.contentType ?? DEFAULT_CONTENT_TYPE,\n fileInfo: options.fileInfo ?? {},\n ...(options.customUploadTimestamp !== undefined\n ? { customUploadTimestamp: String(options.customUploadTimestamp) }\n : {}),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n },\n {\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n },\n )\n startPromise = rawStart.then((resp) => {\n largeFileId = resp.fileId\n if (abortScope.signal.aborted || errored !== null) {\n cancelStartedLargeFile(largeFileId)\n }\n return largeFileId\n })\n }\n const started = startPromise\n return raceWithAbort(started, abortScope.signal).catch((err) => {\n if (abortScope.signal.aborted) scheduleCancelLargeFileAfterStart(started)\n throw err\n })\n }\n\n async function shipPart(data: Uint8Array, partNumber: number): Promise<void> {\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n const fileId = await ensureStarted()\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n abortScope.signal.throwIfAborted()\n\n const result = await uploadPartWithFreshUrl(raw, accountInfo, fileId, {\n fileName: options.fileName,\n partNumber,\n data: data as BodyInit,\n contentLength: data.byteLength,\n contentSha1: sha1Hex,\n retry: options.retry,\n signal: abortScope.signal,\n onUploadRetry: options.onUploadRetry,\n retryResponseBodyFailures: resolveRetryResponseBodyFailures(\n options.retryResponseBodyFailures,\n ),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n })\n partSha1s[partNumber - 1] = result.contentSha1\n tracker.addBytes(data.byteLength)\n tracker.completePart()\n }\n\n function markErrored(err: unknown): Error {\n const error = toError(err)\n errored = error\n tracker.dispose()\n abortScope.abort(error)\n return error\n }\n\n function cancelStartedLargeFile(fileId: LargeFileId): void {\n if (cancelAfterStartScheduled) return\n cancelAfterStartScheduled = true\n void cancelLargeFileBestEffort(raw, accountInfo, fileId, cleanupWriteStreamOptions(options))\n }\n\n function scheduleCancelLargeFileAfterStart(started: Promise<LargeFileId>): void {\n void started\n .then((fileId) => cancelStartedLargeFile(fileId))\n .catch(() => {\n // If start failed, no file ID is available to cancel.\n })\n }\n\n async function settleInflightForClose(): Promise<PromiseSettledResult<void>[]> {\n const settled = Promise.allSettled(inflight)\n if (startPromise === null || largeFileId !== null) return await settled\n\n const abortWaiter = waitForAbort(abortScope.signal)\n try {\n const first = await Promise.race([\n settled.then(() => 'settled' as const),\n startPromise.then(\n () => 'start-settled' as const,\n () => 'start-settled' as const,\n ),\n abortWaiter.promise.then(() => 'aborted' as const),\n ])\n if (first === 'aborted' && largeFileId === null) {\n throw abortReason(abortScope.signal)\n }\n return await settled\n } finally {\n abortWaiter.dispose()\n }\n }\n\n function startPartWithAcquiredSlot(data: Uint8Array, partNumber: number): void {\n const task = (async () => {\n try {\n await shipPart(data, partNumber)\n } catch (err) {\n markErrored(err)\n throw err\n } finally {\n sem.release()\n }\n })()\n inflight.push(task)\n // Swallow rejection here; we check `errored` later.\n task.catch(() => {})\n }\n\n async function acquirePartSlot(): Promise<void> {\n await sem.acquire()\n if (errored !== null) {\n sem.release()\n throw errored\n }\n try {\n abortScope.signal.throwIfAborted()\n } catch (err) {\n sem.release()\n throw err\n }\n }\n\n async function waitForInflightPartsToSettle(\n timeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS,\n ): Promise<void> {\n /* v8 ignore next -- only called after a large file exists, which requires at least one part */\n if (inflight.length === 0) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.allSettled(inflight).then(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs)\n }),\n ])\n } finally {\n /* v8 ignore next -- setTimeout is assigned synchronously when the race promise is built */\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async function dispatchPart(): Promise<void> {\n /* v8 ignore next -- callers guard on pendingBytes before dispatching the final part */\n if (pending.length === 0) return\n await acquirePartSlot()\n let data: Uint8Array\n if (pending.length === 1) {\n const head = pending[0]\n /* v8 ignore next -- pending is never sparse; this narrows noUncheckedIndexedAccess */\n if (!head) {\n sem.release()\n return\n }\n data = head\n } else {\n const total = pending.reduce((sum, chunk) => sum + chunk.byteLength, 0)\n data = new Uint8Array(total)\n let offset = 0\n for (const chunk of pending) {\n data.set(chunk, offset)\n offset += chunk.byteLength\n }\n }\n pending.length = 0\n pendingBytes = 0\n const partNumber = nextPartNumber++\n startPartWithAcquiredSlot(data, partNumber)\n }\n\n const writable = new WritableStream<Uint8Array>({\n async write(chunk: Uint8Array): Promise<void> {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n if (chunk.byteLength === 0) return\n\n pending.push(chunk)\n pendingBytes += chunk.byteLength\n while (pendingBytes >= partSize) {\n await acquirePartSlot()\n if (errored) {\n sem.release()\n throw errored\n }\n // Pull exactly partSize bytes off the front\n const carved = carveExact(pending, partSize)\n const partNumber = nextPartNumber++\n pendingBytes -= partSize\n startPartWithAcquiredSlot(carved, partNumber)\n }\n },\n\n async close(): Promise<void> {\n try {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n\n // Ship any remaining bytes as the last part. If the total fit in one\n // single buffered batch (no parts shipped yet), we have to use the\n // multipart path anyway since we already called startLargeFile lazily.\n if (pendingBytes > 0) {\n await dispatchPart()\n }\n\n const settled = await settleInflightForClose()\n const rejected = settled.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (rejected !== undefined && errored === null) {\n markErrored(rejected.reason)\n }\n if (errored) throw errored\n\n if (largeFileId === null) {\n // Stream closed before any data was written. Start an empty large\n // file? B2 requires at least 2 parts. Reject — callers shouldn't\n // close an empty stream.\n throw new Error('createWriteStream closed without any data written.')\n }\n\n const result = await finishLargeFileWithAbortReconciliation(raw, accountInfo, {\n fileId: largeFileId,\n bucketId: options.bucketId,\n fileName: options.fileName,\n partSha1s,\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n })\n tracker.dispose()\n abortScope.dispose()\n resolveDone(result)\n } catch (err) {\n const closeError = toError(err)\n if (errored === null) errored = closeError\n tracker.dispose()\n abortScope.abort(errored)\n const observedError = errored\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Mirror writer.abort(): close() must not wait for non-abortable\n // b2_start_large_file. If a file ID arrives later, cancel it in the\n // background.\n scheduleCancelLargeFileAfterStart(startPromise)\n abortScope.dispose()\n rejectDone(observedError)\n throw observedError\n }\n await Promise.allSettled(inflight)\n // Capture into a const so the cancel closure sees a non-null\n // `fileId`; closures don't observe the outer `!== null` narrowing\n // because the variable is mutable across the lambda boundary.\n let finalError: unknown = observedError\n if (fileIdToCancel !== null) {\n finalError = await resolveLargeFileErrorAfterCleanup(observedError, raw, accountInfo, {\n fileId: fileIdToCancel,\n bucketId: options.bucketId,\n fileName: options.fileName,\n signal: options.signal,\n onCleanupFailure: options.onCleanupFailure,\n })\n }\n abortScope.dispose()\n rejectDone(finalError)\n throw finalError\n }\n },\n\n async abort(reason: unknown): Promise<void> {\n const abortError = markErrored(reason)\n pending.length = 0\n pendingBytes = 0\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Do not await an in-flight start request here. A stalled\n // b2_start_large_file must not make writer.abort() hang; if it later\n // returns a file ID, cancel it best-effort in the background.\n scheduleCancelLargeFileAfterStart(startPromise)\n }\n if (fileIdToCancel !== null) {\n await waitForInflightPartsToSettle()\n await cancelLargeFileBestEffort(\n raw,\n accountInfo,\n fileIdToCancel,\n cleanupWriteStreamOptions(options),\n )\n }\n tracker.dispose()\n abortScope.dispose()\n rejectDone(abortError)\n },\n })\n\n return { writable, done }\n}\n\nfunction cleanupWriteStreamOptions(options: CreateWriteStreamOptions): {\n readonly signal?: AbortSignal\n} & CleanupFailureOptions {\n return {\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onCleanupFailure !== undefined\n ? { onCleanupFailure: options.onCleanupFailure }\n : {}),\n }\n}\n\n/**\n * Removes exactly `size` bytes from the front of `chunks` (mutates) and returns\n * them as a contiguous Uint8Array. Any trailing remainder of the last chunk\n * stays at the front of `chunks` for the next part.\n *\n * @param chunks - Queue of pending chunks. Modified in place.\n * @param size - Number of bytes to carve off the front.\n *\n * @returns A new Uint8Array containing exactly `size` bytes.\n */\nfunction carveExact(chunks: Uint8Array[], size: number): Uint8Array {\n const out = new Uint8Array(size)\n let written = 0\n while (written < size && chunks.length > 0) {\n const head = chunks[0]\n /* v8 ignore next -- chunks is never sparse; this narrows noUncheckedIndexedAccess */\n if (!head) break\n const need = size - written\n if (head.byteLength <= need) {\n out.set(head, written)\n written += head.byteLength\n chunks.shift()\n } else {\n out.set(head.subarray(0, need), written)\n chunks[0] = head.subarray(need)\n written += need\n }\n }\n return out\n}\n\nfunction waitForAbort(signal: AbortSignal): {\n readonly promise: Promise<unknown>\n dispose(): void\n} {\n /* v8 ignore next -- callers check abort before entering the start/close wait race */\n if (signal.aborted) {\n return {\n promise: Promise.resolve(abortReason(signal)),\n dispose() {},\n }\n }\n\n let onAbort: (() => void) | undefined\n const promise = new Promise<unknown>((resolve) => {\n onAbort = () => resolve(abortReason(signal))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n\n return {\n promise,\n dispose() {\n /* v8 ignore next -- listener is assigned synchronously with promise construction */\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FA,SAAgB,kBACd,KACA,aACA,SACmB;CACnB,MAAM,cAAc,YAAY,2BAA2B;CAC3D,MAAM,sBAAsB,YAAY,uBAAuB;CAC/D,MAAM,WAAW,KAAK,IAAI,QAAQ,YAAY,qBAAqB,WAAW;CAC9E,MAAM,cAAc,QAAQ,eAAA;CAC5B,MAAM,UAAU,IAAI,iBAAA,gBAAgB,QAAQ,YAAY,MAAM,MAAM,EAClE,GAAI,QAAQ,2BAA2B,KAAA,IACnC,EAAE,eAAe,QAAQ,uBAAuB,IAChD,CAAC,EACP,CAAC;CACD,MAAM,MAAM,IAAI,oBAAA,UAAU,WAAW;CACrC,MAAM,aAAa,oBAAA,iBAAiB,QAAQ,MAAM;CAElD,IAAI,cAAkC;CACtC,IAAI,eAA4C;CAChD,IAAI,4BAA4B;CAChC,IAAI,iBAAiB;CACrB,IAAI,eAAe;CACnB,MAAM,UAAwB,CAAC;CAC/B,MAAM,YAAsB,CAAC;CAC7B,MAAM,WAA4B,CAAC;CACnC,IAAI,UAAwB;CAO5B,MAAM,EACJ,SAAS,MACT,SAAS,aACT,QAAQ,eACN,QAAQ,cAA2B;CAUvC,KAAK,YAAY,CAAC,CAAC;CAEnB,SAAS,gBAAsC;EAC7C,IAAI,gBAAgB,MAAM,OAAO,QAAQ,QAAQ,WAAW;EAC5D,IAAI,iBAAiB,MAqBnB,eApBiB,IAAI,eACnB,YAAY,UAAU,GACtB,YAAY,aAAa,GACzB;GACE,UAAU,QAAQ;GAClB,UAAU,QAAQ;GAClB,aAAa,QAAQ,eAAA;GACrB,UAAU,QAAQ,YAAY,CAAC;GAC/B,GAAI,QAAQ,0BAA0B,KAAA,IA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AiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D,CAGE;EACA,UAAU;;GAER,IAAI,YAAY,KAAA,GAAW,OAAO,oBAAoB,SAAS,OAAO;EACxE;CACF;AACF"}
|
package/dist/upload/stream.d.cts
CHANGED
|
@@ -34,6 +34,12 @@ export interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFai
|
|
|
34
34
|
readonly concurrency?: number;
|
|
35
35
|
/** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */
|
|
36
36
|
readonly onProgress?: ProgressListener;
|
|
37
|
+
/**
|
|
38
|
+
* Minimum milliseconds between byte-only progress callbacks. Defaults to
|
|
39
|
+
* the SDK's 100 ms progress interval; set to 0 for per-chunk callbacks.
|
|
40
|
+
* Part-completion progress callbacks are always emitted immediately.
|
|
41
|
+
*/
|
|
42
|
+
readonly progressIntervalMillis?: number;
|
|
37
43
|
/** Aborts the upload and cancels the unfinished large file. */
|
|
38
44
|
readonly signal?: AbortSignal;
|
|
39
45
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/upload/stream.js"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAEhD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,KAAK,EAAE,QAAQ,EAAe,MAAM,iBAAiB,CAAA;AAK5D,OAAO,EACL,KAAK,qBAAqB,EAI3B,MAAM,aAAa,CAAA;AAGpB,OAAO,EAEL,KAAK,kBAAkB,EAExB,MAAM,YAAY,CAAA;AAEnB,8DAA8D;AAC9D,MAAM,WAAW,wB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AM,WAAW,iBAAiB;IAChC,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;IAC7C,oFAAoF;IACpF,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAA;CACpC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,SAAS,EACd,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,wBAAwB,GAChC,iBAAiB,CAyWnB"}
|
package/dist/upload/stream.d.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFai
|
|
|
34
34
|
readonly concurrency?: number;
|
|
35
35
|
/** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */
|
|
36
36
|
readonly onProgress?: ProgressListener;
|
|
37
|
+
/**
|
|
38
|
+
* Minimum milliseconds between byte-only progress callbacks. Defaults to
|
|
39
|
+
* the SDK's 100 ms progress interval; set to 0 for per-chunk callbacks.
|
|
40
|
+
* Part-completion progress callbacks are always emitted immediately.
|
|
41
|
+
*/
|
|
42
|
+
readonly progressIntervalMillis?: number;
|
|
37
43
|
/** Aborts the upload and cancels the unfinished large file. */
|
|
38
44
|
readonly signal?: AbortSignal;
|
|
39
45
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/upload/stream.js"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAA;AAEhD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAE9D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,KAAK,EAAE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CAAC,EAAE,gBAAgB,CAAA;IACtC;;;;OAIG;IACH,QAAQ,CAAC,sBAAsB,CAAC,EAAE,MAAM,CAAA;IACxC,+DAA+D;IAC/D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAC9B;AAED;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC,mDAAmD;IACnD,QAAQ,CAAC,QAAQ,EAAE,cAAc,CAAC,UAAU,CAAC,CAAA;IAC7C,oFAAoF;IACpF,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAA;CACpC;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,SAAS,EACd,WAAW,EAAE,WAAW,EACxB,OAAO,EAAE,wBAAwB,GAChC,iBAAiB,CAyWnB"}
|
package/dist/upload/stream.js
CHANGED
|
@@ -30,7 +30,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
30
30
|
const recommendedPartSize = accountInfo.getRecommendedPartSize();
|
|
31
31
|
const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize);
|
|
32
32
|
const concurrency = options.concurrency ?? 4;
|
|
33
|
-
const tracker = new ProgressTracker(options.onProgress, null, null);
|
|
33
|
+
const tracker = new ProgressTracker(options.onProgress, null, null, { ...options.progressIntervalMillis !== void 0 ? { minIntervalMs: options.progressIntervalMillis } : {} });
|
|
34
34
|
const sem = new Semaphore(concurrency);
|
|
35
35
|
const abortScope = createAbortScope(options.signal);
|
|
36
36
|
let largeFileId = null;
|
|
@@ -96,6 +96,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
96
96
|
function markErrored(err) {
|
|
97
97
|
const error = toError(err);
|
|
98
98
|
errored = error;
|
|
99
|
+
tracker.dispose();
|
|
99
100
|
abortScope.abort(error);
|
|
100
101
|
return error;
|
|
101
102
|
}
|
|
@@ -150,6 +151,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
150
151
|
}
|
|
151
152
|
}
|
|
152
153
|
async function waitForInflightPartsToSettle(timeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS) {
|
|
154
|
+
/* v8 ignore next -- only called after a large file exists, which requires at least one part */
|
|
153
155
|
if (inflight.length === 0) return;
|
|
154
156
|
let timeout;
|
|
155
157
|
try {
|
|
@@ -157,15 +159,18 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
157
159
|
timeout = setTimeout(resolve, timeoutMs);
|
|
158
160
|
})]);
|
|
159
161
|
} finally {
|
|
162
|
+
/* v8 ignore next -- setTimeout is assigned synchronously when the race promise is built */
|
|
160
163
|
if (timeout !== void 0) clearTimeout(timeout);
|
|
161
164
|
}
|
|
162
165
|
}
|
|
163
166
|
async function dispatchPart() {
|
|
167
|
+
/* v8 ignore next -- callers guard on pendingBytes before dispatching the final part */
|
|
164
168
|
if (pending.length === 0) return;
|
|
165
169
|
await acquirePartSlot();
|
|
166
170
|
let data;
|
|
167
171
|
if (pending.length === 1) {
|
|
168
172
|
const head = pending[0];
|
|
173
|
+
/* v8 ignore next -- pending is never sparse; this narrows noUncheckedIndexedAccess */
|
|
169
174
|
if (!head) {
|
|
170
175
|
sem.release();
|
|
171
176
|
return;
|
|
@@ -222,11 +227,13 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
222
227
|
signal: abortScope.signal,
|
|
223
228
|
...options.retry !== void 0 ? { retry: options.retry } : {}
|
|
224
229
|
});
|
|
230
|
+
tracker.dispose();
|
|
225
231
|
abortScope.dispose();
|
|
226
232
|
resolveDone(result);
|
|
227
233
|
} catch (err) {
|
|
228
234
|
const closeError = toError(err);
|
|
229
235
|
if (errored === null) errored = closeError;
|
|
236
|
+
tracker.dispose();
|
|
230
237
|
abortScope.abort(errored);
|
|
231
238
|
const observedError = errored;
|
|
232
239
|
const fileIdToCancel = largeFileId;
|
|
@@ -260,6 +267,7 @@ function createWriteStream(raw, accountInfo, options) {
|
|
|
260
267
|
await waitForInflightPartsToSettle();
|
|
261
268
|
await cancelLargeFileBestEffort(raw, accountInfo, fileIdToCancel, cleanupWriteStreamOptions(options));
|
|
262
269
|
}
|
|
270
|
+
tracker.dispose();
|
|
263
271
|
abortScope.dispose();
|
|
264
272
|
rejectDone(abortError);
|
|
265
273
|
}
|
|
@@ -288,6 +296,7 @@ function carveExact(chunks, size) {
|
|
|
288
296
|
let written = 0;
|
|
289
297
|
while (written < size && chunks.length > 0) {
|
|
290
298
|
const head = chunks[0];
|
|
299
|
+
/* v8 ignore next -- chunks is never sparse; this narrows noUncheckedIndexedAccess */
|
|
291
300
|
if (!head) break;
|
|
292
301
|
const need = size - written;
|
|
293
302
|
if (head.byteLength <= need) {
|
|
@@ -303,6 +312,7 @@ function carveExact(chunks, size) {
|
|
|
303
312
|
return out;
|
|
304
313
|
}
|
|
305
314
|
function waitForAbort(signal) {
|
|
315
|
+
/* v8 ignore next -- callers check abort before entering the start/close wait race */
|
|
306
316
|
if (signal.aborted) return {
|
|
307
317
|
promise: Promise.resolve(abortReason(signal)),
|
|
308
318
|
dispose() {}
|
|
@@ -314,6 +324,7 @@ function waitForAbort(signal) {
|
|
|
314
324
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
315
325
|
}),
|
|
316
326
|
dispose() {
|
|
327
|
+
/* v8 ignore next -- listener is assigned synchronously with promise construction */
|
|
317
328
|
if (onAbort !== void 0) signal.removeEventListener("abort", onAbort);
|
|
318
329
|
}
|
|
319
330
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream.js","names":[],"sources":["../../src/upload/stream.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport type { ProgressListener } from '../streams/progress.ts'\nimport { ProgressTracker } from '../streams/progress.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId, LargeFileId } from '../types/ids.ts'\nimport { abortReason, raceWithAbort } from '../util/abort.ts'\nimport { DEFAULT_CONTENT_TYPE, DEFAULT_TRANSFER_CONCURRENCY } from '../util/defaults.ts'\nimport { toError } from '../util/to-error.ts'\nimport { createAbortScope } from './abort-scope.ts'\nimport {\n type CleanupFailureOptions,\n cancelLargeFileBestEffort,\n DEFAULT_CLEANUP_TIMEOUT_MS,\n resolveLargeFileErrorAfterCleanup,\n} from './cancel.ts'\nimport { Semaphore } from './concurrency.ts'\nimport { finishLargeFileWithAbortReconciliation } from './finish.ts'\nimport {\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n uploadPartWithFreshUrl,\n} from './retry.ts'\n\n/** Options for creating a streaming multipart upload sink. */\nexport interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFailureOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Destination file name in the bucket. */\n readonly fileName: string\n /** MIME type. Defaults to `b2/x-auto`. */\n readonly contentType?: string\n /** Custom file info stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption applied to each part. */\n readonly serverSideEncryption?: EncryptionSetting\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `src_last_modified_millis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /**\n * Target part size in bytes. The stream buffers writes until this many bytes\n * are accumulated, then ships a part. Must be at least the account's\n * absolute minimum part size; the implementation will raise it if too small.\n */\n readonly partSize?: number\n /** Maximum number of parts uploaded in parallel. Defaults to 4. */\n readonly concurrency?: number\n /** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */\n readonly onProgress?: ProgressListener\n /** Aborts the upload and cancels the unfinished large file. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Handle returned by `B2Object.createWriteStream`: the Web `WritableStream` to\n * pipe data into, plus a promise that resolves with the finished\n * {@link FileVersion} once the stream is closed and all parts have been\n * uploaded.\n */\nexport interface UploadWriteHandle {\n /** Web `WritableStream` sink to pipe data into. */\n readonly writable: WritableStream<Uint8Array>\n /** Resolves with the finalized file version when the stream closes successfully. */\n readonly done: Promise<FileVersion>\n}\n\n/**\n * Creates a {@link WritableStream} that streams data into a B2 multipart upload.\n *\n * Buffers incoming chunks until `partSize` bytes are accumulated, ships each\n * complete part through the standard multipart engine, and finalizes the file\n * once the stream is closed. Honours backpressure via the queue's bounded\n * concurrency. Streaming uploads do not support resume because the total size\n * and per-part hashes aren't known in advance; use {@link uploadLargeFile} with\n * a buffered source when resume is required.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, part URL pool).\n * @param options - Streaming upload parameters.\n *\n * @returns A {@link UploadWriteHandle} with the writable sink and a completion promise.\n */\nexport function createWriteStream(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: CreateWriteStreamOptions,\n): UploadWriteHandle {\n const minPartSize = accountInfo.getAbsoluteMinimumPartSize()\n const recommendedPartSize = accountInfo.getRecommendedPartSize()\n const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize)\n const concurrency = options.concurrency ?? DEFAULT_TRANSFER_CONCURRENCY\n const tracker = new ProgressTracker(options.onProgress, null, null)\n const sem = new Semaphore(concurrency)\n const abortScope = createAbortScope(options.signal)\n\n let largeFileId: LargeFileId | null = null\n let startPromise: Promise<LargeFileId> | null = null\n let cancelAfterStartScheduled = false\n let nextPartNumber = 1\n let pendingBytes = 0\n const pending: Uint8Array[] = []\n const partSha1s: string[] = []\n const inflight: Promise<void>[] = []\n let errored: Error | null = null\n\n // ES2024 `Promise.withResolvers()` exposes the resolve/reject pair as\n // properties of the returned object, avoiding the `let resolve!:` /\n // `let reject!:` non-null-assertion pattern needed before this API\n // existed. Available in Node 22 (our minimum), Bun, Deno, modern\n // browsers, and Cloudflare Workers.\n const {\n promise: done,\n resolve: resolveDone,\n reject: rejectDone,\n } = Promise.withResolvers<FileVersion>()\n // Attach a no-op rejection handler so a `done` that rejects before the\n // caller observes it never surfaces as a process-level unhandled rejection.\n // The error is not swallowed: `close()`/`abort()` also reject the writable\n // (so `pipeTo`/`getWriter().close()` throw), and any later `await done` /\n // `done.then(onRejected)` the caller attaches still sees the rejection —\n // extra handlers on the same promise all fire. Mirrors the\n // `task.catch(() => {})` pattern used for inflight part uploads below, and\n // keeps the engine well-behaved under Bun and Node's strict\n // unhandled-rejection mode.\n done.catch(() => {})\n\n function ensureStarted(): Promise<LargeFileId> {\n if (largeFileId !== null) return Promise.resolve(largeFileId)\n if (startPromise === null) {\n const rawStart = raw.startLargeFile(\n accountInfo.getApiUrl(),\n accountInfo.getAuthToken(),\n {\n bucketId: options.bucketId,\n fileName: options.fileName,\n contentType: options.contentType ?? DEFAULT_CONTENT_TYPE,\n fileInfo: options.fileInfo ?? {},\n ...(options.customUploadTimestamp !== undefined\n ? { customUploadTimestamp: String(options.customUploadTimestamp) }\n : {}),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n },\n {\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n },\n )\n startPromise = rawStart.then((resp) => {\n largeFileId = resp.fileId\n if (abortScope.signal.aborted || errored !== null) {\n cancelStartedLargeFile(largeFileId)\n }\n return largeFileId\n })\n }\n const started = startPromise\n return raceWithAbort(started, abortScope.signal).catch((err) => {\n if (abortScope.signal.aborted) scheduleCancelLargeFileAfterStart(started)\n throw err\n })\n }\n\n async function shipPart(data: Uint8Array, partNumber: number): Promise<void> {\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n const fileId = await ensureStarted()\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n abortScope.signal.throwIfAborted()\n\n const result = await uploadPartWithFreshUrl(raw, accountInfo, fileId, {\n fileName: options.fileName,\n partNumber,\n data: data as BodyInit,\n contentLength: data.byteLength,\n contentSha1: sha1Hex,\n retry: options.retry,\n signal: abortScope.signal,\n onUploadRetry: options.onUploadRetry,\n retryResponseBodyFailures: resolveRetryResponseBodyFailures(\n options.retryResponseBodyFailures,\n ),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n })\n partSha1s[partNumber - 1] = result.contentSha1\n tracker.addBytes(data.byteLength)\n tracker.completePart()\n }\n\n function markErrored(err: unknown): Error {\n const error = toError(err)\n errored = error\n abortScope.abort(error)\n return error\n }\n\n function cancelStartedLargeFile(fileId: LargeFileId): void {\n if (cancelAfterStartScheduled) return\n cancelAfterStartScheduled = true\n void cancelLargeFileBestEffort(raw, accountInfo, fileId, cleanupWriteStreamOptions(options))\n }\n\n function scheduleCancelLargeFileAfterStart(started: Promise<LargeFileId>): void {\n void started\n .then((fileId) => cancelStartedLargeFile(fileId))\n .catch(() => {\n // If start failed, no file ID is available to cancel.\n })\n }\n\n async function settleInflightForClose(): Promise<PromiseSettledResult<void>[]> {\n const settled = Promise.allSettled(inflight)\n if (startPromise === null || largeFileId !== null) return await settled\n\n const abortWaiter = waitForAbort(abortScope.signal)\n try {\n const first = await Promise.race([\n settled.then(() => 'settled' as const),\n startPromise.then(\n () => 'start-settled' as const,\n () => 'start-settled' as const,\n ),\n abortWaiter.promise.then(() => 'aborted' as const),\n ])\n if (first === 'aborted' && largeFileId === null) {\n throw abortReason(abortScope.signal)\n }\n return await settled\n } finally {\n abortWaiter.dispose()\n }\n }\n\n function startPartWithAcquiredSlot(data: Uint8Array, partNumber: number): void {\n const task = (async () => {\n try {\n await shipPart(data, partNumber)\n } catch (err) {\n markErrored(err)\n throw err\n } finally {\n sem.release()\n }\n })()\n inflight.push(task)\n // Swallow rejection here; we check `errored` later.\n task.catch(() => {})\n }\n\n async function acquirePartSlot(): Promise<void> {\n await sem.acquire()\n if (errored !== null) {\n sem.release()\n throw errored\n }\n try {\n abortScope.signal.throwIfAborted()\n } catch (err) {\n sem.release()\n throw err\n }\n }\n\n async function waitForInflightPartsToSettle(\n timeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS,\n ): Promise<void> {\n if (inflight.length === 0) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.allSettled(inflight).then(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs)\n }),\n ])\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async function dispatchPart(): Promise<void> {\n if (pending.length === 0) return\n await acquirePartSlot()\n let data: Uint8Array\n if (pending.length === 1) {\n const head = pending[0]\n if (!head) {\n sem.release()\n return\n }\n data = head\n } else {\n const total = pending.reduce((sum, chunk) => sum + chunk.byteLength, 0)\n data = new Uint8Array(total)\n let offset = 0\n for (const chunk of pending) {\n data.set(chunk, offset)\n offset += chunk.byteLength\n }\n }\n pending.length = 0\n pendingBytes = 0\n const partNumber = nextPartNumber++\n startPartWithAcquiredSlot(data, partNumber)\n }\n\n const writable = new WritableStream<Uint8Array>({\n async write(chunk: Uint8Array): Promise<void> {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n if (chunk.byteLength === 0) return\n\n pending.push(chunk)\n pendingBytes += chunk.byteLength\n while (pendingBytes >= partSize) {\n await acquirePartSlot()\n if (errored) {\n sem.release()\n throw errored\n }\n // Pull exactly partSize bytes off the front\n const carved = carveExact(pending, partSize)\n const partNumber = nextPartNumber++\n pendingBytes -= partSize\n startPartWithAcquiredSlot(carved, partNumber)\n }\n },\n\n async close(): Promise<void> {\n try {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n\n // Ship any remaining bytes as the last part. If the total fit in one\n // single buffered batch (no parts shipped yet), we have to use the\n // multipart path anyway since we already called startLargeFile lazily.\n if (pendingBytes > 0) {\n await dispatchPart()\n }\n\n const settled = await settleInflightForClose()\n const rejected = settled.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (rejected !== undefined && errored === null) {\n markErrored(rejected.reason)\n }\n if (errored) throw errored\n\n if (largeFileId === null) {\n // Stream closed before any data was written. Start an empty large\n // file? B2 requires at least 2 parts. Reject — callers shouldn't\n // close an empty stream.\n throw new Error('createWriteStream closed without any data written.')\n }\n\n const result = await finishLargeFileWithAbortReconciliation(raw, accountInfo, {\n fileId: largeFileId,\n bucketId: options.bucketId,\n fileName: options.fileName,\n partSha1s,\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n })\n abortScope.dispose()\n resolveDone(result)\n } catch (err) {\n const closeError = toError(err)\n if (errored === null) errored = closeError\n abortScope.abort(errored)\n const observedError = errored\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Mirror writer.abort(): close() must not wait for non-abortable\n // b2_start_large_file. If a file ID arrives later, cancel it in the\n // background.\n scheduleCancelLargeFileAfterStart(startPromise)\n abortScope.dispose()\n rejectDone(observedError)\n throw observedError\n }\n await Promise.allSettled(inflight)\n // Capture into a const so the cancel closure sees a non-null\n // `fileId`; closures don't observe the outer `!== null` narrowing\n // because the variable is mutable across the lambda boundary.\n let finalError: unknown = observedError\n if (fileIdToCancel !== null) {\n finalError = await resolveLargeFileErrorAfterCleanup(observedError, raw, accountInfo, {\n fileId: fileIdToCancel,\n bucketId: options.bucketId,\n fileName: options.fileName,\n signal: options.signal,\n onCleanupFailure: options.onCleanupFailure,\n })\n }\n abortScope.dispose()\n rejectDone(finalError)\n throw finalError\n }\n },\n\n async abort(reason: unknown): Promise<void> {\n const abortError = markErrored(reason)\n pending.length = 0\n pendingBytes = 0\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Do not await an in-flight start request here. A stalled\n // b2_start_large_file must not make writer.abort() hang; if it later\n // returns a file ID, cancel it best-effort in the background.\n scheduleCancelLargeFileAfterStart(startPromise)\n }\n if (fileIdToCancel !== null) {\n await waitForInflightPartsToSettle()\n await cancelLargeFileBestEffort(\n raw,\n accountInfo,\n fileIdToCancel,\n cleanupWriteStreamOptions(options),\n )\n }\n abortScope.dispose()\n rejectDone(abortError)\n },\n })\n\n return { writable, done }\n}\n\nfunction cleanupWriteStreamOptions(options: CreateWriteStreamOptions): {\n readonly signal?: AbortSignal\n} & CleanupFailureOptions {\n return {\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onCleanupFailure !== undefined\n ? { onCleanupFailure: options.onCleanupFailure }\n : {}),\n }\n}\n\n/**\n * Removes exactly `size` bytes from the front of `chunks` (mutates) and returns\n * them as a contiguous Uint8Array. Any trailing remainder of the last chunk\n * stays at the front of `chunks` for the next part.\n *\n * @param chunks - Queue of pending chunks. Modified in place.\n * @param size - Number of bytes to carve off the front.\n *\n * @returns A new Uint8Array containing exactly `size` bytes.\n */\nfunction carveExact(chunks: Uint8Array[], size: number): Uint8Array {\n const out = new Uint8Array(size)\n let written = 0\n while (written < size && chunks.length > 0) {\n const head = chunks[0]\n if (!head) break\n const need = size - written\n if (head.byteLength <= need) {\n out.set(head, written)\n written += head.byteLength\n chunks.shift()\n } else {\n out.set(head.subarray(0, need), written)\n chunks[0] = head.subarray(need)\n written += need\n }\n }\n return out\n}\n\nfunction waitForAbort(signal: AbortSignal): {\n readonly promise: Promise<unknown>\n dispose(): void\n} {\n if (signal.aborted) {\n return {\n promise: Promise.resolve(abortReason(signal)),\n dispose() {},\n }\n }\n\n let onAbort: (() => void) | undefined\n const promise = new Promise<unknown>((resolve) => {\n onAbort = () => resolve(abortReason(signal))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n\n return {\n promise,\n dispose() {\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAuFA,SAAgB,kBACd,KACA,aACA,SACmB;CACnB,MAAM,cAAc,YAAY,2BAA2B;CAC3D,MAAM,sBAAsB,YAAY,uBAAuB;CAC/D,MAAM,WAAW,KAAK,IAAI,QAAQ,YAAY,qBAAqB,WAAW;CAC9E,MAAM,cAAc,QAAQ,eAAA;CAC5B,MAAM,UAAU,IAAI,gBAAgB,Q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AI,CAAC,MAAM;EACX,MAAM,OAAO,OAAO;EACpB,IAAI,KAAK,cAAc,MAAM;GAC3B,IAAI,IAAI,MAAM,OAAO;GACrB,WAAW,KAAK;GAChB,OAAO,MAAM;EACf,OAAO;GACL,IAAI,IAAI,KAAK,SAAS,GAAG,IAAI,GAAG,OAAO;GACvC,OAAO,KAAK,KAAK,SAAS,IAAI;GAC9B,WAAW;EACb;CACF;CACA,OAAO;AACT;AAEA,SAAS,aAAa,QAGpB;CACA,IAAI,OAAO,SACT,OAAO;EACL,SAAS,QAAQ,QAAQ,YAAY,MAAM,CAAC;EAC5C,UAAU,CAAC;CACb;CAGF,IAAI;CAMJ,OAAO;EACL,SAAA,IANkB,SAAkB,YAAY;GAChD,gBAAgB,QAAQ,YAAY,MAAM,CAAC;GAC3C,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EAC1D,CAGE;EACA,UAAU;GACR,IAAI,YAAY,KAAA,GAAW,OAAO,oBAAoB,SAAS,OAAO;EACxE;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"stream.js","names":[],"sources":["../../src/upload/stream.ts"],"sourcesContent":["import type { AccountInfo } from '../auth/account-info.ts'\nimport type { RawClient } from '../raw/index.ts'\nimport { IncrementalSha1 } from '../streams/hash.ts'\nimport type { ProgressListener } from '../streams/progress.ts'\nimport { ProgressTracker } from '../streams/progress.ts'\nimport type { EncryptionSetting } from '../types/encryption.ts'\nimport type { FileVersion } from '../types/file.ts'\nimport type { BucketId, LargeFileId } from '../types/ids.ts'\nimport { abortReason, raceWithAbort } from '../util/abort.ts'\nimport { DEFAULT_CONTENT_TYPE, DEFAULT_TRANSFER_CONCURRENCY } from '../util/defaults.ts'\nimport { toError } from '../util/to-error.ts'\nimport { createAbortScope } from './abort-scope.ts'\nimport {\n type CleanupFailureOptions,\n cancelLargeFileBestEffort,\n DEFAULT_CLEANUP_TIMEOUT_MS,\n resolveLargeFileErrorAfterCleanup,\n} from './cancel.ts'\nimport { Semaphore } from './concurrency.ts'\nimport { finishLargeFileWithAbortReconciliation } from './finish.ts'\nimport {\n resolveRetryResponseBodyFailures,\n type UploadRetryOptions,\n uploadPartWithFreshUrl,\n} from './retry.ts'\n\n/** Options for creating a streaming multipart upload sink. */\nexport interface CreateWriteStreamOptions extends UploadRetryOptions, CleanupFailureOptions {\n /** Target bucket for the upload. */\n readonly bucketId: BucketId\n /** Destination file name in the bucket. */\n readonly fileName: string\n /** MIME type. Defaults to `b2/x-auto`. */\n readonly contentType?: string\n /** Custom file info stored with the file. */\n readonly fileInfo?: Record<string, string>\n /** Server-side encryption applied to each part. */\n readonly serverSideEncryption?: EncryptionSetting\n /**\n * B2 upload timestamp override in milliseconds since epoch.\n * Sets the file version `uploadTimestamp`; distinct from `src_last_modified_millis` metadata.\n * Requires B2 account enablement for Custom Upload Timestamp.\n */\n readonly customUploadTimestamp?: number\n /**\n * Target part size in bytes. The stream buffers writes until this many bytes\n * are accumulated, then ships a part. Must be at least the account's\n * absolute minimum part size; the implementation will raise it if too small.\n */\n readonly partSize?: number\n /** Maximum number of parts uploaded in parallel. Defaults to 4. */\n readonly concurrency?: number\n /** Callback invoked with upload progress events. `totalBytes` is `null` (size unknown). */\n readonly onProgress?: ProgressListener\n /**\n * Minimum milliseconds between byte-only progress callbacks. Defaults to\n * the SDK's 100 ms progress interval; set to 0 for per-chunk callbacks.\n * Part-completion progress callbacks are always emitted immediately.\n */\n readonly progressIntervalMillis?: number\n /** Aborts the upload and cancels the unfinished large file. */\n readonly signal?: AbortSignal\n}\n\n/**\n * Handle returned by `B2Object.createWriteStream`: the Web `WritableStream` to\n * pipe data into, plus a promise that resolves with the finished\n * {@link FileVersion} once the stream is closed and all parts have been\n * uploaded.\n */\nexport interface UploadWriteHandle {\n /** Web `WritableStream` sink to pipe data into. */\n readonly writable: WritableStream<Uint8Array>\n /** Resolves with the finalized file version when the stream closes successfully. */\n readonly done: Promise<FileVersion>\n}\n\n/**\n * Creates a {@link WritableStream} that streams data into a B2 multipart upload.\n *\n * Buffers incoming chunks until `partSize` bytes are accumulated, ships each\n * complete part through the standard multipart engine, and finalizes the file\n * once the stream is closed. Honours backpressure via the queue's bounded\n * concurrency. Streaming uploads do not support resume because the total size\n * and per-part hashes aren't known in advance; use {@link uploadLargeFile} with\n * a buffered source when resume is required.\n *\n * @param raw - Low-level B2 API client.\n * @param accountInfo - Authorized account state (tokens, URLs, part URL pool).\n * @param options - Streaming upload parameters.\n *\n * @returns A {@link UploadWriteHandle} with the writable sink and a completion promise.\n */\nexport function createWriteStream(\n raw: RawClient,\n accountInfo: AccountInfo,\n options: CreateWriteStreamOptions,\n): UploadWriteHandle {\n const minPartSize = accountInfo.getAbsoluteMinimumPartSize()\n const recommendedPartSize = accountInfo.getRecommendedPartSize()\n const partSize = Math.max(options.partSize ?? recommendedPartSize, minPartSize)\n const concurrency = options.concurrency ?? DEFAULT_TRANSFER_CONCURRENCY\n const tracker = new ProgressTracker(options.onProgress, null, null, {\n ...(options.progressIntervalMillis !== undefined\n ? { minIntervalMs: options.progressIntervalMillis }\n : {}),\n })\n const sem = new Semaphore(concurrency)\n const abortScope = createAbortScope(options.signal)\n\n let largeFileId: LargeFileId | null = null\n let startPromise: Promise<LargeFileId> | null = null\n let cancelAfterStartScheduled = false\n let nextPartNumber = 1\n let pendingBytes = 0\n const pending: Uint8Array[] = []\n const partSha1s: string[] = []\n const inflight: Promise<void>[] = []\n let errored: Error | null = null\n\n // ES2024 `Promise.withResolvers()` exposes the resolve/reject pair as\n // properties of the returned object, avoiding the `let resolve!:` /\n // `let reject!:` non-null-assertion pattern needed before this API\n // existed. Available in Node 22 (our minimum), Bun, Deno, modern\n // browsers, and Cloudflare Workers.\n const {\n promise: done,\n resolve: resolveDone,\n reject: rejectDone,\n } = Promise.withResolvers<FileVersion>()\n // Attach a no-op rejection handler so a `done` that rejects before the\n // caller observes it never surfaces as a process-level unhandled rejection.\n // The error is not swallowed: `close()`/`abort()` also reject the writable\n // (so `pipeTo`/`getWriter().close()` throw), and any later `await done` /\n // `done.then(onRejected)` the caller attaches still sees the rejection —\n // extra handlers on the same promise all fire. Mirrors the\n // `task.catch(() => {})` pattern used for inflight part uploads below, and\n // keeps the engine well-behaved under Bun and Node's strict\n // unhandled-rejection mode.\n done.catch(() => {})\n\n function ensureStarted(): Promise<LargeFileId> {\n if (largeFileId !== null) return Promise.resolve(largeFileId)\n if (startPromise === null) {\n const rawStart = raw.startLargeFile(\n accountInfo.getApiUrl(),\n accountInfo.getAuthToken(),\n {\n bucketId: options.bucketId,\n fileName: options.fileName,\n contentType: options.contentType ?? DEFAULT_CONTENT_TYPE,\n fileInfo: options.fileInfo ?? {},\n ...(options.customUploadTimestamp !== undefined\n ? { customUploadTimestamp: String(options.customUploadTimestamp) }\n : {}),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n },\n {\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n },\n )\n startPromise = rawStart.then((resp) => {\n largeFileId = resp.fileId\n if (abortScope.signal.aborted || errored !== null) {\n cancelStartedLargeFile(largeFileId)\n }\n return largeFileId\n })\n }\n const started = startPromise\n return raceWithAbort(started, abortScope.signal).catch((err) => {\n if (abortScope.signal.aborted) scheduleCancelLargeFileAfterStart(started)\n throw err\n })\n }\n\n async function shipPart(data: Uint8Array, partNumber: number): Promise<void> {\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n const fileId = await ensureStarted()\n if (errored !== null) throw errored\n abortScope.signal.throwIfAborted()\n\n const sha1 = new IncrementalSha1()\n await sha1.update(data)\n const sha1Hex = await sha1.digest()\n abortScope.signal.throwIfAborted()\n\n const result = await uploadPartWithFreshUrl(raw, accountInfo, fileId, {\n fileName: options.fileName,\n partNumber,\n data: data as BodyInit,\n contentLength: data.byteLength,\n contentSha1: sha1Hex,\n retry: options.retry,\n signal: abortScope.signal,\n onUploadRetry: options.onUploadRetry,\n retryResponseBodyFailures: resolveRetryResponseBodyFailures(\n options.retryResponseBodyFailures,\n ),\n ...(options.serverSideEncryption !== undefined\n ? { serverSideEncryption: options.serverSideEncryption }\n : {}),\n })\n partSha1s[partNumber - 1] = result.contentSha1\n tracker.addBytes(data.byteLength)\n tracker.completePart()\n }\n\n function markErrored(err: unknown): Error {\n const error = toError(err)\n errored = error\n tracker.dispose()\n abortScope.abort(error)\n return error\n }\n\n function cancelStartedLargeFile(fileId: LargeFileId): void {\n if (cancelAfterStartScheduled) return\n cancelAfterStartScheduled = true\n void cancelLargeFileBestEffort(raw, accountInfo, fileId, cleanupWriteStreamOptions(options))\n }\n\n function scheduleCancelLargeFileAfterStart(started: Promise<LargeFileId>): void {\n void started\n .then((fileId) => cancelStartedLargeFile(fileId))\n .catch(() => {\n // If start failed, no file ID is available to cancel.\n })\n }\n\n async function settleInflightForClose(): Promise<PromiseSettledResult<void>[]> {\n const settled = Promise.allSettled(inflight)\n if (startPromise === null || largeFileId !== null) return await settled\n\n const abortWaiter = waitForAbort(abortScope.signal)\n try {\n const first = await Promise.race([\n settled.then(() => 'settled' as const),\n startPromise.then(\n () => 'start-settled' as const,\n () => 'start-settled' as const,\n ),\n abortWaiter.promise.then(() => 'aborted' as const),\n ])\n if (first === 'aborted' && largeFileId === null) {\n throw abortReason(abortScope.signal)\n }\n return await settled\n } finally {\n abortWaiter.dispose()\n }\n }\n\n function startPartWithAcquiredSlot(data: Uint8Array, partNumber: number): void {\n const task = (async () => {\n try {\n await shipPart(data, partNumber)\n } catch (err) {\n markErrored(err)\n throw err\n } finally {\n sem.release()\n }\n })()\n inflight.push(task)\n // Swallow rejection here; we check `errored` later.\n task.catch(() => {})\n }\n\n async function acquirePartSlot(): Promise<void> {\n await sem.acquire()\n if (errored !== null) {\n sem.release()\n throw errored\n }\n try {\n abortScope.signal.throwIfAborted()\n } catch (err) {\n sem.release()\n throw err\n }\n }\n\n async function waitForInflightPartsToSettle(\n timeoutMs = DEFAULT_CLEANUP_TIMEOUT_MS,\n ): Promise<void> {\n /* v8 ignore next -- only called after a large file exists, which requires at least one part */\n if (inflight.length === 0) return\n let timeout: ReturnType<typeof setTimeout> | undefined\n try {\n await Promise.race([\n Promise.allSettled(inflight).then(() => undefined),\n new Promise<void>((resolve) => {\n timeout = setTimeout(resolve, timeoutMs)\n }),\n ])\n } finally {\n /* v8 ignore next -- setTimeout is assigned synchronously when the race promise is built */\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async function dispatchPart(): Promise<void> {\n /* v8 ignore next -- callers guard on pendingBytes before dispatching the final part */\n if (pending.length === 0) return\n await acquirePartSlot()\n let data: Uint8Array\n if (pending.length === 1) {\n const head = pending[0]\n /* v8 ignore next -- pending is never sparse; this narrows noUncheckedIndexedAccess */\n if (!head) {\n sem.release()\n return\n }\n data = head\n } else {\n const total = pending.reduce((sum, chunk) => sum + chunk.byteLength, 0)\n data = new Uint8Array(total)\n let offset = 0\n for (const chunk of pending) {\n data.set(chunk, offset)\n offset += chunk.byteLength\n }\n }\n pending.length = 0\n pendingBytes = 0\n const partNumber = nextPartNumber++\n startPartWithAcquiredSlot(data, partNumber)\n }\n\n const writable = new WritableStream<Uint8Array>({\n async write(chunk: Uint8Array): Promise<void> {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n if (chunk.byteLength === 0) return\n\n pending.push(chunk)\n pendingBytes += chunk.byteLength\n while (pendingBytes >= partSize) {\n await acquirePartSlot()\n if (errored) {\n sem.release()\n throw errored\n }\n // Pull exactly partSize bytes off the front\n const carved = carveExact(pending, partSize)\n const partNumber = nextPartNumber++\n pendingBytes -= partSize\n startPartWithAcquiredSlot(carved, partNumber)\n }\n },\n\n async close(): Promise<void> {\n try {\n if (errored) throw errored\n abortScope.signal.throwIfAborted()\n\n // Ship any remaining bytes as the last part. If the total fit in one\n // single buffered batch (no parts shipped yet), we have to use the\n // multipart path anyway since we already called startLargeFile lazily.\n if (pendingBytes > 0) {\n await dispatchPart()\n }\n\n const settled = await settleInflightForClose()\n const rejected = settled.find(\n (result): result is PromiseRejectedResult => result.status === 'rejected',\n )\n if (rejected !== undefined && errored === null) {\n markErrored(rejected.reason)\n }\n if (errored) throw errored\n\n if (largeFileId === null) {\n // Stream closed before any data was written. Start an empty large\n // file? B2 requires at least 2 parts. Reject — callers shouldn't\n // close an empty stream.\n throw new Error('createWriteStream closed without any data written.')\n }\n\n const result = await finishLargeFileWithAbortReconciliation(raw, accountInfo, {\n fileId: largeFileId,\n bucketId: options.bucketId,\n fileName: options.fileName,\n partSha1s,\n signal: abortScope.signal,\n ...(options.retry !== undefined ? { retry: options.retry } : {}),\n })\n tracker.dispose()\n abortScope.dispose()\n resolveDone(result)\n } catch (err) {\n const closeError = toError(err)\n if (errored === null) errored = closeError\n tracker.dispose()\n abortScope.abort(errored)\n const observedError = errored\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Mirror writer.abort(): close() must not wait for non-abortable\n // b2_start_large_file. If a file ID arrives later, cancel it in the\n // background.\n scheduleCancelLargeFileAfterStart(startPromise)\n abortScope.dispose()\n rejectDone(observedError)\n throw observedError\n }\n await Promise.allSettled(inflight)\n // Capture into a const so the cancel closure sees a non-null\n // `fileId`; closures don't observe the outer `!== null` narrowing\n // because the variable is mutable across the lambda boundary.\n let finalError: unknown = observedError\n if (fileIdToCancel !== null) {\n finalError = await resolveLargeFileErrorAfterCleanup(observedError, raw, accountInfo, {\n fileId: fileIdToCancel,\n bucketId: options.bucketId,\n fileName: options.fileName,\n signal: options.signal,\n onCleanupFailure: options.onCleanupFailure,\n })\n }\n abortScope.dispose()\n rejectDone(finalError)\n throw finalError\n }\n },\n\n async abort(reason: unknown): Promise<void> {\n const abortError = markErrored(reason)\n pending.length = 0\n pendingBytes = 0\n const fileIdToCancel = largeFileId\n if (fileIdToCancel === null && startPromise !== null) {\n // Do not await an in-flight start request here. A stalled\n // b2_start_large_file must not make writer.abort() hang; if it later\n // returns a file ID, cancel it best-effort in the background.\n scheduleCancelLargeFileAfterStart(startPromise)\n }\n if (fileIdToCancel !== null) {\n await waitForInflightPartsToSettle()\n await cancelLargeFileBestEffort(\n raw,\n accountInfo,\n fileIdToCancel,\n cleanupWriteStreamOptions(options),\n )\n }\n tracker.dispose()\n abortScope.dispose()\n rejectDone(abortError)\n },\n })\n\n return { writable, done }\n}\n\nfunction cleanupWriteStreamOptions(options: CreateWriteStreamOptions): {\n readonly signal?: AbortSignal\n} & CleanupFailureOptions {\n return {\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onCleanupFailure !== undefined\n ? { onCleanupFailure: options.onCleanupFailure }\n : {}),\n }\n}\n\n/**\n * Removes exactly `size` bytes from the front of `chunks` (mutates) and returns\n * them as a contiguous Uint8Array. Any trailing remainder of the last chunk\n * stays at the front of `chunks` for the next part.\n *\n * @param chunks - Queue of pending chunks. Modified in place.\n * @param size - Number of bytes to carve off the front.\n *\n * @returns A new Uint8Array containing exactly `size` bytes.\n */\nfunction carveExact(chunks: Uint8Array[], size: number): Uint8Array {\n const out = new Uint8Array(size)\n let written = 0\n while (written < size && chunks.length > 0) {\n const head = chunks[0]\n /* v8 ignore next -- chunks is never sparse; this narrows noUncheckedIndexedAccess */\n if (!head) break\n const need = size - written\n if (head.byteLength <= need) {\n out.set(head, written)\n written += head.byteLength\n chunks.shift()\n } else {\n out.set(head.subarray(0, need), written)\n chunks[0] = head.subarray(need)\n written += need\n }\n }\n return out\n}\n\nfunction waitForAbort(signal: AbortSignal): {\n readonly promise: Promise<unknown>\n dispose(): void\n} {\n /* v8 ignore next -- callers check abort before entering the start/close wait race */\n if (signal.aborted) {\n return {\n promise: Promise.resolve(abortReason(signal)),\n dispose() {},\n }\n }\n\n let onAbort: (() => void) | undefined\n const promise = new Promise<unknown>((resolve) => {\n onAbort = () => resolve(abortReason(signal))\n signal.addEventListener('abort', onAbort, { once: true })\n })\n\n return {\n promise,\n dispose() {\n /* v8 ignore next -- listener is assigned synchronously with promise construction */\n if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)\n },\n }\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