@edgestore/server 0.8.0 → 1.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/adapters/astro/index.d.ts +1 -1
  2. package/adapters/astro/index.js +1 -1
  3. package/adapters/express/index.d.ts +1 -1
  4. package/adapters/express/index.js +1 -1
  5. package/adapters/fastify/index.d.ts +1 -1
  6. package/adapters/fastify/index.js +1 -1
  7. package/adapters/hono/index.d.ts +1 -1
  8. package/adapters/hono/index.js +1 -1
  9. package/adapters/next/app/index.d.ts +1 -1
  10. package/adapters/next/app/index.js +1 -1
  11. package/adapters/next/pages/index.d.ts +1 -1
  12. package/adapters/next/pages/index.js +1 -1
  13. package/adapters/remix/index.d.ts +1 -1
  14. package/adapters/remix/index.js +1 -1
  15. package/adapters/start/index.d.ts +1 -1
  16. package/adapters/start/index.js +1 -1
  17. package/core/index.d.ts +1 -1
  18. package/core/index.js +1 -1
  19. package/dist/adapters/astro/index.d.ts +2 -2
  20. package/dist/adapters/astro/index.js +28 -30
  21. package/dist/adapters/express/index.d.ts +2 -2
  22. package/dist/adapters/express/index.js +28 -30
  23. package/dist/adapters/fastify/index.d.ts +2 -2
  24. package/dist/adapters/fastify/index.js +28 -30
  25. package/dist/adapters/hono/index.d.ts +2 -2
  26. package/dist/adapters/hono/index.js +28 -30
  27. package/dist/adapters/imageTypes.js +1 -3
  28. package/dist/adapters/next/app/index.d.ts +2 -2
  29. package/dist/adapters/next/app/index.js +29 -31
  30. package/dist/adapters/next/pages/index.d.ts +2 -2
  31. package/dist/adapters/next/pages/index.js +29 -31
  32. package/dist/adapters/remix/index.d.ts +2 -2
  33. package/dist/adapters/remix/index.js +28 -30
  34. package/dist/adapters/shared.d.ts.map +1 -1
  35. package/dist/adapters/shared.js +44 -50
  36. package/dist/adapters/start/index.d.ts +2 -2
  37. package/dist/adapters/start/index.js +28 -30
  38. package/dist/core/client/index.d.ts.map +1 -1
  39. package/dist/core/client/index.js +7 -9
  40. package/dist/core/index.d.ts +2 -2
  41. package/dist/core/index.js +2 -10
  42. package/dist/core/sdk/index.d.ts.map +1 -1
  43. package/dist/core/sdk/index.js +10 -13
  44. package/dist/index.js +1 -10
  45. package/dist/libs/errors/EdgeStoreCredentialsError.js +1 -3
  46. package/dist/libs/logger.js +5 -9
  47. package/dist/libs/utils.js +1 -3
  48. package/dist/providers/aws/index.d.ts.map +1 -1
  49. package/dist/providers/aws/index.js +12 -15
  50. package/dist/providers/azure/index.d.ts.map +1 -1
  51. package/dist/providers/azure/index.js +6 -9
  52. package/dist/providers/edgestore/index.js +12 -14
  53. package/dist/version.d.ts +1 -1
  54. package/dist/version.d.ts.map +1 -1
  55. package/dist/version.js +2 -5
  56. package/package.json +51 -50
  57. package/providers/aws/index.d.ts +1 -1
  58. package/providers/aws/index.js +1 -1
  59. package/providers/azure/index.d.ts +1 -1
  60. package/providers/azure/index.js +1 -1
  61. package/providers/edgestore/index.d.ts +1 -1
  62. package/providers/edgestore/index.js +1 -1
  63. package/src/adapters/shared.ts +12 -13
  64. package/src/core/client/index.ts +0 -1
  65. package/src/core/sdk/index.ts +1 -8
  66. package/src/providers/aws/index.ts +1 -2
  67. package/src/providers/azure/index.ts +1 -2
  68. package/src/version.ts +1 -1
  69. package/dist/adapters/astro/index.mjs +0 -172
  70. package/dist/adapters/express/index.mjs +0 -108
  71. package/dist/adapters/fastify/index.mjs +0 -135
  72. package/dist/adapters/hono/index.mjs +0 -131
  73. package/dist/adapters/imageTypes.mjs +0 -12
  74. package/dist/adapters/next/app/index.mjs +0 -163
  75. package/dist/adapters/next/pages/index.mjs +0 -112
  76. package/dist/adapters/remix/index.mjs +0 -148
  77. package/dist/adapters/shared.mjs +0 -471
  78. package/dist/adapters/start/index.mjs +0 -181
  79. package/dist/core/client/index.mjs +0 -221
  80. package/dist/core/index.mjs +0 -2
  81. package/dist/core/sdk/index.mjs +0 -253
  82. package/dist/index.mjs +0 -1
  83. package/dist/libs/errors/EdgeStoreCredentialsError.mjs +0 -10
  84. package/dist/libs/logger.mjs +0 -53
  85. package/dist/libs/utils.mjs +0 -10
  86. package/dist/providers/aws/index.mjs +0 -103
  87. package/dist/providers/azure/index.mjs +0 -85
  88. package/dist/providers/edgestore/index.mjs +0 -164
  89. package/dist/version.mjs +0 -4
