@edgestore/server 1.0.0-next.4 → 1.0.0-rc.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +2 -8
  2. package/agent-docs/README.md +1 -1
  3. package/agent-docs/astro.md +3 -9
  4. package/agent-docs/backend-client.md +16 -29
  5. package/agent-docs/configuration.md +41 -10
  6. package/agent-docs/express.md +3 -9
  7. package/agent-docs/fastify.md +3 -9
  8. package/agent-docs/hono.md +3 -9
  9. package/agent-docs/next.md +5 -17
  10. package/agent-docs/provider-azure-blob.md +150 -59
  11. package/agent-docs/provider-custom.md +42 -13
  12. package/agent-docs/provider-edgestore.md +9 -9
  13. package/agent-docs/provider-s3.md +224 -119
  14. package/agent-docs/remix.md +3 -9
  15. package/agent-docs/tanstack-start.md +3 -9
  16. package/dist/adapters/astro/index.d.ts +2 -2
  17. package/dist/adapters/astro/index.d.ts.map +1 -1
  18. package/dist/adapters/astro/index.js +1 -2
  19. package/dist/adapters/dispatcher.d.ts +2 -3
  20. package/dist/adapters/dispatcher.d.ts.map +1 -1
  21. package/dist/adapters/dispatcher.js +17 -22
  22. package/dist/adapters/express/index.d.ts +2 -2
  23. package/dist/adapters/express/index.d.ts.map +1 -1
  24. package/dist/adapters/express/index.js +1 -5
  25. package/dist/adapters/fastify/index.d.ts +2 -2
  26. package/dist/adapters/fastify/index.d.ts.map +1 -1
  27. package/dist/adapters/fastify/index.js +1 -5
  28. package/dist/adapters/hono/index.d.ts +2 -2
  29. package/dist/adapters/hono/index.d.ts.map +1 -1
  30. package/dist/adapters/hono/index.js +1 -2
  31. package/dist/adapters/next/app/index.d.ts +2 -2
  32. package/dist/adapters/next/app/index.d.ts.map +1 -1
  33. package/dist/adapters/next/app/index.js +1 -2
  34. package/dist/adapters/next/pages/index.d.ts +2 -2
  35. package/dist/adapters/next/pages/index.d.ts.map +1 -1
  36. package/dist/adapters/next/pages/index.js +1 -5
  37. package/dist/adapters/remix/index.d.ts +2 -2
  38. package/dist/adapters/remix/index.d.ts.map +1 -1
  39. package/dist/adapters/remix/index.js +1 -2
  40. package/dist/adapters/shared.d.ts +31 -143
  41. package/dist/adapters/shared.d.ts.map +1 -1
  42. package/dist/adapters/shared.js +115 -197
  43. package/dist/adapters/start/index.d.ts +2 -2
  44. package/dist/adapters/start/index.d.ts.map +1 -1
  45. package/dist/adapters/start/index.js +1 -2
  46. package/dist/core/client/bucketClient.d.ts +0 -1
  47. package/dist/core/client/bucketClient.d.ts.map +1 -1
  48. package/dist/core/client/bucketClient.js +6 -28
  49. package/dist/core/client/index.d.ts +25 -26
  50. package/dist/core/client/index.d.ts.map +1 -1
  51. package/dist/core/client/index.js +2 -3
  52. package/dist/core/provider.d.ts +11 -2
  53. package/dist/core/provider.d.ts.map +1 -1
  54. package/dist/core/provider.js +20 -3
  55. package/dist/core/router.d.ts +25 -0
  56. package/dist/core/router.d.ts.map +1 -0
  57. package/dist/core/router.js +49 -0
  58. package/dist/core/routerRules.d.ts +1 -1
  59. package/dist/index.d.ts +4 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +3 -3
  62. package/dist/providers/azure-blob/blocks.d.ts +48 -0
  63. package/dist/providers/azure-blob/blocks.d.ts.map +1 -0
  64. package/dist/providers/azure-blob/blocks.js +126 -0
  65. package/dist/providers/azure-blob/index.d.ts +81 -49
  66. package/dist/providers/azure-blob/index.d.ts.map +1 -1
  67. package/dist/providers/azure-blob/index.js +194 -105
  68. package/dist/providers/edgestore/index.d.ts +12 -32
  69. package/dist/providers/edgestore/index.d.ts.map +1 -1
  70. package/dist/providers/edgestore/index.js +34 -31
  71. package/dist/providers/s3/backendUpload.d.ts +10 -0
  72. package/dist/providers/s3/backendUpload.d.ts.map +1 -0
  73. package/dist/providers/s3/backendUpload.js +59 -0
  74. package/dist/providers/s3/index.d.ts +52 -97
  75. package/dist/providers/s3/index.d.ts.map +1 -1
  76. package/dist/providers/s3/index.js +221 -91
  77. package/dist/providers/s3/multipart.d.ts +23 -0
  78. package/dist/providers/s3/multipart.d.ts.map +1 -0
  79. package/dist/providers/s3/multipart.js +96 -0
  80. package/dist/providers/s3/objectHeaders.d.ts +4 -0
  81. package/dist/providers/s3/objectHeaders.d.ts.map +1 -0
  82. package/dist/providers/s3/objectHeaders.js +22 -0
  83. package/dist/providers/s3/options.d.ts +85 -0
  84. package/dist/providers/s3/options.d.ts.map +1 -0
  85. package/dist/providers/storage/multipartSession.d.ts +51 -0
  86. package/dist/providers/storage/multipartSession.d.ts.map +1 -0
  87. package/dist/providers/storage/multipartSession.js +83 -0
  88. package/dist/providers/storage/objectKeys.d.ts +41 -0
  89. package/dist/providers/storage/objectKeys.d.ts.map +1 -0
  90. package/dist/providers/storage/objectKeys.js +67 -0
  91. package/dist/providers/storage/transfer.d.ts +18 -0
  92. package/dist/providers/storage/transfer.d.ts.map +1 -0
  93. package/dist/providers/storage/transfer.js +69 -0
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.d.ts.map +1 -1
  96. package/package.json +5 -12
  97. package/src/adapters/astro/index.ts +3 -4
  98. package/src/adapters/dispatcher.ts +21 -30
  99. package/src/adapters/express/index.ts +3 -9
  100. package/src/adapters/fastify/index.ts +3 -9
  101. package/src/adapters/hono/index.ts +3 -4
  102. package/src/adapters/next/app/index.ts +3 -4
  103. package/src/adapters/next/pages/index.ts +3 -9
  104. package/src/adapters/remix/index.ts +3 -4
  105. package/src/adapters/shared.ts +166 -285
  106. package/src/adapters/start/index.ts +3 -4
  107. package/src/core/client/bucketClient.ts +10 -41
  108. package/src/core/client/index.ts +29 -49
  109. package/src/core/provider.ts +25 -10
  110. package/src/core/router.ts +97 -0
  111. package/src/index.ts +4 -11
  112. package/src/providers/azure-blob/blocks.ts +201 -0
  113. package/src/providers/azure-blob/index.ts +290 -170
  114. package/src/providers/edgestore/index.ts +38 -35
  115. package/src/providers/s3/backendUpload.ts +82 -0
  116. package/src/providers/s3/index.ts +279 -227
  117. package/src/providers/s3/multipart.ts +138 -0
  118. package/src/providers/s3/objectHeaders.ts +23 -0
  119. package/src/providers/s3/options.ts +102 -0
  120. package/src/providers/storage/multipartSession.ts +145 -0
  121. package/src/providers/storage/objectKeys.ts +106 -0
  122. package/src/providers/storage/transfer.ts +105 -0
  123. package/src/version.ts +1 -1
  124. package/core/index.d.ts +0 -1
  125. package/core/index.js +0 -1
  126. package/dist/core/index.d.ts +0 -22
  127. package/dist/core/index.d.ts.map +0 -1
  128. package/dist/core/index.js +0 -14
  129. package/src/core/index.ts +0 -43
