@edgestore/server 0.8.0 → 1.0.0-next.1
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/README.md +10 -4
- package/adapters/astro/index.d.ts +1 -1
- package/adapters/astro/index.js +1 -1
- package/adapters/express/index.d.ts +1 -1
- package/adapters/express/index.js +1 -1
- package/adapters/fastify/index.d.ts +1 -1
- package/adapters/fastify/index.js +1 -1
- package/adapters/hono/index.d.ts +1 -1
- package/adapters/hono/index.js +1 -1
- package/adapters/next/app/index.d.ts +1 -1
- package/adapters/next/app/index.js +1 -1
- package/adapters/next/pages/index.d.ts +1 -1
- package/adapters/next/pages/index.js +1 -1
- package/adapters/remix/index.d.ts +1 -1
- package/adapters/remix/index.js +1 -1
- package/adapters/start/index.d.ts +1 -1
- package/adapters/start/index.js +1 -1
- package/core/index.d.ts +1 -1
- package/core/index.js +1 -1
- package/dist/adapters/astro/index.d.ts +8 -13
- package/dist/adapters/astro/index.d.ts.map +1 -1
- package/dist/adapters/astro/index.js +17 -166
- package/dist/adapters/dispatcher.d.ts +30 -0
- package/dist/adapters/dispatcher.d.ts.map +1 -0
- package/dist/adapters/dispatcher.js +172 -0
- package/dist/adapters/express/index.d.ts +8 -13
- package/dist/adapters/express/index.d.ts.map +1 -1
- package/dist/adapters/express/index.js +27 -99
- package/dist/adapters/fastify/index.d.ts +8 -13
- package/dist/adapters/fastify/index.d.ts.map +1 -1
- package/dist/adapters/fastify/index.js +26 -126
- package/dist/adapters/hono/index.d.ts +8 -13
- package/dist/adapters/hono/index.d.ts.map +1 -1
- package/dist/adapters/hono/index.js +17 -126
- package/dist/adapters/imageTypes.js +1 -3
- package/dist/adapters/next/app/index.d.ts +8 -13
- package/dist/adapters/next/app/index.d.ts.map +1 -1
- package/dist/adapters/next/app/index.js +24 -153
- package/dist/adapters/next/pages/index.d.ts +8 -13
- package/dist/adapters/next/pages/index.d.ts.map +1 -1
- package/dist/adapters/next/pages/index.js +37 -100
- package/dist/adapters/remix/index.d.ts +8 -13
- package/dist/adapters/remix/index.d.ts.map +1 -1
- package/dist/adapters/remix/index.js +17 -141
- package/dist/adapters/shared.d.ts +140 -55
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/adapters/shared.js +218 -215
- package/dist/adapters/start/index.d.ts +8 -13
- package/dist/adapters/start/index.d.ts.map +1 -1
- package/dist/adapters/start/index.js +17 -174
- package/dist/core/client/bucketClient.d.ts +7 -0
- package/dist/core/client/bucketClient.d.ts.map +1 -0
- package/dist/core/client/bucketClient.js +312 -0
- package/dist/core/client/index.d.ts +119 -140
- package/dist/core/client/index.d.ts.map +1 -1
- package/dist/core/client/index.js +13 -220
- package/dist/core/index.d.ts +21 -2
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +14 -10
- package/dist/core/provider.d.ts +15 -0
- package/dist/core/provider.d.ts.map +1 -0
- package/dist/core/provider.js +25 -0
- package/dist/core/routerRules.d.ts +21 -0
- package/dist/core/routerRules.d.ts.map +1 -0
- package/dist/core/routerRules.js +54 -0
- package/dist/core/validateFile.d.ts +9 -0
- package/dist/core/validateFile.d.ts.map +1 -0
- package/dist/core/validateFile.js +43 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -10
- package/dist/libs/env.d.ts +3 -0
- package/dist/libs/env.d.ts.map +1 -0
- package/dist/libs/env.js +14 -0
- package/dist/libs/errors/EdgeStoreCredentialsError.js +1 -3
- package/dist/libs/logger.d.ts +2 -1
- package/dist/libs/logger.d.ts.map +1 -1
- package/dist/libs/logger.js +5 -9
- package/dist/libs/utils.js +1 -3
- package/dist/providers/azure-blob/index.d.ts +119 -0
- package/dist/providers/azure-blob/index.d.ts.map +1 -0
- package/dist/providers/azure-blob/index.js +166 -0
- package/dist/providers/edgestore/index.d.ts +171 -3
- package/dist/providers/edgestore/index.d.ts.map +1 -1
- package/dist/providers/edgestore/index.js +307 -141
- package/dist/providers/{aws → s3}/index.d.ts +68 -11
- package/dist/providers/s3/index.d.ts.map +1 -0
- package/dist/providers/s3/index.js +146 -0
- package/dist/test-utils/edgestoreSmoke.d.ts +0 -2
- package/dist/test-utils/edgestoreSmoke.d.ts.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.d.ts.map +1 -1
- package/package.json +58 -56
- package/providers/azure-blob/index.d.ts +1 -0
- package/providers/azure-blob/index.js +1 -0
- package/providers/edgestore/index.d.ts +1 -1
- package/providers/edgestore/index.js +1 -1
- package/providers/s3/index.d.ts +1 -0
- package/providers/s3/index.js +1 -0
- package/src/adapters/astro/index.ts +27 -211
- package/src/adapters/dispatcher.ts +261 -0
- package/src/adapters/express/index.ts +43 -149
- package/src/adapters/fastify/index.ts +43 -191
- package/src/adapters/hono/index.ts +28 -183
- package/src/adapters/next/app/index.ts +37 -201
- package/src/adapters/next/pages/index.ts +55 -156
- package/src/adapters/remix/index.ts +27 -190
- package/src/adapters/shared.ts +249 -274
- package/src/adapters/start/index.ts +28 -200
- package/src/core/client/bucketClient.ts +480 -0
- package/src/core/client/index.ts +300 -428
- package/src/core/index.ts +42 -1
- package/src/core/provider.ts +80 -0
- package/src/core/routerRules.ts +75 -0
- package/src/core/validateFile.ts +50 -0
- package/src/index.ts +10 -0
- package/src/libs/env.ts +16 -0
- package/src/libs/logger.ts +4 -2
- package/src/providers/azure-blob/index.ts +265 -0
- package/src/providers/edgestore/index.ts +426 -154
- package/src/providers/s3/index.ts +289 -0
- package/src/test-utils/edgestoreSmoke.ts +0 -11
- package/src/version.ts +1 -1
- package/dist/adapters/astro/index.mjs +0 -172
- package/dist/adapters/express/index.mjs +0 -108
- package/dist/adapters/fastify/index.mjs +0 -135
- package/dist/adapters/hono/index.mjs +0 -131
- package/dist/adapters/imageTypes.mjs +0 -12
- package/dist/adapters/next/app/index.mjs +0 -163
- package/dist/adapters/next/pages/index.mjs +0 -112
- package/dist/adapters/remix/index.mjs +0 -148
- package/dist/adapters/shared.mjs +0 -471
- package/dist/adapters/start/index.mjs +0 -181
- package/dist/core/client/index.mjs +0 -221
- package/dist/core/index.mjs +0 -2
- package/dist/core/sdk/index.d.ts +0 -282
- package/dist/core/sdk/index.d.ts.map +0 -1
- package/dist/core/sdk/index.js +0 -256
- package/dist/core/sdk/index.mjs +0 -253
- package/dist/index.mjs +0 -1
- package/dist/libs/errors/EdgeStoreCredentialsError.mjs +0 -10
- package/dist/libs/logger.mjs +0 -53
- package/dist/libs/utils.mjs +0 -10
- package/dist/providers/aws/index.d.ts.map +0 -1
- package/dist/providers/aws/index.js +0 -105
- package/dist/providers/aws/index.mjs +0 -103
- package/dist/providers/azure/index.d.ts +0 -39
- package/dist/providers/azure/index.d.ts.map +0 -1
- package/dist/providers/azure/index.js +0 -87
- package/dist/providers/azure/index.mjs +0 -85
- package/dist/providers/edgestore/index.mjs +0 -164
- package/dist/version.js +0 -7
- package/dist/version.mjs +0 -4
- package/providers/aws/index.d.ts +0 -1
- package/providers/aws/index.js +0 -1
- package/providers/azure/index.d.ts +0 -1
- package/providers/azure/index.js +0 -1
- package/src/core/sdk/index.ts +0 -549
- package/src/providers/aws/index.ts +0 -240
- package/src/providers/azure/index.ts +0 -142
package/src/core/index.ts
CHANGED
|
@@ -1,2 +1,43 @@
|
|
|
1
|
+
import type { AnyEdgeStoreProvider, AnyRouter } from '@edgestore/shared';
|
|
2
|
+
import { createBackendClient, type EdgeStoreClient } from './client';
|
|
3
|
+
|
|
1
4
|
export * from './client';
|
|
2
|
-
export
|
|
5
|
+
export {
|
|
6
|
+
defineProvider,
|
|
7
|
+
getProviderBaseUrl,
|
|
8
|
+
referenceFromUrl,
|
|
9
|
+
validateProviderCursor,
|
|
10
|
+
validateProviderReference,
|
|
11
|
+
} from './provider';
|
|
12
|
+
|
|
13
|
+
export type ConfiguredEdgeStore<
|
|
14
|
+
TRouter extends AnyRouter,
|
|
15
|
+
TProvider extends AnyEdgeStoreProvider,
|
|
16
|
+
> = {
|
|
17
|
+
router: TRouter;
|
|
18
|
+
provider: TProvider;
|
|
19
|
+
baseUrl?: string;
|
|
20
|
+
client: EdgeStoreClient<TRouter, TProvider>;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function createEdgeStore<
|
|
24
|
+
TRouter extends AnyRouter,
|
|
25
|
+
TProvider extends AnyEdgeStoreProvider,
|
|
26
|
+
>(config: {
|
|
27
|
+
router: TRouter;
|
|
28
|
+
provider: TProvider;
|
|
29
|
+
/**
|
|
30
|
+
* Application EdgeStore handler URL used to proxy protected files during
|
|
31
|
+
* local development.
|
|
32
|
+
*
|
|
33
|
+
* @example http://localhost:3000/api/edgestore
|
|
34
|
+
*/
|
|
35
|
+
baseUrl?: string;
|
|
36
|
+
}): ConfiguredEdgeStore<TRouter, TProvider> {
|
|
37
|
+
return {
|
|
38
|
+
router: config.router,
|
|
39
|
+
provider: config.provider,
|
|
40
|
+
baseUrl: config.baseUrl,
|
|
41
|
+
client: createBackendClient(config.router, config.provider, config.baseUrl),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AnyEdgeStoreProvider,
|
|
3
|
+
EdgeStoreProvider,
|
|
4
|
+
ProviderCursor,
|
|
5
|
+
ProviderReference,
|
|
6
|
+
} from '@edgestore/shared';
|
|
7
|
+
import type { StandardSchemaV1 } from '@standard-schema/spec';
|
|
8
|
+
|
|
9
|
+
export function defineProvider<
|
|
10
|
+
const TReferenceSchema extends StandardSchemaV1,
|
|
11
|
+
const TCursorSchema extends StandardSchemaV1 = StandardSchemaV1<
|
|
12
|
+
unknown,
|
|
13
|
+
string
|
|
14
|
+
>,
|
|
15
|
+
const TProvider extends EdgeStoreProvider<
|
|
16
|
+
TReferenceSchema,
|
|
17
|
+
StandardSchemaV1.InferOutput<TCursorSchema>
|
|
18
|
+
> = EdgeStoreProvider<
|
|
19
|
+
TReferenceSchema,
|
|
20
|
+
StandardSchemaV1.InferOutput<TCursorSchema>
|
|
21
|
+
>,
|
|
22
|
+
>(
|
|
23
|
+
provider: TProvider & {
|
|
24
|
+
reference: { schema: TReferenceSchema };
|
|
25
|
+
files: { cursorSchema?: TCursorSchema };
|
|
26
|
+
},
|
|
27
|
+
): TProvider {
|
|
28
|
+
return provider;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function getProviderBaseUrl(
|
|
32
|
+
provider: AnyEdgeStoreProvider,
|
|
33
|
+
): Promise<string> {
|
|
34
|
+
return typeof provider.baseUrl === 'function'
|
|
35
|
+
? await provider.baseUrl()
|
|
36
|
+
: provider.baseUrl;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function referenceFromUrl<TProvider extends AnyEdgeStoreProvider>(
|
|
40
|
+
provider: TProvider,
|
|
41
|
+
url: string,
|
|
42
|
+
): Promise<ProviderReference<TProvider>> {
|
|
43
|
+
return await validateProviderValue(
|
|
44
|
+
provider.reference.schema,
|
|
45
|
+
await provider.reference.fromUrl(url),
|
|
46
|
+
'file reference',
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function validateProviderReference<
|
|
51
|
+
TProvider extends AnyEdgeStoreProvider,
|
|
52
|
+
>(
|
|
53
|
+
provider: TProvider,
|
|
54
|
+
reference: unknown,
|
|
55
|
+
): Promise<ProviderReference<TProvider>> {
|
|
56
|
+
return await validateProviderValue(
|
|
57
|
+
provider.reference.schema,
|
|
58
|
+
reference,
|
|
59
|
+
'file reference',
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function validateProviderCursor<
|
|
64
|
+
TProvider extends AnyEdgeStoreProvider,
|
|
65
|
+
>(provider: TProvider, cursor: unknown): Promise<ProviderCursor<TProvider>> {
|
|
66
|
+
const schema = provider.files.cursorSchema;
|
|
67
|
+
if (!schema) return cursor as ProviderCursor<TProvider>;
|
|
68
|
+
return await validateProviderValue(schema, cursor, 'list cursor');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function validateProviderValue<TSchema extends StandardSchemaV1>(
|
|
72
|
+
schema: TSchema,
|
|
73
|
+
value: unknown,
|
|
74
|
+
label: string,
|
|
75
|
+
): Promise<StandardSchemaV1.InferOutput<TSchema>> {
|
|
76
|
+
const result = await schema['~standard'].validate(value);
|
|
77
|
+
if (!result.issues) return result.value;
|
|
78
|
+
const detail = result.issues.map((issue) => issue.message).join('; ');
|
|
79
|
+
throw new TypeError(`Invalid provider ${label}: ${detail}`);
|
|
80
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import {
|
|
2
|
+
EdgeStoreError,
|
|
3
|
+
type AnyBuilder,
|
|
4
|
+
type InferBucketPathObject,
|
|
5
|
+
type InferBucketPathOrder,
|
|
6
|
+
} from '@edgestore/shared';
|
|
7
|
+
import { ZodNever, type z } from 'zod';
|
|
8
|
+
|
|
9
|
+
export async function parseBucketInput<TBucket extends AnyBuilder>(
|
|
10
|
+
bucket: TBucket,
|
|
11
|
+
input: unknown,
|
|
12
|
+
): Promise<z.infer<TBucket['_def']['input']>> {
|
|
13
|
+
if (bucket._def.input instanceof ZodNever) {
|
|
14
|
+
return {} as z.infer<TBucket['_def']['input']>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
return await bucket._def.input.parseAsync(input);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
throw new EdgeStoreError({
|
|
21
|
+
message: 'Invalid bucket input',
|
|
22
|
+
code: 'BAD_REQUEST',
|
|
23
|
+
cause: error instanceof Error ? error : undefined,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function buildPath(params: {
|
|
29
|
+
bucket: AnyBuilder;
|
|
30
|
+
pathAttrs: {
|
|
31
|
+
ctx: unknown;
|
|
32
|
+
input: unknown;
|
|
33
|
+
};
|
|
34
|
+
}) {
|
|
35
|
+
const pathParams = params.bucket._def.path;
|
|
36
|
+
return pathParams.map((param) => {
|
|
37
|
+
const entry = Object.entries(param)[0];
|
|
38
|
+
if (!entry) {
|
|
39
|
+
throw new EdgeStoreError({
|
|
40
|
+
message: `Empty path param found in: ${JSON.stringify(pathParams)}`,
|
|
41
|
+
code: 'SERVER_ERROR',
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const [key, value] = entry;
|
|
45
|
+
const pathValue = value()
|
|
46
|
+
.split('.')
|
|
47
|
+
.reduce<unknown>((current, segment) => {
|
|
48
|
+
if (
|
|
49
|
+
typeof current !== 'object' ||
|
|
50
|
+
current === null ||
|
|
51
|
+
!(segment in current)
|
|
52
|
+
) {
|
|
53
|
+
throw new EdgeStoreError({
|
|
54
|
+
message: `Missing key ${segment} in ${JSON.stringify(current)}`,
|
|
55
|
+
code: 'BAD_REQUEST',
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
return (current as Record<string, unknown>)[segment];
|
|
59
|
+
}, params.pathAttrs);
|
|
60
|
+
|
|
61
|
+
return { key, value: pathValue as string };
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function parsePath<TBucket extends AnyBuilder>(
|
|
66
|
+
path: { key: string; value: string }[],
|
|
67
|
+
) {
|
|
68
|
+
return {
|
|
69
|
+
parsedPath: Object.fromEntries(path.map(({ key, value }) => [key, value])),
|
|
70
|
+
pathOrder: path.map(({ key }) => key),
|
|
71
|
+
} as {
|
|
72
|
+
parsedPath: InferBucketPathObject<TBucket>;
|
|
73
|
+
pathOrder: InferBucketPathOrder<TBucket>;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { EdgeStoreError, type AnyBuilder } from '@edgestore/shared';
|
|
2
|
+
import { IMAGE_MIME_TYPES } from '../adapters/imageTypes';
|
|
3
|
+
|
|
4
|
+
export function validateFileForBucket(params: {
|
|
5
|
+
bucket: AnyBuilder;
|
|
6
|
+
fileInfo: { size: number; type: string };
|
|
7
|
+
}) {
|
|
8
|
+
const { bucket, fileInfo } = params;
|
|
9
|
+
|
|
10
|
+
if (
|
|
11
|
+
bucket._def.type === 'IMAGE' &&
|
|
12
|
+
!IMAGE_MIME_TYPES.includes(fileInfo.type)
|
|
13
|
+
) {
|
|
14
|
+
throw new EdgeStoreError({
|
|
15
|
+
code: 'MIME_TYPE_NOT_ALLOWED',
|
|
16
|
+
message: 'Only images are allowed in this bucket',
|
|
17
|
+
details: {
|
|
18
|
+
allowedMimeTypes: IMAGE_MIME_TYPES,
|
|
19
|
+
mimeType: fileInfo.type,
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const maxSize = bucket._def.bucketConfig?.maxSize;
|
|
25
|
+
if (maxSize !== undefined && fileInfo.size > maxSize) {
|
|
26
|
+
throw new EdgeStoreError({
|
|
27
|
+
code: 'FILE_TOO_LARGE',
|
|
28
|
+
message: `File size is too big. Max size is ${maxSize}`,
|
|
29
|
+
details: { maxFileSize: maxSize, fileSize: fileInfo.size },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const accept = bucket._def.bucketConfig?.accept;
|
|
34
|
+
if (
|
|
35
|
+
accept &&
|
|
36
|
+
!accept.some((value) => matchesMimeType(fileInfo.type, value))
|
|
37
|
+
) {
|
|
38
|
+
throw new EdgeStoreError({
|
|
39
|
+
code: 'MIME_TYPE_NOT_ALLOWED',
|
|
40
|
+
message: `"${fileInfo.type}" is not allowed. Accepted types are ${JSON.stringify(accept)}`,
|
|
41
|
+
details: { allowedMimeTypes: accept, mimeType: fileInfo.type },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function matchesMimeType(mimeType: string, accepted: string) {
|
|
47
|
+
return accepted.endsWith('/*')
|
|
48
|
+
? mimeType.startsWith(accepted.slice(0, -1))
|
|
49
|
+
: mimeType === accepted;
|
|
50
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
1
|
export { initEdgeStore } from '@edgestore/shared';
|
|
2
|
+
export {
|
|
3
|
+
createEdgeStore,
|
|
4
|
+
defineProvider,
|
|
5
|
+
type ConfiguredEdgeStore,
|
|
6
|
+
type EdgeStoreClient,
|
|
7
|
+
type InferClientInputs,
|
|
8
|
+
type InferClientOutputs,
|
|
9
|
+
type InferClientResponse,
|
|
10
|
+
EdgeStoreFileMutationError,
|
|
11
|
+
} from './core';
|
package/src/libs/env.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function getEnv(key: string): string | undefined {
|
|
2
|
+
if (typeof process !== 'undefined' && process.env) {
|
|
3
|
+
// @ts-expect-error - In Vite/Astro, env variables are available on import.meta.
|
|
4
|
+
return process.env[key] ?? import.meta.env?.[key];
|
|
5
|
+
}
|
|
6
|
+
// @ts-expect-error - In Vite/Astro, env variables are available on import.meta.
|
|
7
|
+
return import.meta.env?.[key];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function isDev(): boolean {
|
|
11
|
+
return (
|
|
12
|
+
process?.env?.NODE_ENV === 'development' ||
|
|
13
|
+
// @ts-expect-error - In Vite/Astro, env variables are available on import.meta.
|
|
14
|
+
import.meta.env?.DEV
|
|
15
|
+
);
|
|
16
|
+
}
|
package/src/libs/logger.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
/* eslint-disable no-console */
|
|
2
2
|
|
|
3
|
-
import { isDev } from '
|
|
3
|
+
import { isDev } from './env';
|
|
4
4
|
|
|
5
5
|
const logLevel = ['debug', 'info', 'warn', 'error', 'none'] as const;
|
|
6
6
|
|
|
7
7
|
export type LogLevel = (typeof logLevel)[number];
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
export type LoggerLike = Pick<Console, 'debug' | 'info' | 'warn' | 'error'>;
|
|
10
|
+
|
|
11
|
+
class Logger implements LoggerLike {
|
|
10
12
|
private logLevel: LogLevel;
|
|
11
13
|
|
|
12
14
|
constructor(logLevel?: LogLevel) {
|
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
/* eslint-disable unicorn/filename-case -- The public provider entrypoint is `azure-blob`. */
|
|
2
|
+
import {
|
|
3
|
+
BlobSASPermissions,
|
|
4
|
+
BlobServiceClient,
|
|
5
|
+
generateBlobSASQueryParameters,
|
|
6
|
+
SASProtocol,
|
|
7
|
+
StorageSharedKeyCredential,
|
|
8
|
+
} from '@azure/storage-blob';
|
|
9
|
+
import { type RequestUploadParams } from '@edgestore/shared';
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import { defineProvider } from '../../core/provider';
|
|
12
|
+
import { getEnv } from '../../libs/env';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Options for the Azure provider. Compatible with Azure Blob Storage and Azurite.
|
|
16
|
+
* Use Azure Storage Explorer for local development with Azurite.
|
|
17
|
+
* @see https://azure.microsoft.com/de-de/products/storage/storage-explorer
|
|
18
|
+
* @category Providers
|
|
19
|
+
* @example
|
|
20
|
+
* azureBlob({
|
|
21
|
+
* storageAccountName: 'devstoreaccount1',
|
|
22
|
+
* storageAccountKey: 'some-account-key',
|
|
23
|
+
* containerName: 'some-container-name',
|
|
24
|
+
* customBaseUrl: 'http://localhost:10000/devstoreaccount1',
|
|
25
|
+
* })
|
|
26
|
+
*/
|
|
27
|
+
export type AzureBlobProviderOptions = {
|
|
28
|
+
/**
|
|
29
|
+
* The storage account name for Azure Blob Storage
|
|
30
|
+
* Can also be set via the `ES_AZURE_ACCOUNT_NAME` environment variable.
|
|
31
|
+
*/
|
|
32
|
+
storageAccountName?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Account key used to authenticate server-side operations and sign
|
|
35
|
+
* short-lived, blob-scoped URLs.
|
|
36
|
+
* Can also be set via the `ES_AZURE_ACCOUNT_KEY` environment variable.
|
|
37
|
+
*/
|
|
38
|
+
storageAccountKey?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Azure Blob Storage container name
|
|
41
|
+
* Can also be set via the `ES_AZURE_CONTAINER_NAME` environment variable.
|
|
42
|
+
*/
|
|
43
|
+
containerName?: string;
|
|
44
|
+
/**
|
|
45
|
+
* Optional base URL for the Azure Blob Storage.
|
|
46
|
+
* Useful for local development with Azurite. For example: `http://localhost:10000/devstoreaccount1`
|
|
47
|
+
* Can also be set via the `ES_AZURE_BASE_URL` environment variable.
|
|
48
|
+
*/
|
|
49
|
+
customBaseUrl?: string;
|
|
50
|
+
/**
|
|
51
|
+
* Lifetime of generated upload URLs in seconds.
|
|
52
|
+
* @default 3600
|
|
53
|
+
*/
|
|
54
|
+
uploadUrlExpiresIn?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Default lifetime of generated private read URLs in seconds.
|
|
57
|
+
* @default 3600
|
|
58
|
+
*/
|
|
59
|
+
signedUrlExpiresIn?: number;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export function azureBlob(options?: AzureBlobProviderOptions) {
|
|
63
|
+
const {
|
|
64
|
+
storageAccountName = getEnv('ES_AZURE_ACCOUNT_NAME'),
|
|
65
|
+
storageAccountKey = getEnv('ES_AZURE_ACCOUNT_KEY'),
|
|
66
|
+
containerName = getEnv('ES_AZURE_CONTAINER_NAME'),
|
|
67
|
+
customBaseUrl = getEnv('ES_AZURE_BASE_URL'),
|
|
68
|
+
uploadUrlExpiresIn = 60 * 60,
|
|
69
|
+
signedUrlExpiresIn = 60 * 60,
|
|
70
|
+
} = options ?? {};
|
|
71
|
+
|
|
72
|
+
if (!storageAccountName) {
|
|
73
|
+
throw new Error(
|
|
74
|
+
'Azure storageAccountName is not configured in AzureBlobProviderOptions.',
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
if (!storageAccountKey) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
'Azure storageAccountKey is not configured in AzureBlobProviderOptions.',
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (!containerName) {
|
|
83
|
+
throw new Error(
|
|
84
|
+
'Azure containerName is not configured in AzureBlobProviderOptions.',
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
const resolvedContainerName = containerName;
|
|
88
|
+
|
|
89
|
+
const baseUrl =
|
|
90
|
+
customBaseUrl ?? `https://${storageAccountName}.blob.core.windows.net`;
|
|
91
|
+
const sharedKeyCredential = new StorageSharedKeyCredential(
|
|
92
|
+
storageAccountName,
|
|
93
|
+
storageAccountKey,
|
|
94
|
+
);
|
|
95
|
+
const blobServiceClient = new BlobServiceClient(baseUrl, sharedKeyCredential);
|
|
96
|
+
const containerClient = blobServiceClient.getContainerClient(
|
|
97
|
+
resolvedContainerName,
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
function createSignedBlobUrl(params: {
|
|
101
|
+
blobName: string;
|
|
102
|
+
permissions: string;
|
|
103
|
+
expiresIn: number;
|
|
104
|
+
}) {
|
|
105
|
+
const expiresAt = new Date(Date.now() + params.expiresIn * 1000);
|
|
106
|
+
const sas = generateBlobSASQueryParameters(
|
|
107
|
+
{
|
|
108
|
+
containerName: resolvedContainerName,
|
|
109
|
+
blobName: params.blobName,
|
|
110
|
+
permissions: BlobSASPermissions.parse(params.permissions),
|
|
111
|
+
protocol: baseUrl.startsWith('https:')
|
|
112
|
+
? SASProtocol.Https
|
|
113
|
+
: SASProtocol.HttpsAndHttp,
|
|
114
|
+
startsOn: new Date(Date.now() - 5 * 60 * 1000),
|
|
115
|
+
expiresOn: expiresAt,
|
|
116
|
+
},
|
|
117
|
+
sharedKeyCredential,
|
|
118
|
+
).toString();
|
|
119
|
+
const blobClient = containerClient.getBlobClient(params.blobName);
|
|
120
|
+
return {
|
|
121
|
+
url: blobClient.url.split('?')[0]!,
|
|
122
|
+
signedUrl: `${blobClient.url.split('?')[0]}?${sas}`,
|
|
123
|
+
expiresAt,
|
|
124
|
+
expiresIn: params.expiresIn,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function getBlobNameFromUrl(url: string) {
|
|
129
|
+
try {
|
|
130
|
+
const blobUrl = new URL(url);
|
|
131
|
+
const containerUrl = new URL(containerClient.url);
|
|
132
|
+
const containerPath = containerUrl.pathname.replace(/\/$/, '');
|
|
133
|
+
|
|
134
|
+
if (blobUrl.origin !== containerUrl.origin) {
|
|
135
|
+
throw new Error();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
if (!blobUrl.pathname.startsWith(`${containerPath}/`)) {
|
|
139
|
+
throw new Error();
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return decodeURIComponent(
|
|
143
|
+
blobUrl.pathname.slice(containerPath.length + 1),
|
|
144
|
+
);
|
|
145
|
+
} catch {
|
|
146
|
+
throw new Error('File URL does not belong to this Azure Blob provider.');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function getBucketBlobName(edgestoreBucketName: string, url: string) {
|
|
151
|
+
const blobName = getBlobNameFromUrl(url);
|
|
152
|
+
if (!blobName.startsWith(`${edgestoreBucketName}/`)) {
|
|
153
|
+
throw new Error(
|
|
154
|
+
`File does not belong to EdgeStore bucket "${edgestoreBucketName}".`,
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return blobName;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function getBlobName(params: RequestUploadParams) {
|
|
161
|
+
const { bucketName: esBucketName, fileInfo } = params;
|
|
162
|
+
const extension = fileInfo.extension
|
|
163
|
+
? `.${fileInfo.extension.replace('.', '')}`
|
|
164
|
+
: '';
|
|
165
|
+
const fileName = fileInfo.fileName ?? `${crypto.randomUUID()}${extension}`;
|
|
166
|
+
|
|
167
|
+
return [
|
|
168
|
+
esBucketName,
|
|
169
|
+
...(fileInfo.isPublic ? ['_public'] : []),
|
|
170
|
+
...fileInfo.path.map((item) => item.value),
|
|
171
|
+
fileName,
|
|
172
|
+
].join('/');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return defineProvider({
|
|
176
|
+
name: 'azure-blob',
|
|
177
|
+
baseUrl,
|
|
178
|
+
reference: {
|
|
179
|
+
schema: z.object({ url: z.string() }),
|
|
180
|
+
fromUrl: (url) => ({ url }),
|
|
181
|
+
},
|
|
182
|
+
async init() {
|
|
183
|
+
return {};
|
|
184
|
+
},
|
|
185
|
+
uploads: {
|
|
186
|
+
async request(params) {
|
|
187
|
+
const blobName = getBlobName(params);
|
|
188
|
+
const uploadAccess = createSignedBlobUrl({
|
|
189
|
+
blobName,
|
|
190
|
+
permissions: 'cw',
|
|
191
|
+
expiresIn: uploadUrlExpiresIn,
|
|
192
|
+
});
|
|
193
|
+
const readAccess = params.fileInfo.isPublic
|
|
194
|
+
? undefined
|
|
195
|
+
: createSignedBlobUrl({
|
|
196
|
+
blobName,
|
|
197
|
+
permissions: 'r',
|
|
198
|
+
expiresIn: signedUrlExpiresIn,
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
uploadUrl: uploadAccess.signedUrl,
|
|
202
|
+
accessUrl: uploadAccess.url,
|
|
203
|
+
accessSignedUrl: readAccess?.signedUrl,
|
|
204
|
+
accessSignedUrlExpiresAt: readAccess?.expiresAt,
|
|
205
|
+
accessSignedUrlExpiresIn: readAccess?.expiresIn,
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
files: {
|
|
210
|
+
async get({ bucketName, file }) {
|
|
211
|
+
const blobClient = containerClient.getBlobClient(
|
|
212
|
+
getBucketBlobName(bucketName, file.url),
|
|
213
|
+
);
|
|
214
|
+
const { contentLength, lastModified } =
|
|
215
|
+
await blobClient.getProperties();
|
|
216
|
+
const timestamp = lastModified ?? new Date();
|
|
217
|
+
return {
|
|
218
|
+
url: blobClient.url.split('?')[0]!,
|
|
219
|
+
sizeBytes: contentLength ?? 0,
|
|
220
|
+
uploadedAt: timestamp,
|
|
221
|
+
updatedAt: timestamp,
|
|
222
|
+
};
|
|
223
|
+
},
|
|
224
|
+
async getSignedUrls({ bucketName, files, expiresIn }) {
|
|
225
|
+
return files.map((file) => {
|
|
226
|
+
const access = createSignedBlobUrl({
|
|
227
|
+
blobName: getBucketBlobName(bucketName, file.url),
|
|
228
|
+
permissions: 'r',
|
|
229
|
+
expiresIn: expiresIn ?? signedUrlExpiresIn,
|
|
230
|
+
});
|
|
231
|
+
return {
|
|
232
|
+
url: access.url,
|
|
233
|
+
signedUrl: access.signedUrl,
|
|
234
|
+
expiresAt: access.expiresAt,
|
|
235
|
+
expiresIn: access.expiresIn,
|
|
236
|
+
};
|
|
237
|
+
});
|
|
238
|
+
},
|
|
239
|
+
async delete({ bucketName, files }) {
|
|
240
|
+
const blobNames = files.map((file) =>
|
|
241
|
+
getBucketBlobName(bucketName, file.url),
|
|
242
|
+
);
|
|
243
|
+
const results = await Promise.all(
|
|
244
|
+
blobNames.map(async (blobName) => {
|
|
245
|
+
try {
|
|
246
|
+
const blobClient = containerClient.getBlobClient(blobName);
|
|
247
|
+
await blobClient.delete();
|
|
248
|
+
return { success: true as const };
|
|
249
|
+
} catch (error) {
|
|
250
|
+
return {
|
|
251
|
+
success: false as const,
|
|
252
|
+
error: {
|
|
253
|
+
code: 'DELETE_FAILED' as const,
|
|
254
|
+
message:
|
|
255
|
+
error instanceof Error ? error.message : 'Delete failed',
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
}),
|
|
260
|
+
);
|
|
261
|
+
return { results };
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
});
|
|
265
|
+
}
|