@@ -1,471 +0,0 @@
1
- import { EdgeStoreError } from '@edgestore/shared';
2
- import { hkdf } from '@panva/hkdf';
3
- import { serialize } from 'cookie';
4
- import { EncryptJWT, jwtDecrypt } from 'jose';
5
- import { v4 } from 'uuid';
6
- import { IMAGE_MIME_TYPES } from './imageTypes.mjs';
7
-
8
- // TODO: change it to 1 hour when we have a way to refresh the token
9
- const DEFAULT_MAX_AGE = 30 * 24 * 60 * 60; // 30 days
10
- const NO_BODY_STATUSES = new Set([
11
- 204,
12
- 205,
13
- 304
14
- ]);
15
- async function fetchProxyFile({ cookieHeader, url }) {
16
- const proxyRes = await fetch(url, {
17
- headers: {
18
- cookie: cookieHeader ?? ''
19
- }
20
- });
21
- const body = NO_BODY_STATUSES.has(proxyRes.status) ? null : await proxyRes.arrayBuffer();
22
- return {
23
- body,
24
- contentType: proxyRes.headers.get('Content-Type') ?? 'application/octet-stream',
25
- status: proxyRes.status
26
- };
27
- }
28
- /**
29
- * Merges the provided cookie configuration with default values
30
- */ function getCookieConfig(cookieConfig) {
31
- const defaultOptions = {
32
- path: '/',
33
- maxAge: DEFAULT_MAX_AGE
34
- };
35
- // Helper function to merge options, filtering out undefined values
36
- const mergeOptions = (configOptions)=>{
37
- const merged = {
38
- ...defaultOptions
39
- };
40
- if (configOptions) {
41
- Object.keys(configOptions).forEach((key)=>{
42
- const value = configOptions[key];
43
- if (value !== undefined) {
44
- merged[key] = value;
45
- }
46
- });
47
- }
48
- return merged;
49
- };
50
- return {
51
- ctx: {
52
- name: cookieConfig?.ctx?.name ?? 'edgestore-ctx',
53
- options: mergeOptions(cookieConfig?.ctx?.options)
54
- },
55
- token: {
56
- name: cookieConfig?.token?.name ?? 'edgestore-token',
57
- options: mergeOptions(cookieConfig?.token?.options)
58
- }
59
- };
60
- }
61
- async function init(params) {
62
- const log = globalThis._EDGE_STORE_LOGGER;
63
- const { ctx, provider, router, cookieConfig } = params;
64
- log.debug('Running [init]', {
65
- ctx
66
- });
67
- const resolvedCookieConfig = getCookieConfig(cookieConfig);
68
- const ctxToken = await encryptJWT(ctx);
69
- const requiresFileAccessCookie = provider.name === 'edgestore' && Object.values(router.buckets).some((bucket)=>bucket._def.accessControl !== undefined && bucket._def.accessControl !== 'private');
70
- const shouldRunProviderInit = provider.name !== 'edgestore' || requiresFileAccessCookie;
71
- let token;
72
- if (shouldRunProviderInit) {
73
- const initRes = await provider.init({
74
- ctx,
75
- router: router
76
- });
77
- token = initRes.token;
78
- }
79
- const newCookies = [
80
- serialize(resolvedCookieConfig.ctx.name, ctxToken, resolvedCookieConfig.ctx.options)
81
- ];
82
- if (token) {
83
- newCookies.push(serialize(resolvedCookieConfig.token.name, token, resolvedCookieConfig.token.options));
84
- }
85
- const baseUrl = await provider.getBaseUrl();
86
- log.debug('Finished [init]', {
87
- ctx,
88
- newCookies,
89
- token,
90
- baseUrl,
91
- providerName: provider.name,
92
- requiresFileAccessCookie
93
- });
94
- return {
95
- newCookies,
96
- token,
97
- baseUrl,
98
- providerName: provider.name,
99
- requiresFileAccessCookie
100
- };
101
- }
102
- async function requestUpload(params) {
103
- const { provider, router, ctxToken, body: { bucketName, input, fileInfo } } = params;
104
- const log = globalThis._EDGE_STORE_LOGGER;
105
- log.debug('Running [requestUpload]', {
106
- bucketName,
107
- input,
108
- fileInfo
109
- });
110
- if (!ctxToken) {
111
- throw new EdgeStoreError({
112
- message: 'Missing edgestore-ctx cookie',
113
- code: 'UNAUTHORIZED'
114
- });
115
- }
116
- const ctx = await getContext(ctxToken);
117
- log.debug('Decrypted Context', {
118
- ctx
119
- });
120
- const bucket = router.buckets[bucketName];
121
- if (!bucket) {
122
- throw new EdgeStoreError({
123
- message: `Bucket ${bucketName} not found`,
124
- code: 'BAD_REQUEST'
125
- });
126
- }
127
- if (bucket._def.beforeUpload) {
128
- log.debug('Running [beforeUpload]');
129
- const canUpload = await bucket._def.beforeUpload?.({
130
- ctx,
131
- input,
132
- fileInfo: {
133
- size: fileInfo.size,
134
- type: fileInfo.type,
135
- fileName: fileInfo.fileName,
136
- extension: fileInfo.extension,
137
- replaceTargetUrl: fileInfo.replaceTargetUrl,
138
- temporary: fileInfo.temporary
139
- }
140
- });
141
- log.debug('Finished [beforeUpload]', {
142
- canUpload
143
- });
144
- if (!canUpload) {
145
- throw new EdgeStoreError({
146
- message: 'Upload not allowed for the current context',
147
- code: 'UPLOAD_NOT_ALLOWED'
148
- });
149
- }
150
- }
151
- if (bucket._def.type === 'IMAGE') {
152
- if (!IMAGE_MIME_TYPES.includes(fileInfo.type)) {
153
- throw new EdgeStoreError({
154
- code: 'MIME_TYPE_NOT_ALLOWED',
155
- message: 'Only images are allowed in this bucket',
156
- details: {
157
- allowedMimeTypes: IMAGE_MIME_TYPES,
158
- mimeType: fileInfo.type
159
- }
160
- });
161
- }
162
- }
163
- if (bucket._def.bucketConfig?.maxSize) {
164
- if (fileInfo.size > bucket._def.bucketConfig.maxSize) {
165
- throw new EdgeStoreError({
166
- code: 'FILE_TOO_LARGE',
167
- message: `File size is too big. Max size is ${bucket._def.bucketConfig.maxSize}`,
168
- details: {
169
- maxFileSize: bucket._def.bucketConfig.maxSize,
170
- fileSize: fileInfo.size
171
- }
172
- });
173
- }
174
- }
175
- if (bucket._def.bucketConfig?.accept) {
176
- const accept = bucket._def.bucketConfig.accept;
177
- let accepted = false;
178
- for (const acceptedMimeType of accept){
179
- if (acceptedMimeType.endsWith('/*')) {
180
- const mimeType = acceptedMimeType.replace('/*', '');
181
- if (fileInfo.type.startsWith(mimeType)) {
182
- accepted = true;
183
- break;
184
- }
185
- } else if (fileInfo.type === acceptedMimeType) {
186
- accepted = true;
187
- break;
188
- }
189
- }
190
- if (!accepted) {
191
- throw new EdgeStoreError({
192
- code: 'MIME_TYPE_NOT_ALLOWED',
193
- message: `"${fileInfo.type}" is not allowed. Accepted types are ${JSON.stringify(accept)}`,
194
- details: {
195
- allowedMimeTypes: accept,
196
- mimeType: fileInfo.type
197
- }
198
- });
199
- }
200
- }
201
- const path = buildPath({
202
- bucket,
203
- pathAttrs: {
204
- ctx,
205
- input
206
- }
207
- });
208
- const metadata = await bucket._def.metadata?.({
209
- ctx,
210
- input
211
- });
212
- const isPublic = bucket._def.accessControl === undefined;
213
- const autoSignedUrls = bucket._def.autoSignedUrls;
214
- log.debug('upload info', {
215
- path,
216
- metadata,
217
- isPublic,
218
- bucketType: bucket._def.type
219
- });
220
- const requestUploadRes = await provider.requestUpload({
221
- bucketName,
222
- bucketType: bucket._def.type,
223
- fileInfo: {
224
- ...fileInfo,
225
- path,
226
- isPublic,
227
- metadata
228
- },
229
- autoSignedUrls
230
- });
231
- const { parsedPath, pathOrder } = parsePath(path);
232
- log.debug('Finished [requestUpload]');
233
- return {
234
- ...requestUploadRes,
235
- size: fileInfo.size,
236
- uploadedAt: new Date().toISOString(),
237
- path: parsedPath,
238
- pathOrder,
239
- metadata
240
- };
241
- }
242
- async function requestUploadParts(params) {
243
- const { provider, ctxToken, body: { multipart, path } } = params;
244
- const log = globalThis._EDGE_STORE_LOGGER;
245
- log.debug('Running [requestUploadParts]', {
246
- multipart,
247
- path
248
- });
249
- if (!ctxToken) {
250
- throw new EdgeStoreError({
251
- message: 'Missing edgestore-ctx cookie',
252
- code: 'UNAUTHORIZED'
253
- });
254
- }
255
- await getContext(ctxToken); // just to check if the token is valid
256
- const res = await provider.requestUploadParts({
257
- multipart,
258
- path
259
- });
260
- log.debug('Finished [requestUploadParts]');
261
- return res;
262
- }
263
- async function completeMultipartUpload(params) {
264
- const { provider, router, ctxToken, body: { bucketName, uploadId, key, parts } } = params;
265
- const log = globalThis._EDGE_STORE_LOGGER;
266
- log.debug('Running [completeMultipartUpload]', {
267
- bucketName,
268
- uploadId,
269
- key
270
- });
271
- if (!ctxToken) {
272
- throw new EdgeStoreError({
273
- message: 'Missing edgestore-ctx cookie',
274
- code: 'UNAUTHORIZED'
275
- });
276
- }
277
- await getContext(ctxToken); // just to check if the token is valid
278
- const bucket = router.buckets[bucketName];
279
- if (!bucket) {
280
- throw new EdgeStoreError({
281
- message: `Bucket ${bucketName} not found`,
282
- code: 'BAD_REQUEST'
283
- });
284
- }
285
- const res = await provider.completeMultipartUpload({
286
- uploadId,
287
- key,
288
- parts
289
- });
290
- log.debug('Finished [completeMultipartUpload]');
291
- return res;
292
- }
293
- async function confirmUpload(params) {
294
- const { provider, router, ctxToken, body: { bucketName, url } } = params;
295
- const log = globalThis._EDGE_STORE_LOGGER;
296
- log.debug('Running [confirmUpload]', {
297
- bucketName,
298
- url
299
- });
300
- if (!ctxToken) {
301
- throw new EdgeStoreError({
302
- message: 'Missing edgestore-ctx cookie',
303
- code: 'UNAUTHORIZED'
304
- });
305
- }
306
- await getContext(ctxToken); // just to check if the token is valid
307
- const bucket = router.buckets[bucketName];
308
- if (!bucket) {
309
- throw new EdgeStoreError({
310
- message: `Bucket ${bucketName} not found`,
311
- code: 'BAD_REQUEST'
312
- });
313
- }
314
- const res = await provider.confirmUpload({
315
- bucket,
316
- url: unproxyUrl(url)
317
- });
318
- log.debug('Finished [confirmUpload]');
319
- return res;
320
- }
321
- async function deleteFile(params) {
322
- const { provider, router, ctxToken, body: { bucketName, url } } = params;
323
- const log = globalThis._EDGE_STORE_LOGGER;
324
- log.debug('Running [deleteFile]', {
325
- bucketName,
326
- url
327
- });
328
- if (!ctxToken) {
329
- throw new EdgeStoreError({
330
- message: 'Missing edgestore-ctx cookie',
331
- code: 'UNAUTHORIZED'
332
- });
333
- }
334
- const ctx = await getContext(ctxToken);
335
- const bucket = router.buckets[bucketName];
336
- if (!bucket) {
337
- throw new EdgeStoreError({
338
- message: `Bucket ${bucketName} not found`,
339
- code: 'BAD_REQUEST'
340
- });
341
- }
342
- if (!bucket._def.beforeDelete) {
343
- throw new EdgeStoreError({
344
- message: 'You need to define beforeDelete if you want to delete files directly from the frontend.',
345
- code: 'SERVER_ERROR'
346
- });
347
- }
348
- const fileInfo = await provider.getFile({
349
- url: unproxyUrl(url)
350
- });
351
- const canDelete = await bucket._def.beforeDelete({
352
- ctx,
353
- fileInfo
354
- });
355
- if (!canDelete) {
356
- throw new EdgeStoreError({
357
- message: 'Delete not allowed for the current context',
358
- code: 'DELETE_NOT_ALLOWED'
359
- });
360
- }
361
- const res = await provider.deleteFile({
362
- bucket,
363
- url: unproxyUrl(url)
364
- });
365
- log.debug('Finished [deleteFile]');
366
- return res;
367
- }
368
- async function encryptJWT(ctx) {
369
- const secret = getEnv('EDGE_STORE_JWT_SECRET') ?? getEnv('EDGE_STORE_SECRET_KEY');
370
- if (!secret) {
371
- throw new EdgeStoreError({
372
- message: 'EDGE_STORE_JWT_SECRET or EDGE_STORE_SECRET_KEY is not defined',
373
- code: 'SERVER_ERROR'
374
- });
375
- }
376
- const encryptionSecret = await getDerivedEncryptionKey(secret);
377
- return await new EncryptJWT(ctx).setProtectedHeader({
378
- alg: 'dir',
379
- enc: 'A256GCM'
380
- }).setIssuedAt().setExpirationTime(Date.now() / 1000 + DEFAULT_MAX_AGE).setJti(v4()).encrypt(encryptionSecret);
381
- }
382
- async function decryptJWT(token) {
383
- const secret = getEnv('EDGE_STORE_JWT_SECRET') ?? getEnv('EDGE_STORE_SECRET_KEY');
384
- if (!secret) {
385
- throw new EdgeStoreError({
386
- message: 'EDGE_STORE_JWT_SECRET or EDGE_STORE_SECRET_KEY is not defined',
387
- code: 'SERVER_ERROR'
388
- });
389
- }
390
- const encryptionSecret = await getDerivedEncryptionKey(secret);
391
- const { payload } = await jwtDecrypt(token, encryptionSecret, {
392
- clockTolerance: 15
393
- });
394
- return payload;
395
- }
396
- async function getDerivedEncryptionKey(secret) {
397
- return await hkdf('sha256', secret, '', 'EdgeStore Generated Encryption Key', 32);
398
- }
399
- function buildPath(params) {
400
- const { bucket } = params;
401
- const pathParams = bucket._def.path;
402
- const path = pathParams.map((param)=>{
403
- const paramEntries = Object.entries(param);
404
- if (paramEntries[0] === undefined) {
405
- throw new EdgeStoreError({
406
- message: `Empty path param found in: ${JSON.stringify(pathParams)}`,
407
- code: 'SERVER_ERROR'
408
- });
409
- }
410
- const [key, value] = paramEntries[0];
411
- // this is a string like: "ctx.xxx" or "input.yyy.zzz"
412
- const currParamVal = value().split('.').reduce((acc2, key)=>{
413
- if (acc2[key] === undefined) {
414
- throw new EdgeStoreError({
415
- message: `Missing key ${key} in ${JSON.stringify(acc2)}`,
416
- code: 'BAD_REQUEST'
417
- });
418
- }
419
- return acc2[key];
420
- }, params.pathAttrs);
421
- return {
422
- key,
423
- value: currParamVal
424
- };
425
- });
426
- return path;
427
- }
428
- function parsePath(path) {
429
- const parsedPath = path.reduce((acc, curr)=>{
430
- acc[curr.key] = curr.value;
431
- return acc;
432
- }, {});
433
- const pathOrder = path.map((p)=>p.key);
434
- return {
435
- parsedPath,
436
- pathOrder
437
- };
438
- }
439
- async function getContext(token) {
440
- return await decryptJWT(token);
441
- }
442
- /**
443
- * On local development, protected files are proxied to the server,
444
- * which changes the original URL.
445
- *
446
- * This function is used to get the original URL,
447
- * so that we can delete or confirm the upload.
448
- */ function unproxyUrl(url) {
449
- if (isDev() && url.startsWith('http://')) {
450
- // get the url param from the query string
451
- const urlParam = new URL(url).searchParams.get('url');
452
- if (urlParam) {
453
- return urlParam;
454
- }
455
- }
456
- return url;
457
- }
458
- function getEnv(key) {
459
- if (typeof process !== 'undefined' && process.env) {
460
- // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
461
- return process.env[key] ?? import.meta.env?.[key];
462
- }
463
- // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
464
- return import.meta.env?.[key];
465
- }
466
- function isDev() {
467
- return process?.env?.NODE_ENV === 'development' || // @ts-expect-error - In Vite/Astro, the env variables are available on `import.meta`.
468
- import.meta.env?.DEV;
469
- }
470
-
471
- export { buildPath, completeMultipartUpload, confirmUpload, deleteFile, fetchProxyFile, getCookieConfig, getEnv, init, isDev, parsePath, requestUpload, requestUploadParts };
@@ -1,181 +0,0 @@
1
- import { EdgeStoreError, EDGE_STORE_ERROR_CODES } from '@edgestore/shared';
2
- import Logger from '../../libs/logger.mjs';
3
- import { matchPath } from '../../libs/utils.mjs';
4
- import { EdgeStoreProvider } from '../../providers/edgestore/index.mjs';
5
- import { getCookieConfig, init, requestUpload, requestUploadParts, completeMultipartUpload, confirmUpload, deleteFile, fetchProxyFile } from '../shared.mjs';
6
-
7
- // Helper to extract a cookie from the request's cookie header
8
- function getCookie(req, cookieName) {
9
- const cookieHeader = req.headers.get('cookie');
10
- if (!cookieHeader) return undefined;
11
- return cookieHeader.split(';').map((cookieStr)=>cookieStr.trim()).reduce((acc, cookieStr)=>{
12
- const [name, ...rest] = cookieStr.split('=');
13
- if (name && rest.length > 0) {
14
- acc[name] = rest.join('=');
15
- }
16
- return acc;
17
- }, {})[cookieName];
18
- }
19
- function createEdgeStoreStartHandler(config) {
20
- const { provider = EdgeStoreProvider(), cookieConfig } = config;
21
- const log = new Logger(config.logLevel);
22
- globalThis._EDGE_STORE_LOGGER = log;
23
- log.debug('Creating EdgeStore TanStack Start handler');
24
- const resolvedCookieConfig = getCookieConfig(cookieConfig);
25
- return async ({ request })=>{
26
- try {
27
- const { pathname } = new URL(request.url);
28
- if (matchPath(pathname, '/health')) {
29
- return new Response('OK', {
30
- status: 200
31
- });
32
- } else if (matchPath(pathname, '/init')) {
33
- let ctx = {};
34
- try {
35
- ctx = 'createContext' in config ? await config.createContext({
36
- req: request
37
- }) : {};
38
- } catch (err) {
39
- throw new EdgeStoreError({
40
- message: 'Error creating context',
41
- code: 'CREATE_CONTEXT_ERROR',
42
- cause: err instanceof Error ? err : undefined
43
- });
44
- }
45
- const { newCookies, ...body } = await init({
46
- ctx,
47
- provider,
48
- router: config.router,
49
- cookieConfig
50
- });
51
- const headers = new Headers();
52
- newCookies.forEach((cookie)=>{
53
- headers.append('Set-Cookie', cookie);
54
- });
55
- headers.set('Content-Type', 'application/json');
56
- return new Response(JSON.stringify(body), {
57
- status: 200,
58
- headers
59
- });
60
- } else if (matchPath(pathname, '/request-upload')) {
61
- const body = await request.json();
62
- const ctxToken = getCookie(request, resolvedCookieConfig.ctx.name);
63
- const result = await requestUpload({
64
- provider,
65
- router: config.router,
66
- body: body,
67
- ctxToken
68
- });
69
- return new Response(JSON.stringify(result), {
70
- status: 200,
71
- headers: {
72
- 'Content-Type': 'application/json'
73
- }
74
- });
75
- } else if (matchPath(pathname, '/request-upload-parts')) {
76
- const body = await request.json();
77
- const ctxToken = getCookie(request, resolvedCookieConfig.ctx.name);
78
- const result = await requestUploadParts({
79
- provider,
80
- router: config.router,
81
- body: body,
82
- ctxToken
83
- });
84
- return new Response(JSON.stringify(result), {
85
- status: 200,
86
- headers: {
87
- 'Content-Type': 'application/json'
88
- }
89
- });
90
- } else if (matchPath(pathname, '/complete-multipart-upload')) {
91
- const body = await request.json();
92
- const ctxToken = getCookie(request, resolvedCookieConfig.ctx.name);
93
- await completeMultipartUpload({
94
- provider,
95
- router: config.router,
96
- body: body,
97
- ctxToken
98
- });
99
- return new Response(null, {
100
- status: 200
101
- });
102
- } else if (matchPath(pathname, '/confirm-upload')) {
103
- const body = await request.json();
104
- const ctxToken = getCookie(request, resolvedCookieConfig.ctx.name);
105
- const result = await confirmUpload({
106
- provider,
107
- router: config.router,
108
- body: body,
109
- ctxToken
110
- });
111
- return new Response(JSON.stringify(result), {
112
- status: 200,
113
- headers: {
114
- 'Content-Type': 'application/json'
115
- }
116
- });
117
- } else if (matchPath(pathname, '/delete-file')) {
118
- const body = await request.json();
119
- const ctxToken = getCookie(request, resolvedCookieConfig.ctx.name);
120
- const result = await deleteFile({
121
- provider,
122
- router: config.router,
123
- body: body,
124
- ctxToken
125
- });
126
- return new Response(JSON.stringify(result), {
127
- status: 200,
128
- headers: {
129
- 'Content-Type': 'application/json'
130
- }
131
- });
132
- } else if (matchPath(pathname, '/proxy-file')) {
133
- const urlParam = new URL(request.url).searchParams.get('url');
134
- if (typeof urlParam === 'string') {
135
- const proxyRes = await fetchProxyFile({
136
- cookieHeader: request.headers.get('cookie') ?? undefined,
137
- url: urlParam
138
- });
139
- const headers = new Headers();
140
- headers.set('Content-Type', proxyRes.contentType);
141
- return new Response(proxyRes.body, {
142
- headers,
143
- status: proxyRes.status
144
- });
145
- } else {
146
- return new Response(null, {
147
- status: 400
148
- });
149
- }
150
- } else {
151
- return new Response(null, {
152
- status: 404
153
- });
154
- }
155
- } catch (err) {
156
- if (err instanceof EdgeStoreError) {
157
- log[err.level](err.formattedMessage());
158
- if (err.cause) log[err.level](err.cause);
159
- const status = EDGE_STORE_ERROR_CODES[err.code] || 500;
160
- return new Response(JSON.stringify(err.formattedJson()), {
161
- status,
162
- headers: {
163
- 'Content-Type': 'application/json'
164
- }
165
- });
166
- }
167
- log.error(err);
168
- return new Response(JSON.stringify(new EdgeStoreError({
169
- message: 'Internal server error',
170
- code: 'SERVER_ERROR'
171
- }).formattedJson()), {
172
- status: 500,
173
- headers: {
174
- 'Content-Type': 'application/json'
175
- }
176
- });
177
- }
178
- };
179
- }
180
-
181
- export { createEdgeStoreStartHandler };