@@ -1,287 +1,339 @@
1
1
  import {
2
- DeleteObjectCommand,
2
+ DeleteObjectsCommand,
3
+ GetObjectCommand,
3
4
  HeadObjectCommand,
4
5
  PutObjectCommand,
5
6
  S3Client,
6
- type S3ClientConfig,
7
+ type PutObjectCommandInput,
7
8
  } from '@aws-sdk/client-s3';
8
9
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
9
- import { type MaybePromise, type RequestUploadParams } from '@edgestore/shared';
10
+ import { planMultipartUpload } from '@edgestore/sdk';
11
+ import {
12
+ type RequestUploadParams,
13
+ type RequestUploadRes,
14
+ } from '@edgestore/shared';
10
15
  import { z } from 'zod';
11
16
  import { defineProvider } from '../../core/provider';
12
17
  import { getEnv } from '../../libs/env';
18
+ import { createMultipartSessions } from '../storage/multipartSession';
19
+ import { createObjectKeys } from '../storage/objectKeys';
20
+ import {
21
+ assertSignedUrlAccessControl,
22
+ signedUrlLifetime,
23
+ } from '../storage/transfer';
24
+ import { uploadObject } from './backendUpload';
25
+ import { createMultipartUploads } from './multipart';
26
+ import { objectUploadHeaders } from './objectHeaders';
27
+ import type { S3ProviderOptions } from './options';
13
28
 
14
- // FileInfo type as received by the provider's requestUpload, part of RequestUploadParams
15
- type ProviderUploadedFileInfo = RequestUploadParams['fileInfo'];
16
-
17
- export type S3PathFnArgs = {
18
- /** Logical EdgeStore router bucket name. */
19
- edgestoreBucketName: string;
20
- /** File info after EdgeStore path and metadata generation. */
21
- fileInfo: ProviderUploadedFileInfo;
22
- /** Default object path relative to the logical bucket prefix. */
23
- defaultPath: string;
24
- };
25
-
26
- export type S3PathFn = (args: S3PathFnArgs) => MaybePromise<string>;
29
+ export type {
30
+ S3ObjectOptions,
31
+ S3PathFn,
32
+ S3PathFnArgs,
33
+ S3ProviderOptions,
34
+ } from './options';
27
35
 
28
- export type S3ProviderOptions = {
29
- /**
30
- * AWS SDK credentials (or credentials provider) to use for S3 requests.
31
- *
32
- * If unset, the AWS SDK will use its default credential provider chain
33
- * (environment variables, shared config files, instance/task roles, etc).
34
- */
35
- credentials?: S3ClientConfig['credentials'];
36
- /**
37
- * Access key for AWS credentials.
38
- * Can also be set via the `ES_AWS_ACCESS_KEY_ID` environment variable.
39
- *
40
- * If unset, the SDK will attempt to use the default credentials provider chain.
41
- *
42
- * @deprecated Pass `credentials` instead.
43
- */
44
- accessKeyId?: string;
45
- /**
46
- * Secret access key for AWS credentials.
47
- * Can also be set via the `ES_AWS_SECRET_ACCESS_KEY` environment variable.
48
- *
49
- * If unset, the SDK will attempt to use the default credentials provider chain.
50
- *
51
- * @deprecated Pass `credentials` instead.
52
- */
53
- secretAccessKey?: string;
54
- /**
55
- * AWS region to use.
56
- * Can also be set via the `ES_AWS_REGION` environment variable.
57
- */
58
- region?: string;
59
- /**
60
- * Name of the S3 bucket to use.
61
- * Can also be set via the `ES_AWS_BUCKET_NAME` environment variable.
62
- */
63
- bucketName?: string;
64
- /**
65
- * Custom endpoint for S3-compatible storage providers (e.g., MinIO).
66
- * Can also be set via the `ES_AWS_ENDPOINT` environment variable.
67
- */
68
- endpoint?: string;
69
- /**
70
- * Force path style for S3-compatible storage providers.
71
- * Can also be set via the `ES_AWS_FORCE_PATH_STYLE` environment variable.
72
- * Defaults to false for AWS S3, but should be true for most S3-compatible providers.
73
- */
74
- forcePathStyle?: boolean;
75
- /**
76
- * Base URL to use for accessing files.
77
- * Only needed if you are using a custom domain or cloudfront.
78
- *
79
- * It can also be set via the `EDGE_STORE_BASE_URL` environment variable.
80
- */
81
- baseUrl?: string;
82
- /**
83
- * Secret to use for encrypting JWT tokens.
84
- * Can be generated with `openssl rand -base64 32`.
85
- *
86
- * It can also be set via the `EDGE_STORE_JWT_SECRET` environment variable.
87
- */
88
- jwtSecret?: string;
89
- /**
90
- * Customizes the object path beneath the logical EdgeStore bucket prefix.
91
- *
92
- * The logical bucket prefix is always preserved so router authorization for
93
- * one bucket cannot access objects from another.
94
- */
95
- path?: S3PathFn;
96
- };
36
+ const expiration = (value: number) => signedUrlLifetime('S3', value);
97
37
 
98
- export function s3(options?: S3ProviderOptions) {
38
+ export function s3(options: S3ProviderOptions = {}) {
99
39
  const {
100
- credentials: credentialsFromOptions,
101
- accessKeyId = getEnv('ES_AWS_ACCESS_KEY_ID'),
102
- secretAccessKey = getEnv('ES_AWS_SECRET_ACCESS_KEY'),
40
+ credentials: configuredCredentials,
103
41
  region = getEnv('ES_AWS_REGION'),
104
42
  bucketName = getEnv('ES_AWS_BUCKET_NAME'),
105
43
  endpoint = getEnv('ES_AWS_ENDPOINT'),
106
44
  forcePathStyle = getEnv('ES_AWS_FORCE_PATH_STYLE') === 'true',
107
- path: resolvePath,
108
- } = options ?? {};
109
-
45
+ } = options;
46
+ const accessKeyId = getEnv('ES_AWS_ACCESS_KEY_ID');
47
+ const secretAccessKey = getEnv('ES_AWS_SECRET_ACCESS_KEY');
48
+ const client =
49
+ options.client ??
50
+ new S3Client({
51
+ region,
52
+ endpoint,
53
+ forcePathStyle,
54
+ credentials:
55
+ configuredCredentials ??
56
+ (accessKeyId && secretAccessKey
57
+ ? { accessKeyId, secretAccessKey }
58
+ : undefined),
59
+ // Presigning without a body must not sign an empty-body optional checksum.
60
+ requestChecksumCalculation: 'WHEN_REQUIRED',
61
+ });
110
62
  const baseUrl =
111
- options?.baseUrl ??
63
+ options.baseUrl ??
112
64
  getEnv('EDGE_STORE_BASE_URL') ??
113
65
  (endpoint
114
- ? `${endpoint}/${bucketName}`
115
- : `https://${bucketName}.s3.${region}.amazonaws.com`);
66
+ ? `${endpoint.replace(/\/+$/, '')}/${bucketName}`
67
+ : region
68
+ ? `https://${bucketName}.s3.${region}.amazonaws.com`
69
+ : async () =>
70
+ `https://${bucketName}.s3.${await client.config.region()}.amazonaws.com`);
71
+ const keys = async () =>
72
+ createObjectKeys(
73
+ 'S3',
74
+ typeof baseUrl === 'function' ? await baseUrl() : baseUrl,
75
+ );
76
+ const uploadExpiresIn = expiration(options.uploadUrlExpiresIn ?? 3600);
77
+ const readExpiresIn = expiration(options.signedUrlExpiresIn ?? 3600);
116
78
 
117
- const credentials =
118
- credentialsFromOptions ??
119
- (accessKeyId && secretAccessKey
120
- ? {
121
- accessKeyId,
122
- secretAccessKey,
123
- }
124
- : undefined);
125
- const s3Client = new S3Client({
126
- region,
127
- credentials,
128
- endpoint,
129
- forcePathStyle,
79
+ function bucket() {
80
+ if (!bucketName)
81
+ throw new Error('S3 bucketName is not configured in S3ProviderOptions.');
82
+ return bucketName;
83
+ }
84
+ function plan(sizeBytes: number) {
85
+ if (!Number.isSafeInteger(sizeBytes) || sizeBytes < 0)
86
+ throw new RangeError(
87
+ 'S3 upload size must be a nonnegative safe integer.',
88
+ );
89
+ const result = planMultipartUpload({
90
+ sizeBytes,
91
+ thresholdBytes: options.multipart?.thresholdBytes,
92
+ preferredPartSizeBytes: options.multipart?.partSizeBytes,
93
+ forceMultipart: sizeBytes > 5 * 1024 ** 3,
94
+ });
95
+ if (result && result.partSizeBytes > 5 * 1024 ** 3)
96
+ throw new RangeError('S3 multipart parts cannot exceed 5 GiB.');
97
+ return result;
98
+ }
99
+ // Validate multipart settings even before the first large upload.
100
+ plan(0);
101
+ const multipart = createMultipartUploads({
102
+ client,
103
+ bucket,
104
+ partUrlExpiresIn: uploadExpiresIn,
105
+ sessions: createMultipartSessions({
106
+ providerName: 'S3',
107
+ audience: `edgestore:s3:${endpoint ?? region ?? 'aws'}:${bucketName}`,
108
+ secret: options.jwtSecret,
109
+ expiresIn: options.multipart?.sessionExpiresIn ?? 86400,
110
+ }),
130
111
  });
131
- const normalizedBaseUrl = baseUrl.replace(/\/+$/, '');
132
112
 
133
- function objectKeyToUrl(objectKey: string) {
134
- const encodedKey = objectKey
135
- .split('/')
136
- .map((segment) => encodeURIComponent(segment))
137
- .join('/');
138
- return `${normalizedBaseUrl}/${encodedKey}`;
113
+ async function prepare({
114
+ bucketName: logicalBucket,
115
+ fileInfo,
116
+ }: RequestUploadParams) {
117
+ const physicalBucket = bucket();
118
+ const objectKeys = await keys();
119
+ const { key, pathArgs } = await objectKeys.forUpload(
120
+ logicalBucket,
121
+ fileInfo,
122
+ options.path,
123
+ );
124
+ const objectOptions =
125
+ typeof options.objectOptions === 'function'
126
+ ? await options.objectOptions(pathArgs)
127
+ : options.objectOptions;
128
+ const input: PutObjectCommandInput = {
129
+ ...objectOptions,
130
+ Bucket: physicalBucket,
131
+ Key: key,
132
+ ContentLength: fileInfo.size,
133
+ ContentType: fileInfo.type || 'application/octet-stream',
134
+ };
135
+ return {
136
+ input,
137
+ key,
138
+ url: objectKeys.toUrl(key),
139
+ plan: plan(fileInfo.size),
140
+ };
139
141
  }
140
142
 
141
- function urlToObjectKey(edgestoreBucketName: string, url: string) {
142
- let objectKey: string;
143
- try {
144
- const fileUrl = new URL(url);
145
- const providerUrl = new URL(`${normalizedBaseUrl}/`);
146
- if (
147
- fileUrl.origin !== providerUrl.origin ||
148
- !fileUrl.pathname.startsWith(providerUrl.pathname)
149
- ) {
150
- throw new Error();
143
+ async function signedRead(key: string, expiresIn = readExpiresIn) {
144
+ const ttl = expiration(expiresIn);
145
+ const signedUrl = await getSignedUrl(
146
+ client,
147
+ new GetObjectCommand({ Bucket: bucket(), Key: key }),
148
+ { expiresIn: ttl },
149
+ );
150
+ return {
151
+ url: (await keys()).toUrl(key),
152
+ signedUrl,
153
+ expiresAt: new Date(Date.now() + ttl * 1000),
154
+ expiresIn: ttl,
155
+ };
156
+ }
157
+ // Presigned browser uploads must not sign a checksum of the empty body.
158
+ let presignable: Promise<void> | undefined;
159
+ function assertPresignableClient() {
160
+ return (presignable ??= (async () => {
161
+ const policy = options.client
162
+ ? await client.config.requestChecksumCalculation?.()
163
+ : undefined;
164
+ if (policy && policy !== 'WHEN_REQUIRED') {
165
+ throw new Error(
166
+ 'An injected S3 client must use requestChecksumCalculation: "WHEN_REQUIRED" for browser uploads.',
167
+ );
151
168
  }
152
- objectKey = decodeURIComponent(
153
- fileUrl.pathname.slice(providerUrl.pathname.length),
154
- );
155
- } catch {
156
- throw new Error('File URL does not belong to this S3 provider.');
157
- }
158
-
159
- if (!objectKey.startsWith(`${edgestoreBucketName}/`)) {
160
- throw new Error(
161
- `File does not belong to EdgeStore bucket "${edgestoreBucketName}".`,
162
- );
163
- }
164
- return objectKey;
169
+ })());
165
170
  }
166
171
 
167
- function normalizeRelativePath(value: string) {
168
- const path = value.replace(/^\/+|\/+$/g, '');
169
- if (
170
- path.length === 0 ||
171
- path.split('/').some((segment) => segment === '.' || segment === '..')
172
- ) {
173
- throw new Error('S3 paths must stay within the EdgeStore bucket prefix.');
174
- }
175
- return path;
172
+ async function readForUpload(key: string, params: RequestUploadParams) {
173
+ if (params.fileInfo.isPublic || !params.autoSignedUrls) return undefined;
174
+ return signedRead(key, params.autoSignedUrls.expiresIn);
176
175
  }
177
176
 
178
177
  return defineProvider({
179
178
  name: 's3',
180
- baseUrl,
181
179
  reference: {
182
- schema: z.object({ url: z.string() }),
180
+ schema: z.union([
181
+ z.object({ key: z.string().min(1) }),
182
+ z.object({ url: z.string().url() }),
183
+ ]),
183
184
  fromUrl: (url) => ({ url }),
184
185
  },
185
- async init() {
186
+ async init({ router }) {
187
+ bucket();
188
+ assertSignedUrlAccessControl('S3', router);
186
189
  return {};
187
190
  },
188
191
  uploads: {
189
- async request(params: RequestUploadParams) {
190
- const { bucketName: esBucketName, fileInfo } = params;
191
-
192
- if (!bucketName) {
193
- throw new Error(
194
- 'S3 bucketName is not configured in S3ProviderOptions.',
195
- );
192
+ supportedOptions: { temporary: false, replaceTargetUrl: false },
193
+ async request(params): Promise<RequestUploadRes> {
194
+ await assertPresignableClient();
195
+ const prepared = await prepare(params);
196
+ const read = await readForUpload(prepared.key, params);
197
+ const access = {
198
+ key: prepared.key,
199
+ url: prepared.url,
200
+ ...(read
201
+ ? {
202
+ signedReadUrl: {
203
+ signedUrl: read.signedUrl,
204
+ expiresAt: read.expiresAt,
205
+ expiresIn: read.expiresIn,
206
+ },
207
+ }
208
+ : {}),
209
+ };
210
+ if (prepared.plan) {
211
+ return {
212
+ ...access,
213
+ multipart: await multipart.request(prepared.input, prepared.plan),
214
+ };
196
215
  }
197
-
198
- const extension = fileInfo.extension
199
- ? `.${fileInfo.extension.replace('.', '')}`
200
- : '';
201
- const defaultResolvedFileName =
202
- fileInfo.fileName ?? `${crypto.randomUUID()}${extension}`;
203
- const defaultPath = [
204
- ...(fileInfo.isPublic ? ['_public'] : []),
205
- ...fileInfo.path.map((item) => item.value),
206
- defaultResolvedFileName,
207
- ].join('/');
208
-
209
- const relativePath = normalizeRelativePath(
210
- resolvePath
211
- ? await resolvePath({
212
- edgestoreBucketName: esBucketName,
213
- fileInfo,
214
- defaultPath,
215
- })
216
- : defaultPath,
217
- );
218
- const accessPath = `${esBucketName}/${relativePath}`;
219
-
220
- const command = new PutObjectCommand({
221
- Bucket: bucketName,
222
- Key: accessPath,
216
+ const uploadHeaders = objectUploadHeaders(prepared.input);
217
+ return {
218
+ ...access,
219
+ uploadUrl: await getSignedUrl(
220
+ client,
221
+ new PutObjectCommand(prepared.input),
222
+ {
223
+ expiresIn: uploadExpiresIn,
224
+ signableHeaders: new Set(['content-type']),
225
+ unhoistableHeaders: new Set(
226
+ Object.keys(uploadHeaders).map((name) => name.toLowerCase()),
227
+ ),
228
+ },
229
+ ),
230
+ uploadHeaders,
231
+ };
232
+ },
233
+ multipart: multipart.operations,
234
+ async upload(params) {
235
+ const prepared = await prepare({
236
+ ...params,
237
+ fileInfo: {
238
+ ...params.fileInfo,
239
+ size: params.source.size,
240
+ type: params.source.type || params.fileInfo.type,
241
+ },
223
242
  });
224
- const signedUrl = await getSignedUrl(s3Client, command, {
225
- expiresIn: 60 * 60,
243
+ // Sign the read URL before sending bytes: nothing fallible may run
244
+ // after the object is committed.
245
+ const signedReadUrl = await readForUpload(prepared.key, params);
246
+ await uploadObject({
247
+ client,
248
+ input: prepared.input,
249
+ plan: prepared.plan,
250
+ source: params.source,
251
+ signal: params.signal,
252
+ onProgress: params.onProgress,
226
253
  });
254
+ // The object is committed. Describe it from what we sent, so a failed
255
+ // or canceled follow-up request cannot turn success into an error.
256
+ const uploadedAt = new Date();
227
257
  return {
228
- uploadUrl: signedUrl,
229
- accessUrl: objectKeyToUrl(accessPath),
258
+ file: {
259
+ key: prepared.key,
260
+ url: prepared.url,
261
+ sizeBytes: params.source.size,
262
+ uploadedAt,
263
+ updatedAt: uploadedAt,
264
+ },
265
+ signedReadUrl,
230
266
  };
231
267
  },
232
268
  },
233
269
  files: {
234
- async get({ bucketName: edgestoreBucketName, file }) {
235
- const path = urlToObjectKey(edgestoreBucketName, file.url);
236
- const { ContentLength, LastModified } = await s3Client.send(
237
- new HeadObjectCommand({
238
- Bucket: bucketName,
239
- Key: path,
240
- }),
270
+ async get({ bucketName: logicalBucket, file }) {
271
+ const objectKeys = await keys();
272
+ const key = objectKeys.fromReference(logicalBucket, file);
273
+ const { ContentLength, LastModified } = await client.send(
274
+ new HeadObjectCommand({ Bucket: bucket(), Key: key }),
241
275
  );
242
-
243
- if (ContentLength === undefined || !LastModified) {
276
+ if (ContentLength === undefined || !LastModified)
244
277
  throw new Error('File not found');
245
- }
246
-
247
278
  return {
248
- url: file.url,
279
+ key,
280
+ url: objectKeys.toUrl(key),
249
281
  sizeBytes: ContentLength,
250
282
  uploadedAt: LastModified,
251
283
  updatedAt: LastModified,
252
284
  };
253
285
  },
254
- async delete({ bucketName: edgestoreBucketName, files }) {
255
- if (!bucketName) {
256
- throw new Error(
257
- 'S3 bucketName is not configured in S3ProviderOptions for deleteFile.',
258
- );
259
- }
260
- const objectKeys = files.map((file) =>
261
- urlToObjectKey(edgestoreBucketName, file.url),
286
+ async getSignedUrls({ bucketName: logicalBucket, files, expiresIn }) {
287
+ const objectKeys = await keys();
288
+ const objectKeysToSign = files.map((file) =>
289
+ objectKeys.fromReference(logicalBucket, file),
290
+ );
291
+ return Promise.all(
292
+ objectKeysToSign.map((key) => signedRead(key, expiresIn)),
262
293
  );
263
- const results = await Promise.all(
264
- objectKeys.map(async (objectKey) => {
265
- try {
266
- await s3Client.send(
267
- new DeleteObjectCommand({
268
- Bucket: bucketName,
269
- Key: objectKey,
270
- }),
271
- );
272
- return { success: true as const };
273
- } catch (error) {
274
- return {
275
- success: false as const,
276
- error: {
277
- code: 'DELETE_FAILED' as const,
278
- message:
279
- error instanceof Error ? error.message : 'Delete failed',
294
+ },
295
+ async delete({ bucketName: logicalBucket, files }) {
296
+ const physicalBucket = bucket();
297
+ const objectKeys = await keys();
298
+ const paths = files.map((file) =>
299
+ objectKeys.fromReference(logicalBucket, file),
300
+ );
301
+ const results = [];
302
+ // DeleteObjects accepts up to 1,000 keys per request.
303
+ for (let start = 0; start < paths.length; start += 1000) {
304
+ const batch = paths.slice(start, start + 1000);
305
+ const errors = new Map<string, string>();
306
+ try {
307
+ const { Errors } = await client.send(
308
+ new DeleteObjectsCommand({
309
+ Bucket: physicalBucket,
310
+ Delete: {
311
+ Objects: [...new Set(batch)].map((Key) => ({ Key })),
312
+ Quiet: true,
280
313
  },
281
- };
314
+ }),
315
+ );
316
+ for (const error of Errors ?? []) {
317
+ if (error.Key)
318
+ errors.set(error.Key, error.Message ?? 'Delete failed');
282
319
  }
283
- }),
284
- );
320
+ } catch (error) {
321
+ const message =
322
+ error instanceof Error ? error.message : 'Delete failed';
323
+ for (const key of batch) errors.set(key, message);
324
+ }
325
+ for (const key of batch) {
326
+ const message = errors.get(key);
327
+ results.push(
328
+ message === undefined
329
+ ? { success: true as const }
330
+ : {
331
+ success: false as const,
332
+ error: { code: 'DELETE_FAILED' as const, message },
333
+ },
334
+ );
335
+ }
336
+ }
285
337
  return { results };
286
338
  },
287
339
  },