@dimah-s3/core 1.2.1 → 1.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/README.md +2 -2
- package/dist/error.d.ts +20 -24
- package/dist/error.d.ts.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -19
- package/dist/index.js.map +1 -1
- package/dist/plugin/create-s3-fetch.d.ts +2 -2
- package/dist/plugin/create-s3-fetch.d.ts.map +1 -1
- package/dist/plugin/types.d.ts +1 -1
- package/dist/schema/error.d.ts +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ pnpm add @dimah-s3/core
|
|
|
14
14
|
## Minimal setup
|
|
15
15
|
|
|
16
16
|
```ts
|
|
17
|
-
import { createS3Client,
|
|
17
|
+
import { createS3Client, APIError } from "@dimah-s3/core";
|
|
18
18
|
|
|
19
19
|
export const api = createS3Client({
|
|
20
20
|
// optional: auth for core routes + client plugins
|
|
@@ -25,7 +25,7 @@ export const api = createS3Client({
|
|
|
25
25
|
try {
|
|
26
26
|
await api.download({ route: "uploads", key });
|
|
27
27
|
} catch (err) {
|
|
28
|
-
if (err instanceof
|
|
28
|
+
if (err instanceof APIError)
|
|
29
29
|
console.error(err.statusCode, err.code, err.message);
|
|
30
30
|
}
|
|
31
31
|
```
|
package/dist/error.d.ts
CHANGED
|
@@ -1,37 +1,33 @@
|
|
|
1
|
-
import { APIError } from "better-call/error";
|
|
1
|
+
import { APIError as BetterCallAPIError } from "better-call/error";
|
|
2
2
|
import { type S3ErrorCode } from "./error-codes";
|
|
3
3
|
export { defineErrorCodes, S3_ERROR_CODES, type S3ErrorCode, } from "./error-codes";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
code?: string;
|
|
4
|
+
type NamedStatus = ConstructorParameters<typeof BetterCallAPIError>[0];
|
|
5
|
+
type APIErrorStatus = NamedStatus | number;
|
|
6
|
+
type APIErrorBody = ConstructorParameters<typeof BetterCallAPIError>[1] & {
|
|
7
|
+
params?: Record<string, string | number>;
|
|
9
8
|
cause?: unknown;
|
|
10
|
-
params?: DimahS3ErrorParams;
|
|
11
|
-
} & Record<string, unknown>;
|
|
12
|
-
type RawError = {
|
|
13
|
-
code: string;
|
|
14
|
-
message: string;
|
|
15
|
-
params?: DimahS3ErrorParams;
|
|
16
9
|
};
|
|
17
10
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
11
|
+
* better-call `APIError` — same name and `(status, body)` constructor as
|
|
12
|
+
* `ctx.error(...)`. HTTP serializes `{ message, code?, params? }` via native
|
|
13
|
+
* `toResponse`.
|
|
21
14
|
*/
|
|
22
|
-
export declare class
|
|
23
|
-
constructor(status?:
|
|
15
|
+
export declare class APIError extends BetterCallAPIError {
|
|
16
|
+
constructor(status?: APIErrorStatus, body?: APIErrorBody, headers?: HeadersInit);
|
|
24
17
|
get code(): string | undefined;
|
|
25
|
-
get params():
|
|
18
|
+
get params(): Record<string, string | number> | undefined;
|
|
26
19
|
/** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */
|
|
27
|
-
static from(status:
|
|
28
|
-
|
|
20
|
+
static from(status: APIErrorStatus, error: {
|
|
21
|
+
code: string;
|
|
22
|
+
message: string;
|
|
23
|
+
params?: Record<string, string | number>;
|
|
24
|
+
}): APIError;
|
|
25
|
+
static fromStatus(status: APIErrorStatus, body?: APIErrorBody): APIError;
|
|
29
26
|
}
|
|
30
|
-
/** True for {@link
|
|
27
|
+
/** True for {@link APIError} and better-call copies (including duck-typed). */
|
|
31
28
|
export declare function isAPIError(error: unknown): error is APIError;
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
export declare function isS3ErrorCode<C extends S3ErrorCode>(error: unknown, code: C): error is DimahS3Error & {
|
|
29
|
+
/** True when `error` is an {@link APIError} with this catalog `code`. */
|
|
30
|
+
export declare function isS3ErrorCode<C extends S3ErrorCode>(error: unknown, code: C): error is APIError & {
|
|
35
31
|
code: C;
|
|
36
32
|
};
|
|
37
33
|
//# sourceMappingURL=error.d.ts.map
|
package/dist/error.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,IAAI,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AACnE,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EACL,gBAAgB,EAChB,cAAc,EACd,KAAK,WAAW,GACjB,MAAM,eAAe,CAAC;AAEvB,KAAK,WAAW,GAAG,qBAAqB,CAAC,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,CAAC;AACvE,KAAK,cAAc,GAAG,WAAW,GAAG,MAAM,CAAC;AAC3C,KAAK,YAAY,GAAG,qBAAqB,CAAC,OAAO,kBAAkB,CAAC,CAAC,CAAC,CAAC,GAAG;IACxE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;IACzC,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF;;;;GAIG;AACH,qBAAa,QAAS,SAAQ,kBAAkB;IAC9C,YACE,MAAM,GAAE,cAA8B,EACtC,IAAI,CAAC,EAAE,YAAY,EACnB,OAAO,CAAC,EAAE,WAAW,EAYtB;IAED,IAAI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IAED,IAAI,MAAM,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,SAAS,CAExD;IAED,2EAA2E;IAC3E,MAAM,CAAC,IAAI,CACT,MAAM,EAAE,cAAc,EACtB,KAAK,EAAE;QACL,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAC;KAC1C,GACA,QAAQ,CAMV;IAED,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,cAAc,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,QAAQ,CAEvE;CACF;AAED,+EAA+E;AAC/E,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,QAAQ,CAM5D;AAED,yEAAyE;AACzE,wBAAgB,aAAa,CAAC,CAAC,SAAS,WAAW,EACjD,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,CAAC,GACN,KAAK,IAAI,QAAQ,GAAG;IAAE,IAAI,EAAE,CAAC,CAAA;CAAE,CAEjC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export * from "./types";
|
|
2
2
|
export * from "./helpers";
|
|
3
3
|
export * from "./schema";
|
|
4
|
-
export {
|
|
4
|
+
export { APIError, defineErrorCodes, isAPIError, isS3ErrorCode, S3_ERROR_CODES, type S3ErrorCode, } from "./error";
|
|
5
5
|
export { S3_API_BASE_PATH, normalizeS3ApiBasePath, S3_API_ROUTES, } from "./routes";
|
|
6
6
|
export { createS3Client, type CreateS3ClientOptions, type CreateS3ClientResult, } from "./create-s3-client";
|
|
7
7
|
export { createS3Fetch, defineClientPlugin, pluginPath, RESERVED_CLIENT_KEYS, } from "./plugin";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,OAAO,EACL,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,OAAO,EACL,QAAQ,EACR,gBAAgB,EAChB,UAAU,EACV,aAAa,EACb,cAAc,EACd,KAAK,WAAW,GACjB,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,gBAAgB,EAChB,sBAAsB,EACtB,aAAa,GACd,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,cAAc,EACd,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,GAC1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,UAAU,EACV,oBAAoB,GACrB,MAAM,UAAU,CAAC;AAClB,YAAY,EACV,sBAAsB,EACtB,iBAAiB,EACjB,oBAAoB,EACpB,cAAc,EACd,OAAO,GACR,MAAM,UAAU,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as z3 from 'zod';
|
|
2
|
-
import { APIError } from 'better-call/error';
|
|
2
|
+
import { APIError as APIError$1 } from 'better-call/error';
|
|
3
3
|
import { createFetch } from '@better-fetch/fetch';
|
|
4
4
|
|
|
5
5
|
// src/helpers/validate-file.ts
|
|
@@ -346,11 +346,15 @@ var S3_ERROR_CODES = defineErrorCodes({
|
|
|
346
346
|
});
|
|
347
347
|
|
|
348
348
|
// src/error.ts
|
|
349
|
-
var
|
|
349
|
+
var APIError = class _APIError extends APIError$1 {
|
|
350
350
|
constructor(status = "BAD_REQUEST", body, headers) {
|
|
351
351
|
const { cause, ...rest } = body ?? {};
|
|
352
|
-
super(
|
|
353
|
-
|
|
352
|
+
super(
|
|
353
|
+
status,
|
|
354
|
+
Object.keys(rest).length > 0 ? rest : void 0,
|
|
355
|
+
headers
|
|
356
|
+
);
|
|
357
|
+
this.name = "APIError";
|
|
354
358
|
if (cause !== void 0) {
|
|
355
359
|
this.cause = cause;
|
|
356
360
|
}
|
|
@@ -363,26 +367,21 @@ var DimahS3Error = class _DimahS3Error extends APIError {
|
|
|
363
367
|
}
|
|
364
368
|
/** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */
|
|
365
369
|
static from(status, error) {
|
|
366
|
-
return new
|
|
370
|
+
return new _APIError(status, {
|
|
367
371
|
message: error.message,
|
|
368
372
|
code: error.code,
|
|
369
373
|
...error.params !== void 0 ? { params: error.params } : {}
|
|
370
374
|
});
|
|
371
375
|
}
|
|
372
376
|
static fromStatus(status, body) {
|
|
373
|
-
return new
|
|
377
|
+
return new _APIError(status, body);
|
|
374
378
|
}
|
|
375
379
|
};
|
|
376
380
|
function isAPIError(error) {
|
|
377
|
-
|
|
378
|
-
const name = error?.name;
|
|
379
|
-
return name === "APIError" || name === "DimahS3Error";
|
|
380
|
-
}
|
|
381
|
-
function isDimahS3Error(error) {
|
|
382
|
-
return error instanceof DimahS3Error || error?.name === "DimahS3Error";
|
|
381
|
+
return error instanceof APIError$1 || error instanceof APIError || error?.name === "APIError";
|
|
383
382
|
}
|
|
384
383
|
function isS3ErrorCode(error, code) {
|
|
385
|
-
return
|
|
384
|
+
return isAPIError(error) && error.code === code;
|
|
386
385
|
}
|
|
387
386
|
|
|
388
387
|
// src/routes.ts
|
|
@@ -415,18 +414,17 @@ function fallbackMessage(error) {
|
|
|
415
414
|
}
|
|
416
415
|
return error.statusText || "Request failed";
|
|
417
416
|
}
|
|
418
|
-
function
|
|
419
|
-
const status = error.status;
|
|
417
|
+
function apiErrorFromFetch(error) {
|
|
420
418
|
const parsed = s3FetchErrorSchema.safeParse(error);
|
|
421
419
|
if (parsed.success) {
|
|
422
420
|
const { message, code, params } = parsed.data;
|
|
423
|
-
return new
|
|
421
|
+
return new APIError(error.status, {
|
|
424
422
|
message,
|
|
425
423
|
...code !== void 0 ? { code } : {},
|
|
426
424
|
...params !== void 0 ? { params } : {}
|
|
427
425
|
});
|
|
428
426
|
}
|
|
429
|
-
return new
|
|
427
|
+
return new APIError(error.status, { message: fallbackMessage(error) });
|
|
430
428
|
}
|
|
431
429
|
function createS3Fetch(base, options) {
|
|
432
430
|
return createFetch({
|
|
@@ -445,7 +443,7 @@ function createS3Fetch(base, options) {
|
|
|
445
443
|
return { ...ctx, headers };
|
|
446
444
|
},
|
|
447
445
|
onError: (ctx) => {
|
|
448
|
-
throw
|
|
446
|
+
throw apiErrorFromFetch(ctx.error);
|
|
449
447
|
}
|
|
450
448
|
});
|
|
451
449
|
}
|
|
@@ -592,6 +590,6 @@ function createS3Client(options) {
|
|
|
592
590
|
};
|
|
593
591
|
}
|
|
594
592
|
|
|
595
|
-
export {
|
|
593
|
+
export { APIError, DELETE_BATCH_MAX_KEYS, RESERVED_CLIENT_KEYS, ROUTE_NAME_PATTERN, S3_API_BASE_PATH, S3_API_ROUTES, S3_DEFAULT_EXPIRES_IN, S3_ERROR_CODES, S3_MAX_EXPIRES_IN, S3_MAX_METADATA_ENTRIES, S3_MAX_OBJECT_KEY_LENGTH, S3_MAX_PART_NUMBER, S3_MAX_POST_OBJECT_BYTES, buildContentDisposition, buildObjectKey, buildPublicObjectUrl, confirmBodySchema, createS3Client, createS3Fetch, defineClientPlugin, defineErrorCodes, deleteBatchBodySchema, deleteQuerySchema, downloadDispositionSchema, downloadModeSchema, downloadQuerySchema, fileNameFromKey, fileQuerySchema, formatFileSize, isAPIError, isS3ErrorCode, matchesFileTypes, matchesMagicBytes, metadataSchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartCompletedPartSchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, normalizeObjectKey, normalizeS3ApiBasePath, objectKeySchema, optionalChecksumSchema, optionalTrimmedString, parseFileName, partNumberSchema, pluginPath, resolveStoredFileName, routeCatalogEntrySchema, routeCatalogResponseSchema, routeNameSchema, s3ErrorParamsSchema, s3FetchErrorSchema, s3ObjectAclSchema, sanitizeFileName, sha256Base64, sha256ChecksumSchema, sha256File, sniffContentType, trimmedString, truncateFileName, uploadBodySchema, validateFile };
|
|
596
594
|
//# sourceMappingURL=index.js.map
|
|
597
595
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/helpers/validate-file.ts","../src/helpers/build-object-key.ts","../src/helpers/parse-file-name.ts","../src/helpers/format-file-size.ts","../src/helpers/build-content-disposition.ts","../src/helpers/sanitize-file-name.ts","../src/helpers/truncate-file-name.ts","../src/helpers/normalize-object-key.ts","../src/helpers/checksum.ts","../src/helpers/magic-bytes.ts","../src/helpers/public-object-url.ts","../src/schema/shared.ts","../src/schema/upload.ts","../src/schema/catalog.ts","../src/schema/download.ts","../src/schema/delete.ts","../src/schema/file.ts","../src/schema/multipart.ts","../src/schema/error.ts","../src/error-codes.ts","../src/error.ts","../src/routes.ts","../src/plugin/create-s3-fetch.ts","../src/plugin/define-client-plugin.ts","../src/plugin/plugin-path.ts","../src/plugin/types.ts","../src/create-s3-client.ts"],"names":["z","z2","z4","z5","z6","z7","z8"],"mappings":";;;;;AAiBO,SAAS,gBAAA,CACd,QAAA,EACA,WAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,SAAA,CAAU,MAAA,EAAQ,OAAO,IAAA;AAC9B,EAAA,MAAM,OAAO,WAAA,IAAe,EAAA;AAC5B,EAAA,OAAO,SAAA,CAAU,IAAA,CAAK,CAAC,KAAA,KAAU;AAC/B,IAAA,IAAI,KAAA,CAAM,UAAA,CAAW,GAAG,CAAA,EAAG;AACzB,MAAA,OAAO,SAAS,WAAA,EAAY,CAAE,QAAA,CAAS,KAAA,CAAM,aAAa,CAAA;AAAA,IAC5D;AACA,IAAA,IAAI,KAAA,CAAM,QAAA,CAAS,IAAI,CAAA,EAAG;AACxB,MAAA,OAAO,KAAK,UAAA,CAAW,KAAA,CAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA;AAAA,IACjD;AACA,IAAA,OAAO,IAAA,KAAS,KAAA;AAAA,EAClB,CAAC,C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AA6BO,SAAS,eACd,OAAA,EACyB;AACzB,EAAA,MAAM,EAAE,UAAU,OAAA,EAAS,OAAA,EAAS,GAAG,YAAA,EAAa,GAAI,WAAW,EAAC;AACpE,EAAA,MAAM,IAAA,GAAO,sBAAA,CAAuB,OAAA,IAAW,QAAA,IAAY,gBAAgB,CAAA;AAC3E,EAAA,MAAM,MAAA,GAAS,aAAA,CAAc,IAAA,EAAM,YAAY,CAAA;AAE/C,EAAA,MAAM,GAAA,GAAM,cAAc,MAAM,CAAA;AAEhC,EAAA,MAAM,gBAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,MAAA,IAAU,OAAA,IAAW,EAAC,EAAG;AAClC,IAAA,IAAK,oBAAA,CAA2C,QAAA,CAAS,MAAA,CAAO,EAAE,CAAA,EAAG;AACnE,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,kBAAA,EAAqB,OAAO,EAAE,CAAA,+BAAA;AAAA,OAChC;AAAA,IACF;AACA,IAAA,IAAI,MAAA,CAAO,MAAM,aAAA,EAAe;AAC9B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+B,MAAA,CAAO,EAAE,CAAA,EAAA,CAAI,CAAA;AAAA,IAC9D;AACA,IAAA,aAAA,CAAc,MAAA,CAAO,EAAE,CAAA,GAAI,MAAA,CAAO,WAAW,MAAM,CAAA;AAAA,EACrD;AAEA,EAAA,OAAO;AAAA,IACL,GAAG,GAAA;AAAA,IACH,GAAG,aAAA;AAAA,IACH,YAAA,EAAc,cAAA;AAAA,IACd,MAAA;AAAA,IACA,QAAQ;AAAC,GACX;AACF","file":"index.js","sourcesContent":["/** Machine-readable codes for client-side file validation failures. */\nexport type ValidateFileErrorCode =\n \"FILE_TYPE_NOT_ALLOWED\" | \"FILE_EMPTY\" | \"FILE_TOO_LARGE\";\n\n/** Result of {@link validateFile} when the file fails a check. */\nexport type ValidateFileError = {\n code: ValidateFileErrorCode;\n /** English fallback message (localize via Fuma when a translator is available). */\n message: string;\n /** Interpolation params for i18n (e.g. `{ type }`, `{ size }`). */\n params?: Record<string, string | number>;\n};\n\n/**\n * Whether `fileName` / `contentType` match HTML `accept` / route `fileTypes`\n * tokens (`image/*`, `application/pdf`, `.png`).\n */\nexport function matchesFileTypes(\n fileName: string,\n contentType: string | undefined,\n fileTypes: readonly string[],\n): boolean {\n if (!fileTypes.length) return true;\n const type = contentType ?? \"\";\n return fileTypes.some((token) => {\n if (token.startsWith(\".\")) {\n return fileName.toLowerCase().endsWith(token.toLowerCase());\n }\n if (token.endsWith(\"/*\")) {\n return type.startsWith(token.replace(\"/*\", \"/\"));\n }\n return type === token;\n });\n}\n\n/**\n * Client-side accept / size / empty checks before starting an upload.\n * Returns `null` when the file is valid.\n */\nexport function validateFile(\n file: File,\n options: { accept?: string[]; maxFileSize?: number },\n): ValidateFileError | null {\n if (options.accept?.length) {\n if (!matchesFileTypes(file.name, file.type, options.accept)) {\n const ext = file.name.includes(\".\") ? file.name.split(\".\").pop() : null;\n const type = ext ? `.${ext}` : file.type || \"unknown\";\n return {\n code: \"FILE_TYPE_NOT_ALLOWED\",\n message: `File type \"${type}\" is not allowed`,\n params: { type },\n };\n }\n }\n\n if (file.size === 0) {\n return {\n code: \"FILE_EMPTY\",\n message: \"File is empty\",\n };\n }\n\n if (\n typeof options.maxFileSize === \"number\" &&\n file.size > options.maxFileSize\n ) {\n const maxMB = (options.maxFileSize / (1024 * 1024)).toFixed(1);\n return {\n code: \"FILE_TOO_LARGE\",\n message: `File size exceeds ${maxMB} MB limit`,\n params: { size: `${maxMB} MB` },\n };\n }\n\n return null;\n}\n","export function buildObjectKey(...parts: string[]): string {\n return parts\n .map((p) => p.replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean)\n .join(\"/\");\n}\n","export function parseFileName(\n contentDisposition: string | null | undefined,\n): string | undefined {\n if (!contentDisposition) return undefined;\n\n const utf8Match = contentDisposition.match(/filename\\*=UTF-8''([^;,\\s]+)/i);\n if (utf8Match) {\n try {\n return decodeURIComponent(utf8Match[1]);\n } catch {\n /* ignore malformed encoding */\n }\n }\n\n const asciiMatch = contentDisposition.match(/filename=\"([^\"]*)\"/i);\n return asciiMatch?.[1];\n}\n\n/** Last path segment of an object key (`uploads/uuid/a.png` → `a.png`). */\nexport function fileNameFromKey(key: string): string | undefined {\n return key\n .split(\"/\")\n .filter((part) => part.length > 0)\n .at(-1);\n}\n\n/**\n * Filename from `Content-Disposition`, falling back to the object key leaf.\n * Used after HeadObject when the disposition header is missing.\n */\nexport function resolveStoredFileName(\n contentDisposition: string | null | undefined,\n key: string,\n): string | undefined {\n return parseFileName(contentDisposition) ?? fileNameFromKey(key);\n}\n","export function formatFileSize(bytes: number): string {\n if (!Number.isFinite(bytes) || bytes <= 0) return \"0 B\";\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"] as const;\n const i = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1,\n );\n const size = bytes / 1024 ** i;\n return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n}\n","export type ContentDispositionType = \"inline\" | \"attachment\";\n\n/**\n * Builds a RFC 6266 `Content-Disposition` value.\n *\n * Includes both the ASCII-safe `filename` fallback and the RFC 5987\n * `filename*` parameter for full Unicode support.\n */\nexport function buildContentDisposition(\n fileName: string,\n type: ContentDispositionType = \"attachment\",\n): string {\n const ascii = fileName.replace(/[^\\x20-\\x7E]/g, \"_\").replace(/[\"\\\\]/g, \"_\");\n const encoded = encodeURIComponent(fileName);\n return `${type}; filename=\"${ascii}\"; filename*=UTF-8''${encoded}`;\n}\n","/** Sanitizes a file name for Content-Disposition, query params, and object keys. */\nexport function sanitizeFileName(fileName: string): string {\n return fileName.replace(/[\"\\\\\\r\\n\\0]/g, \"_\");\n}\n","/**\n * Truncates a filename while preserving the extension when possible.\n */\nexport function truncateFileName(name: string, maxChars = 48): string {\n if (name.length <= maxChars) return name;\n const dotIndex = name.lastIndexOf(\".\");\n if (dotIndex <= 0) {\n return name.slice(0, maxChars - 1) + \"…\";\n }\n const ext = name.slice(dotIndex);\n const available = maxChars - ext.length - 1;\n if (available <= 0) {\n return name.slice(0, maxChars - 1) + \"…\";\n }\n return name.slice(0, available) + \"… \" + ext;\n}\n","/** S3 object key maximum (1024 bytes). */\nexport const S3_MAX_OBJECT_KEY_LENGTH = 1024;\n\n/**\n * Strip leading/trailing slashes and reject `.` / `..` / empty segments,\n * NUL, backslashes, and oversized keys. Returns `null` when the key is unsafe.\n */\nexport function normalizeObjectKey(key: string): string | null {\n const trimmed = key.replace(/^\\/+/u, \"\").replace(/\\/+$/u, \"\");\n if (!trimmed) return null;\n if (trimmed.length > S3_MAX_OBJECT_KEY_LENGTH) return null;\n if (trimmed.includes(\"\\\\\") || trimmed.includes(\"\\0\")) return null;\n const parts = trimmed.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n return null;\n }\n return parts.join(\"/\");\n}\n","/** SHA-256 digest as unpadded base64 (S3 `ChecksumSHA256`). */\nexport async function sha256Base64(data: BufferSource): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", data);\n const bytes = new Uint8Array(digest);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/=+$/, \"\");\n}\n\n/** SHA-256 of a `Blob` / `File` as unpadded base64. */\nexport async function sha256File(file: Blob): Promise<string> {\n return sha256Base64(await file.arrayBuffer());\n}\n","type MagicMatch = {\n mime: string;\n bytes: number[];\n offset?: number;\n};\n\nconst MAGIC: readonly MagicMatch[] = [\n { mime: \"image/png\", bytes: [0x89, 0x50, 0x4e, 0x47] },\n { mime: \"image/jpeg\", bytes: [0xff, 0xd8, 0xff] },\n { mime: \"image/gif\", bytes: [0x47, 0x49, 0x46, 0x38] },\n { mime: \"image/webp\", bytes: [0x52, 0x49, 0x46, 0x46], offset: 0 },\n { mime: \"application/pdf\", bytes: [0x25, 0x50, 0x44, 0x46] },\n { mime: \"application/zip\", bytes: [0x50, 0x4b, 0x03, 0x04] },\n { mime: \"video/webm\", bytes: [0x1a, 0x45, 0xdf, 0xa3] },\n];\n\nfunction prefixEquals(\n bytes: Uint8Array,\n expected: readonly number[],\n offset = 0,\n): boolean {\n if (bytes.length < offset + expected.length) return false;\n return expected.every((value, i) => bytes[offset + i] === value);\n}\n\n/**\n * Sniff a MIME type from the start of a file. Returns `undefined` when\n * the prefix is unknown — this is not a substitute for `fileTypes`.\n */\nexport function sniffContentType(bytes: Uint8Array): string | undefined {\n if (prefixEquals(bytes, [0x52, 0x49, 0x46, 0x46]) && bytes.length >= 12) {\n const tag = String.fromCharCode(bytes[8], bytes[9], bytes[10], bytes[11]);\n if (tag === \"WEBP\") return \"image/webp\";\n }\n for (const entry of MAGIC) {\n if (entry.mime === \"image/webp\") continue;\n if (prefixEquals(bytes, entry.bytes, entry.offset)) return entry.mime;\n }\n return undefined;\n}\n\n/**\n * Whether `bytes` match `expected` (exact MIME or `image/*`).\n * Unknown prefixes return `false`.\n */\nexport function matchesMagicBytes(\n bytes: Uint8Array,\n expected: string,\n): boolean {\n const sniffed = sniffContentType(bytes);\n if (!sniffed) return false;\n if (expected.endsWith(\"/*\")) {\n return sniffed.startsWith(expected.replace(\"/*\", \"/\"));\n }\n return sniffed === expected;\n}\n","/**\n * Join a public origin (CDN or virtual-hosted S3) with an object key.\n * Does not sign — only for `public-read` objects or a fronting CDN.\n */\nexport function buildPublicObjectUrl(options: {\n /** Origin with no trailing slash, e.g. `https://cdn.example.com`. */\n baseUrl: string;\n key: string;\n}): string {\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const path = options.key\n .split(\"/\")\n .filter((part) => part.length > 0)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n return `${base}/${path}`;\n}\n","import * as z from \"zod\";\nimport {\n normalizeObjectKey,\n S3_MAX_OBJECT_KEY_LENGTH,\n} from \"@/helpers/normalize-object-key\";\n\n/** Fallback when the route omits `expiresIn`. */\nexport const S3_DEFAULT_EXPIRES_IN = 600;\n\n/** AWS SigV4 presign maximum (7 days), in seconds. */\nexport const S3_MAX_EXPIRES_IN = 604_800;\n\n/** S3 POST object maximum (5 GiB), in bytes. */\nexport const S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;\n\n/** S3 multipart part number maximum. */\nexport const S3_MAX_PART_NUMBER = 10_000;\n\n/** Max user-defined metadata entries on an upload body. */\nexport const S3_MAX_METADATA_ENTRIES = 32;\n\n/** Named file-route identifier (`avatars`, `uploads`, …). */\nexport const ROUTE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;\n\n/** Non-empty trimmed string. */\nexport const trimmedString = z.string().trim().min(1);\n\n/** Optional trimmed string. Blank or whitespace-only values are omitted. */\nexport const optionalTrimmedString = z.preprocess((value: unknown) => {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n return trimmed === \"\" ? undefined : trimmed;\n}, z.string().optional());\n\nexport const routeNameSchema = trimmedString.regex(\n ROUTE_NAME_PATTERN,\n \"Invalid route name\",\n);\n\n/** Stored object key — normalized, no `.` / `..` / NUL / backslash segments. */\nexport const objectKeySchema = trimmedString\n .max(S3_MAX_OBJECT_KEY_LENGTH)\n .transform((value, ctx) => {\n const normalized = normalizeObjectKey(value);\n if (normalized == null) {\n ctx.issues.push({\n code: \"custom\",\n message: \"Invalid object key\",\n input: value,\n });\n return z.NEVER;\n }\n return normalized;\n });\n\n/** 1-based S3 multipart part number. */\nexport const partNumberSchema = z.int().min(1).max(S3_MAX_PART_NUMBER);\n\nexport const s3ObjectAclSchema = z.enum([\"private\", \"public-read\"]);\n\n/**\n * S3 `ChecksumSHA256` — 32-byte SHA-256 as standard base64 (padding optional).\n * Matches `sha256Base64()` output and the padded form AWS also accepts.\n */\nexport const sha256ChecksumSchema = z.stringFormat(\n \"sha256-base64\",\n /^[A-Za-z0-9+/]{43}=?$/,\n);\n\n/** Optional checksum; blank / whitespace-only values are omitted. */\nexport const optionalChecksumSchema = optionalTrimmedString.pipe(\n sha256ChecksumSchema.optional(),\n);\n\nconst metadataKeySchema = z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/i, \"Invalid metadata key\")\n .max(128);\n\nexport const metadataSchema = z\n .record(metadataKeySchema, z.string().max(2048))\n .refine((value) => Object.keys(value).length <= S3_MAX_METADATA_ENTRIES, {\n message: \"Too many metadata entries\",\n });\n","import * as z from \"zod\";\nimport {\n metadataSchema,\n objectKeySchema,\n optionalChecksumSchema,\n optionalTrimmedString,\n routeNameSchema,\n trimmedString,\n} from \"./shared\";\n\nexport const uploadBodySchema = z.strictObject({\n route: routeNameSchema,\n fileName: trimmedString,\n fileSize: z.int().positive(),\n contentType: optionalTrimmedString,\n metadata: metadataSchema.optional(),\n /** Unpadded base64 SHA-256. Required when the route sets `upload.checksum`. */\n checksum: optionalChecksumSchema,\n});\n\nexport const confirmBodySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n});\n","import * as z from \"zod\";\nimport type { S3RouteName } from \"@/types/routes\";\nimport { routeNameSchema } from \"./shared\";\n\nexport const downloadDispositionSchema = z.enum([\"inline\", \"attachment\"]);\nexport const downloadModeSchema = z.enum([\"presign\", \"proxy\"]);\n\nexport const routeCatalogUploadSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({\n enabled: z.literal(true),\n fileTypes: z.array(z.string()).optional(),\n maxFileSize: z.int().positive().optional(),\n multipart: z.boolean(),\n checksum: z.boolean().optional(),\n replace: z.literal(\"overwrite\").optional(),\n }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogDownloadSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({\n enabled: z.literal(true),\n disposition: downloadDispositionSchema.optional(),\n mode: downloadModeSchema.optional(),\n }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogDeleteSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({ enabled: z.literal(true) }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogEntrySchema = z.strictObject({\n upload: routeCatalogUploadSchema,\n download: routeCatalogDownloadSchema,\n delete: routeCatalogDeleteSchema,\n});\n\nexport const routeCatalogResponseSchema = z.strictObject({\n routes: z.record(routeNameSchema, routeCatalogEntrySchema),\n});\n\nexport type RouteCatalogEntry = z.output<typeof routeCatalogEntrySchema>;\nexport type RouteCatalogResponse = {\n routes: Record<S3RouteName, RouteCatalogEntry>;\n};\n","import * as z from \"zod\";\nimport { downloadDispositionSchema } from \"./catalog\";\nimport {\n objectKeySchema,\n optionalTrimmedString,\n routeNameSchema,\n} from \"./shared\";\n\n/** Query string — numbers arrive as strings. Extra keys are rejected. */\nexport const downloadQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n fileName: optionalTrimmedString,\n disposition: downloadDispositionSchema.optional(),\n});\n","import * as z from \"zod\";\nimport { objectKeySchema, routeNameSchema } from \"./shared\";\n\nexport const DELETE_BATCH_MAX_KEYS = 100;\n\nexport const deleteQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n});\n\nexport const deleteBatchBodySchema = z.strictObject({\n route: routeNameSchema,\n keys: z.array(objectKeySchema).min(1).max(DELETE_BATCH_MAX_KEYS),\n});\n","import * as z from \"zod\";\nimport { downloadDispositionSchema } from \"./catalog\";\nimport {\n objectKeySchema,\n optionalTrimmedString,\n routeNameSchema,\n} from \"./shared\";\n\n/** Query for the same-origin proxy download (`GET /file`). */\nexport const fileQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n fileName: optionalTrimmedString,\n disposition: downloadDispositionSchema.optional(),\n});\n","import * as z from \"zod\";\nimport { uploadBodySchema } from \"./upload\";\nimport {\n objectKeySchema,\n partNumberSchema,\n routeNameSchema,\n trimmedString,\n} from \"./shared\";\n\nexport const multipartInitBodySchema = uploadBodySchema;\n\nconst multipartSessionFields = {\n route: routeNameSchema,\n key: objectKeySchema,\n uploadId: trimmedString,\n};\n\nexport const multipartSignPartBodySchema = z.strictObject({\n ...multipartSessionFields,\n partNumber: partNumberSchema,\n partSize: z.int().positive(),\n});\n\nexport const multipartListPartsQuerySchema = z.strictObject({\n ...multipartSessionFields,\n});\n\nexport const multipartCompletedPartSchema = z.strictObject({\n partNumber: partNumberSchema,\n});\n\nexport const multipartCompleteBodySchema = z.strictObject({\n ...multipartSessionFields,\n parts: z.array(multipartCompletedPartSchema).min(1),\n});\n\nexport const multipartAbortBodySchema = z.strictObject({\n ...multipartSessionFields,\n});\n","import * as z from \"zod\";\n\n/** `params` bag on API error JSON. */\nexport const s3ErrorParamsSchema = z.record(\n z.string(),\n z.union([z.string(), z.number()]),\n);\n\n/**\n * better-fetch `errorSchema` — same `{ message, code?, params? }` body\n * better-call serializes from `DimahS3Error`.\n */\nexport const s3FetchErrorSchema = z.object({\n message: z.string(),\n code: z.string().optional(),\n params: s3ErrorParamsSchema.optional(),\n});\n\nexport type S3FetchError = z.output<typeof s3FetchErrorSchema>;\n","/**\n * Pair each stable API `code` with its English `message`.\n * Same shape as Better Auth `defineErrorCodes`.\n */\nexport function defineErrorCodes<const T extends Record<string, string>>(\n messages: T,\n): { readonly [K in keyof T]: { readonly code: K; readonly message: T[K] } } {\n const codes = {} as {\n [K in keyof T]: { readonly code: K; readonly message: T[K] };\n };\n for (const code of Object.keys(messages) as (keyof T)[]) {\n codes[code] = { code, message: messages[code] };\n }\n return codes;\n}\n\n/**\n * Domain error catalog. Zod failures share {@link S3_ERROR_CODES.VALIDATION_ERROR};\n * HTTP 404 for unknown routes uses {@link S3_ERROR_CODES.NOT_FOUND}.\n */\nexport const S3_ERROR_CODES = defineErrorCodes({\n NOT_FOUND: \"Not Found\",\n UNAUTHORIZED: \"Unauthorized\",\n FORBIDDEN: \"Forbidden\",\n CONFLICT: \"Conflict\",\n INTERNAL_ERROR: \"Internal server error\",\n OBJECT_NOT_FOUND: \"Object not found\",\n FEATURE_DISABLED: \"{feature} is disabled\",\n INVALID_KEY: \"Object key is invalid\",\n UNKNOWN_ROUTE: \"Unknown file route\",\n FILE_TYPE_NOT_ALLOWED: \"File type is not allowed\",\n S3_NETWORK_ERROR:\n \"S3 endpoint unreachable ({code}): check your endpoint URL and network connectivity\",\n MULTIPART_PART_MISSING: \"Uploaded part {partNumber} was not found\",\n PAYLOAD_TOO_LARGE: \"Payload too large\",\n QUOTA_EXCEEDED: \"Storage quota exceeded\",\n VALIDATION_ERROR: \"Validation Error\",\n});\n\nexport type S3ErrorCode = keyof typeof S3_ERROR_CODES;\n","import { APIError } from \"better-call/error\";\nimport { type S3ErrorCode } from \"./error-codes\";\n\nexport {\n defineErrorCodes,\n S3_ERROR_CODES,\n type S3ErrorCode,\n} from \"./error-codes\";\n\nexport type DimahS3ErrorParams = Record<string, string | number>;\n\nexport type DimahS3ErrorStatus = NonNullable<\n ConstructorParameters<typeof APIError>[0]\n>;\n\nexport type DimahS3ErrorBody = {\n message?: string;\n code?: string;\n cause?: unknown;\n params?: DimahS3ErrorParams;\n} & Record<string, unknown>;\n\ntype RawError = {\n code: string;\n message: string;\n params?: DimahS3ErrorParams;\n};\n\n/**\n * Typed API error. Same constructor as better-call {@link APIError}\n * (`status`, `body`) so `ctx.error(...)` and `DimahS3Error.from(...)` share\n * a shape. HTTP serializes `{ message, code?, params? }` via native `toResponse`.\n */\nexport class DimahS3Error extends APIError {\n constructor(\n status: DimahS3ErrorStatus = \"BAD_REQUEST\",\n body?: DimahS3ErrorBody,\n headers?: HeadersInit,\n ) {\n const { cause, ...rest } = body ?? {};\n super(status, Object.keys(rest).length > 0 ? rest : undefined, headers);\n this.name = \"DimahS3Error\";\n if (cause !== undefined) {\n this.cause = cause;\n }\n }\n\n get code(): string | undefined {\n return this.body?.code;\n }\n\n get params(): DimahS3ErrorParams | undefined {\n return this.body?.params as DimahS3ErrorParams | undefined;\n }\n\n /** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */\n static from(status: DimahS3ErrorStatus, error: RawError): DimahS3Error {\n return new DimahS3Error(status, {\n message: error.message,\n code: error.code,\n ...(error.params !== undefined ? { params: error.params } : {}),\n });\n }\n\n static fromStatus(\n status: DimahS3ErrorStatus,\n body?: DimahS3ErrorBody,\n ): DimahS3Error {\n return new DimahS3Error(status, body);\n }\n}\n\n/** True for {@link DimahS3Error} and better-call `APIError` (including duck-typed copies). */\nexport function isAPIError(error: unknown): error is APIError {\n if (error instanceof APIError) return true;\n const name = (error as { name?: string } | null)?.name;\n return name === \"APIError\" || name === \"DimahS3Error\";\n}\n\nexport function isDimahS3Error(error: unknown): error is DimahS3Error {\n return (\n error instanceof DimahS3Error ||\n (error as { name?: string } | null)?.name === \"DimahS3Error\"\n );\n}\n\n/** True when `error` is a {@link DimahS3Error} with this catalog `code`. */\nexport function isS3ErrorCode<C extends S3ErrorCode>(\n error: unknown,\n code: C,\n): error is DimahS3Error & { code: C } {\n return isDimahS3Error(error) && error.code === code;\n}\n","/** Default mount path for the catch-all route (`app/api/s3/[...s3]/route.ts`). */\nexport const S3_API_BASE_PATH = \"/api/s3\";\n\nexport function normalizeS3ApiBasePath(basePath: string): string {\n return basePath.replace(/\\/$/, \"\");\n}\n\n/** Relative paths under {@link S3_API_BASE_PATH}. Always start with `/`. */\nexport const S3_API_ROUTES = {\n upload: \"/presign/upload\",\n uploadConfirm: \"/presign/upload/confirm\",\n download: \"/presign/download\",\n file: \"/file\",\n catalog: \"/routes\",\n delete: \"/delete\",\n deleteBatch: \"/delete/batch\",\n multipartInit: \"/presign/multipart/init\",\n multipartPart: \"/presign/multipart/part\",\n multipartComplete: \"/presign/multipart/complete\",\n multipartAbort: \"/presign/multipart/abort\",\n multipartListParts: \"/presign/multipart/parts\",\n} as const;\n","import { createFetch } from \"@better-fetch/fetch\";\nimport type { Status } from \"better-call/error\";\nimport { DimahS3Error } from \"@/error\";\nimport { s3FetchErrorSchema } from \"@/schema/error\";\nimport type { S3ClientFetchOptions, S3Fetch } from \"./types\";\n\nasync function resolveHeaders(\n headers: S3ClientFetchOptions[\"headers\"],\n): Promise<HeadersInit | undefined> {\n if (headers == null) return undefined;\n if (typeof headers === \"function\") return headers();\n return headers;\n}\n\nfunction fallbackMessage(error: {\n statusText: string;\n error?: unknown;\n}): string {\n if (typeof error.error === \"string\" && error.error.trim()) {\n return error.error;\n }\n return error.statusText || \"Request failed\";\n}\n\n/**\n * better-fetch `onError` receives the JSON body spread with `status` /\n * `statusText` — not a `BetterFetchError` instance.\n */\nfunction dimahErrorFromFetch(error: {\n status: number;\n statusText: string;\n error?: unknown;\n}): DimahS3Error {\n const status = error.status as Status;\n const parsed = s3FetchErrorSchema.safeParse(error);\n if (parsed.success) {\n const { message, code, params } = parsed.data;\n return new DimahS3Error(status, {\n message,\n ...(code !== undefined ? { code } : {}),\n ...(params !== undefined ? { params } : {}),\n });\n }\n return new DimahS3Error(status, { message: fallbackMessage(error) });\n}\n\n/**\n * Shared `$fetch` for core routes and client plugins.\n * `base` is a normalized API prefix (e.g. `/api/s3`).\n *\n * Non-OK JSON matching {@link s3FetchErrorSchema} throws {@link DimahS3Error}.\n * `throw: true` is the better-fetch flag; `onError` maps onto the same class\n * the server throws so `instanceof DimahS3Error` works in the browser.\n */\nexport function createS3Fetch(\n base: string,\n options?: S3ClientFetchOptions,\n): S3Fetch {\n return createFetch({\n baseURL: base,\n throw: true,\n errorSchema: s3FetchErrorSchema,\n customFetchImpl: options?.fetch,\n credentials: options?.credentials,\n onRequest: async (ctx) => {\n const extra = await resolveHeaders(options?.headers);\n if (!extra) return ctx;\n const headers = new Headers(ctx.headers);\n new Headers(extra).forEach((value, key) => {\n headers.set(key, value);\n });\n return { ...ctx, headers };\n },\n onError: (ctx) => {\n throw dimahErrorFromFetch(ctx.error);\n },\n });\n}\n","import type { S3ClientPlugin } from \"./types\";\n\n/**\n * Identity helper that preserves literal `id` and method types for\n * {@link createS3Client} inference (`api[id]`).\n *\n * `$InferServerPlugin` must share the same `id` as the client plugin.\n *\n * ```ts\n * export function dbClient() {\n * return defineClientPlugin({\n * id: \"db\",\n * $InferServerPlugin: {} as ReturnType<typeof db>,\n * getActions: ($fetch) => ({\n * listObjects: () => $fetch(\"/db/objects\", { method: \"GET\" }),\n * }),\n * });\n * }\n * ```\n */\nexport function defineClientPlugin<\n Id extends string,\n TMethods extends Record<string, unknown> = Record<string, unknown>,\n TServer extends { id: Id } = { id: Id },\n>(\n plugin: S3ClientPlugin<Id, TMethods, TServer>,\n): S3ClientPlugin<Id, TMethods, TServer> {\n return plugin;\n}\n","import { ROUTE_NAME_PATTERN } from \"@/schema/shared\";\n\n/**\n * Build a plugin HTTP path under `basePath`.\n * Server endpoints and client `getActions` share this so URLs never diverge.\n *\n * @example\n * pluginPath(\"db\", \"objects\") // \"/db/objects\"\n */\nexport function pluginPath(pluginId: string, path: string): string {\n if (!ROUTE_NAME_PATTERN.test(pluginId)) {\n throw new Error(`Invalid plugin id \"${pluginId}\"`);\n }\n return `/${pluginId}/${path.replace(/^\\/+/, \"\")}`;\n}\n","import type { BetterFetch } from \"@better-fetch/fetch\";\n\n/**\n * Shared `$fetch` for core routes and client plugins.\n * Always created with `throw: true` and `errorSchema` (`s3FetchErrorSchema`) —\n * non-OK JSON becomes {@link DimahS3Error} via `onError`.\n */\nexport type S3Fetch = BetterFetch<{ throw: true }>;\n\n/**\n * Optional fetch configuration for {@link createS3Client}.\n * Applied to core routes and every client plugin sharing the same `$fetch`.\n */\nexport type S3ClientFetchOptions = {\n /** Defaults to global `fetch` — override for SSR, tests, or logging. */\n fetch?: typeof fetch;\n /** e.g. `\"include\"` to send cookies cross-origin. */\n credentials?: RequestCredentials;\n /**\n * Static headers or a (possibly async) factory called per request —\n * useful for Authorization tokens.\n */\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n};\n\n/**\n * Browser / isomorphic client plugin — mirrors server `DimahS3Plugin`\n * (literal `id` + methods flattened onto the `createS3Client` result).\n *\n * @typeParam Id — unique plugin id; becomes `api[id]`.\n * @typeParam TMethods — methods returned by {@link S3ClientPlugin.getActions}.\n * @typeParam TServer — matching server plugin; `$InferServerPlugin` must share `id`.\n */\nexport type S3ClientPlugin<\n Id extends string = string,\n TMethods extends Record<string, unknown> = Record<string, unknown>,\n TServer extends { id: string } = { id: Id },\n> = {\n id: Id;\n /**\n * Type-only pointer at the matching server plugin (`ReturnType<typeof db>`).\n * Constrains `id` to match the server plugin's `id`.\n */\n $InferServerPlugin?: TServer & { id: Id };\n /** Build typed methods that call plugin endpoints via the shared `$fetch`. */\n getActions: ($fetch: S3Fetch) => TMethods;\n};\n\n/** Map client plugin ids → their method bags. */\nexport type ClientPluginMethodsMap<P extends readonly S3ClientPlugin[]> = {\n [K in P[number] as K[\"id\"]]: K extends S3ClientPlugin<string, infer M>\n ? M\n : never;\n};\n\n/** Keys reserved on the `createS3Client` result — client plugins may not use these as ids. */\nexport const RESERVED_CLIENT_KEYS = [\n \"upload\",\n \"confirm\",\n \"download\",\n \"catalog\",\n \"delete\",\n \"deleteMany\",\n \"multipart\",\n \"$ERROR_CODES\",\n \"$fetch\",\n \"$Infer\",\n \"Provider\",\n \"useApi\",\n] as const;\n\nexport type ReservedClientKey = (typeof RESERVED_CLIENT_KEYS)[number];\n","import type {\n DeleteBatchResponse,\n DeleteResponse,\n MultipartAbortResponse,\n MultipartCompleteResponse,\n MultipartInitResponse,\n MultipartListPartsResponse,\n MultipartPartResponse,\n DownloadPresignResponse,\n S3Api,\n UploadConfirmResponse,\n UploadPresignResponse,\n RouteCatalogResponse,\n} from \"./types\";\nimport { sanitizeFileName } from \"./helpers/sanitize-file-name\";\nimport { S3_ERROR_CODES } from \"./error\";\nimport {\n createS3Fetch,\n RESERVED_CLIENT_KEYS,\n type ClientPluginMethodsMap,\n type S3ClientFetchOptions,\n type S3ClientPlugin,\n type S3Fetch,\n} from \"./plugin\";\nimport {\n normalizeS3ApiBasePath,\n S3_API_BASE_PATH,\n S3_API_ROUTES,\n} from \"./routes\";\n\n/** Options for {@link createS3Client}. */\nexport type CreateS3ClientOptions<\n P extends readonly S3ClientPlugin[] = readonly S3ClientPlugin[],\n> = {\n /** API path prefix — must match server `basePath`. @default \"/api/s3\" */\n basePath?: string;\n /**\n * Absolute client origin + path (e.g. `https://api.example.com/api/s3`).\n * Wins over {@link basePath} when both are set.\n */\n baseURL?: string;\n /** Client plugins (e.g. `dbClient()` from `@dimah-s3/db/client`). */\n plugins?: P;\n} & S3ClientFetchOptions;\n\n/** Strip server-only `headers` before sending over HTTP. */\nfunction withoutHeaders<T extends { headers?: HeadersInit }>(\n value: T,\n): Omit<T, \"headers\"> {\n const { headers: _headers, ...rest } = value;\n return rest;\n}\n\nfunction createCoreApi($fetch: S3Fetch): S3Api {\n return {\n upload(payload) {\n return $fetch<UploadPresignResponse>(S3_API_ROUTES.upload, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n confirm(payload) {\n return $fetch<UploadConfirmResponse>(S3_API_ROUTES.uploadConfirm, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n download(payload) {\n const { route, key, fileName, disposition } = withoutHeaders(payload);\n return $fetch<DownloadPresignResponse>(S3_API_ROUTES.download, {\n method: \"GET\",\n query: {\n route,\n key,\n fileName: fileName ? sanitizeFileName(fileName) : undefined,\n disposition,\n },\n });\n },\n\n catalog() {\n return $fetch<RouteCatalogResponse>(S3_API_ROUTES.catalog, {\n method: \"GET\",\n });\n },\n\n delete(payload) {\n const { route, key } = withoutHeaders(payload);\n return $fetch<DeleteResponse>(S3_API_ROUTES.delete, {\n method: \"DELETE\",\n query: { route, key },\n });\n },\n\n deleteMany(payload) {\n return $fetch<DeleteBatchResponse>(S3_API_ROUTES.deleteBatch, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n multipart: {\n init(payload) {\n return $fetch<MultipartInitResponse>(S3_API_ROUTES.multipartInit, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n signPart(payload) {\n return $fetch<MultipartPartResponse>(S3_API_ROUTES.multipartPart, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n listParts(payload) {\n const { route, key, uploadId } = withoutHeaders(payload);\n return $fetch<MultipartListPartsResponse>(\n S3_API_ROUTES.multipartListParts,\n { method: \"GET\", query: { route, key, uploadId } },\n );\n },\n\n complete(payload) {\n return $fetch<MultipartCompleteResponse>(\n S3_API_ROUTES.multipartComplete,\n {\n method: \"POST\",\n body: withoutHeaders(payload),\n },\n );\n },\n\n abort(payload) {\n return $fetch<MultipartAbortResponse>(S3_API_ROUTES.multipartAbort, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n },\n };\n}\n\n/** Browser client returned by {@link createS3Client}. */\nexport type CreateS3ClientResult<P extends readonly S3ClientPlugin[] = []> =\n S3Api &\n ClientPluginMethodsMap<P> & {\n $ERROR_CODES: typeof S3_ERROR_CODES;\n $fetch: S3Fetch;\n $Infer: { plugins: P };\n };\n\n/**\n * Browser (or isomorphic) client for the dimah-s3 HTTP API.\n *\n * For React apps prefer `createS3Client` from `@dimah-s3/react` — same options,\n * plus a bound `Provider` / typed `useApi` on the client object.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/core\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const api = createS3Client({\n * basePath: \"/api/s3\",\n * plugins: [dbClient()],\n * });\n *\n * await api.db.listObjects();\n * ```\n */\nexport function createS3Client<const P extends readonly S3ClientPlugin[] = []>(\n options?: CreateS3ClientOptions<P>,\n): CreateS3ClientResult<P> {\n const { basePath, baseURL, plugins, ...fetchOptions } = options ?? {};\n const base = normalizeS3ApiBasePath(baseURL ?? basePath ?? S3_API_BASE_PATH);\n const $fetch = createS3Fetch(base, fetchOptions);\n\n const api = createCoreApi($fetch);\n\n const pluginMethods: Record<string, unknown> = {};\n for (const plugin of plugins ?? []) {\n if ((RESERVED_CLIENT_KEYS as readonly string[]).includes(plugin.id)) {\n throw new Error(\n `Client plugin id \"${plugin.id}\" is reserved on the S3 client.`,\n );\n }\n if (plugin.id in pluginMethods) {\n throw new Error(`Duplicate client plugin id \"${plugin.id}\".`);\n }\n pluginMethods[plugin.id] = plugin.getActions($fetch);\n }\n\n return {\n ...api,\n ...pluginMethods,\n $ERROR_CODES: S3_ERROR_CODES,\n $fetch,\n $Infer: {} as CreateS3ClientResult<P>[\"$Infer\"],\n } as CreateS3ClientResult<P>;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/helpers/validate-file.ts","../src/helpers/build-object-key.ts","../src/helpers/parse-file-name.ts","../src/helpers/format-file-size.ts","../src/helpers/build-content-disposition.ts","../src/helpers/sanitize-file-name.ts","../src/helpers/truncate-file-name.ts","../src/helpers/normalize-object-key.ts","../src/helpers/checksum.ts","../src/helpers/magic-bytes.ts","../src/helpers/public-object-url.ts","../src/schema/shared.ts","../src/schema/upload.ts","../src/schema/catalog.ts","../src/schema/download.ts","../src/schema/delete.ts","../src/schema/file.ts","../src/schema/multipart.ts","../src/schema/error.ts","../src/error-codes.ts","../src/error.ts","../src/routes.ts","../src/plugin/create-s3-fetch.ts","../src/plugin/define-client-plugin.ts","../src/plugin/plugin-path.ts","../src/plugin/types.ts","../src/create-s3-client.ts"],"names":["z","z2","z4","z5","z6","z7","z8","BetterCallAPIError"],"mappings":";;;;;AAiBO,SAAS,gBAAA,CACd,QAAA,EACA,WAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,SAAA,CAAU,MAAA,EAAQ,OAAO,IAAA;AAC9B,EAAA,MAAM,OAAO,WAAA,IAAe,EAAA;AAC5B,EAAA,OAAO,SAAA,CAAU,IAAA,CAAK,CAAC,KAAA,KAAU;AAC/B,IAAA,IAAI,KAAA,CAAM,UAAA,CAAW,GAAG,CAAA,EAAG;AACzB,MAAA,OAAO,SAAS,WAAA,EAAY,CAAE,QAAA,CAAS,KAAA,CAAM,aAAa,CAAA;AAAA,IAC5D;AACA,IAAA,IAAI,KAAA,CAAM,QAAA,CAAS,IAAI,CAAA,EAAG;AACxB,MAAA,OAAO,KAAK,UAAA,CAAW,KAAA,CAAM,OAAA,CAAQ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AAU,OAAA,EAAS,OAAA,EAAS,GAAG,YAAA,EAAa,GAAI,WAAW,EAAC;AACpE,EAAA,MAAM,IAAA,GAAO,sBAAA,CAAuB,OAAA,IAAW,QAAA,IAAY,gBAAgB,CAAA;AAC3E,EAAA,MAAM,MAAA,GAAS,aAAA,CAAc,IAAA,EAAM,YAAY,CAAA;AAE/C,EAAA,MAAM,GAAA,GAAM,cAAc,MAAM,CAAA;AAEhC,EAAA,MAAM,gBAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,MAAA,IAAU,OAAA,IAAW,EAAC,EAAG;AAClC,IAAA,IAAK,oBAAA,CAA2C,QAAA,CAAS,MAAA,CAAO,EAAE,CAAA,EAAG;AACnE,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,kBAAA,EAAqB,OAAO,EAAE,CAAA,+BAAA;AAAA,OAChC;AAAA,IACF;AACA,IAAA,IAAI,MAAA,CAAO,MAAM,aAAA,EAAe;AAC9B,MAAA,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+B,MAAA,CAAO,EAAE,CAAA,EAAA,CAAI,CAAA;AAAA,IAC9D;AACA,IAAA,aAAA,CAAc,MAAA,CAAO,EAAE,CAAA,GAAI,MAAA,CAAO,WAAW,MAAM,CAAA;AAAA,EACrD;AAEA,EAAA,OAAO;AAAA,IACL,GAAG,GAAA;AAAA,IACH,GAAG,aAAA;AAAA,IACH,YAAA,EAAc,cAAA;AAAA,IACd,MAAA;AAAA,IACA,QAAQ;AAAC,GACX;AACF","file":"index.js","sourcesContent":["/** Machine-readable codes for client-side file validation failures. */\nexport type ValidateFileErrorCode =\n \"FILE_TYPE_NOT_ALLOWED\" | \"FILE_EMPTY\" | \"FILE_TOO_LARGE\";\n\n/** Result of {@link validateFile} when the file fails a check. */\nexport type ValidateFileError = {\n code: ValidateFileErrorCode;\n /** English fallback message (localize via Fuma when a translator is available). */\n message: string;\n /** Interpolation params for i18n (e.g. `{ type }`, `{ size }`). */\n params?: Record<string, string | number>;\n};\n\n/**\n * Whether `fileName` / `contentType` match HTML `accept` / route `fileTypes`\n * tokens (`image/*`, `application/pdf`, `.png`).\n */\nexport function matchesFileTypes(\n fileName: string,\n contentType: string | undefined,\n fileTypes: readonly string[],\n): boolean {\n if (!fileTypes.length) return true;\n const type = contentType ?? \"\";\n return fileTypes.some((token) => {\n if (token.startsWith(\".\")) {\n return fileName.toLowerCase().endsWith(token.toLowerCase());\n }\n if (token.endsWith(\"/*\")) {\n return type.startsWith(token.replace(\"/*\", \"/\"));\n }\n return type === token;\n });\n}\n\n/**\n * Client-side accept / size / empty checks before starting an upload.\n * Returns `null` when the file is valid.\n */\nexport function validateFile(\n file: File,\n options: { accept?: string[]; maxFileSize?: number },\n): ValidateFileError | null {\n if (options.accept?.length) {\n if (!matchesFileTypes(file.name, file.type, options.accept)) {\n const ext = file.name.includes(\".\") ? file.name.split(\".\").pop() : null;\n const type = ext ? `.${ext}` : file.type || \"unknown\";\n return {\n code: \"FILE_TYPE_NOT_ALLOWED\",\n message: `File type \"${type}\" is not allowed`,\n params: { type },\n };\n }\n }\n\n if (file.size === 0) {\n return {\n code: \"FILE_EMPTY\",\n message: \"File is empty\",\n };\n }\n\n if (\n typeof options.maxFileSize === \"number\" &&\n file.size > options.maxFileSize\n ) {\n const maxMB = (options.maxFileSize / (1024 * 1024)).toFixed(1);\n return {\n code: \"FILE_TOO_LARGE\",\n message: `File size exceeds ${maxMB} MB limit`,\n params: { size: `${maxMB} MB` },\n };\n }\n\n return null;\n}\n","export function buildObjectKey(...parts: string[]): string {\n return parts\n .map((p) => p.replace(/^\\/+|\\/+$/g, \"\"))\n .filter(Boolean)\n .join(\"/\");\n}\n","export function parseFileName(\n contentDisposition: string | null | undefined,\n): string | undefined {\n if (!contentDisposition) return undefined;\n\n const utf8Match = contentDisposition.match(/filename\\*=UTF-8''([^;,\\s]+)/i);\n if (utf8Match) {\n try {\n return decodeURIComponent(utf8Match[1]);\n } catch {\n /* ignore malformed encoding */\n }\n }\n\n const asciiMatch = contentDisposition.match(/filename=\"([^\"]*)\"/i);\n return asciiMatch?.[1];\n}\n\n/** Last path segment of an object key (`uploads/uuid/a.png` → `a.png`). */\nexport function fileNameFromKey(key: string): string | undefined {\n return key\n .split(\"/\")\n .filter((part) => part.length > 0)\n .at(-1);\n}\n\n/**\n * Filename from `Content-Disposition`, falling back to the object key leaf.\n * Used after HeadObject when the disposition header is missing.\n */\nexport function resolveStoredFileName(\n contentDisposition: string | null | undefined,\n key: string,\n): string | undefined {\n return parseFileName(contentDisposition) ?? fileNameFromKey(key);\n}\n","export function formatFileSize(bytes: number): string {\n if (!Number.isFinite(bytes) || bytes <= 0) return \"0 B\";\n const units = [\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\"] as const;\n const i = Math.min(\n Math.floor(Math.log(bytes) / Math.log(1024)),\n units.length - 1,\n );\n const size = bytes / 1024 ** i;\n return `${size.toFixed(i === 0 ? 0 : 1)} ${units[i]}`;\n}\n","export type ContentDispositionType = \"inline\" | \"attachment\";\n\n/**\n * Builds a RFC 6266 `Content-Disposition` value.\n *\n * Includes both the ASCII-safe `filename` fallback and the RFC 5987\n * `filename*` parameter for full Unicode support.\n */\nexport function buildContentDisposition(\n fileName: string,\n type: ContentDispositionType = \"attachment\",\n): string {\n const ascii = fileName.replace(/[^\\x20-\\x7E]/g, \"_\").replace(/[\"\\\\]/g, \"_\");\n const encoded = encodeURIComponent(fileName);\n return `${type}; filename=\"${ascii}\"; filename*=UTF-8''${encoded}`;\n}\n","/** Sanitizes a file name for Content-Disposition, query params, and object keys. */\nexport function sanitizeFileName(fileName: string): string {\n return fileName.replace(/[\"\\\\\\r\\n\\0]/g, \"_\");\n}\n","/**\n * Truncates a filename while preserving the extension when possible.\n */\nexport function truncateFileName(name: string, maxChars = 48): string {\n if (name.length <= maxChars) return name;\n const dotIndex = name.lastIndexOf(\".\");\n if (dotIndex <= 0) {\n return name.slice(0, maxChars - 1) + \"…\";\n }\n const ext = name.slice(dotIndex);\n const available = maxChars - ext.length - 1;\n if (available <= 0) {\n return name.slice(0, maxChars - 1) + \"…\";\n }\n return name.slice(0, available) + \"… \" + ext;\n}\n","/** S3 object key maximum (1024 bytes). */\nexport const S3_MAX_OBJECT_KEY_LENGTH = 1024;\n\n/**\n * Strip leading/trailing slashes and reject `.` / `..` / empty segments,\n * NUL, backslashes, and oversized keys. Returns `null` when the key is unsafe.\n */\nexport function normalizeObjectKey(key: string): string | null {\n const trimmed = key.replace(/^\\/+/u, \"\").replace(/\\/+$/u, \"\");\n if (!trimmed) return null;\n if (trimmed.length > S3_MAX_OBJECT_KEY_LENGTH) return null;\n if (trimmed.includes(\"\\\\\") || trimmed.includes(\"\\0\")) return null;\n const parts = trimmed.split(\"/\");\n if (parts.some((part) => part === \"\" || part === \".\" || part === \"..\")) {\n return null;\n }\n return parts.join(\"/\");\n}\n","/** SHA-256 digest as unpadded base64 (S3 `ChecksumSHA256`). */\nexport async function sha256Base64(data: BufferSource): Promise<string> {\n const digest = await crypto.subtle.digest(\"SHA-256\", data);\n const bytes = new Uint8Array(digest);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/=+$/, \"\");\n}\n\n/** SHA-256 of a `Blob` / `File` as unpadded base64. */\nexport async function sha256File(file: Blob): Promise<string> {\n return sha256Base64(await file.arrayBuffer());\n}\n","type MagicMatch = {\n mime: string;\n bytes: number[];\n offset?: number;\n};\n\nconst MAGIC: readonly MagicMatch[] = [\n { mime: \"image/png\", bytes: [0x89, 0x50, 0x4e, 0x47] },\n { mime: \"image/jpeg\", bytes: [0xff, 0xd8, 0xff] },\n { mime: \"image/gif\", bytes: [0x47, 0x49, 0x46, 0x38] },\n { mime: \"image/webp\", bytes: [0x52, 0x49, 0x46, 0x46], offset: 0 },\n { mime: \"application/pdf\", bytes: [0x25, 0x50, 0x44, 0x46] },\n { mime: \"application/zip\", bytes: [0x50, 0x4b, 0x03, 0x04] },\n { mime: \"video/webm\", bytes: [0x1a, 0x45, 0xdf, 0xa3] },\n];\n\nfunction prefixEquals(\n bytes: Uint8Array,\n expected: readonly number[],\n offset = 0,\n): boolean {\n if (bytes.length < offset + expected.length) return false;\n return expected.every((value, i) => bytes[offset + i] === value);\n}\n\n/**\n * Sniff a MIME type from the start of a file. Returns `undefined` when\n * the prefix is unknown — this is not a substitute for `fileTypes`.\n */\nexport function sniffContentType(bytes: Uint8Array): string | undefined {\n if (prefixEquals(bytes, [0x52, 0x49, 0x46, 0x46]) && bytes.length >= 12) {\n const tag = String.fromCharCode(bytes[8], bytes[9], bytes[10], bytes[11]);\n if (tag === \"WEBP\") return \"image/webp\";\n }\n for (const entry of MAGIC) {\n if (entry.mime === \"image/webp\") continue;\n if (prefixEquals(bytes, entry.bytes, entry.offset)) return entry.mime;\n }\n return undefined;\n}\n\n/**\n * Whether `bytes` match `expected` (exact MIME or `image/*`).\n * Unknown prefixes return `false`.\n */\nexport function matchesMagicBytes(\n bytes: Uint8Array,\n expected: string,\n): boolean {\n const sniffed = sniffContentType(bytes);\n if (!sniffed) return false;\n if (expected.endsWith(\"/*\")) {\n return sniffed.startsWith(expected.replace(\"/*\", \"/\"));\n }\n return sniffed === expected;\n}\n","/**\n * Join a public origin (CDN or virtual-hosted S3) with an object key.\n * Does not sign — only for `public-read` objects or a fronting CDN.\n */\nexport function buildPublicObjectUrl(options: {\n /** Origin with no trailing slash, e.g. `https://cdn.example.com`. */\n baseUrl: string;\n key: string;\n}): string {\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const path = options.key\n .split(\"/\")\n .filter((part) => part.length > 0)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n return `${base}/${path}`;\n}\n","import * as z from \"zod\";\nimport {\n normalizeObjectKey,\n S3_MAX_OBJECT_KEY_LENGTH,\n} from \"@/helpers/normalize-object-key\";\n\n/** Fallback when the route omits `expiresIn`. */\nexport const S3_DEFAULT_EXPIRES_IN = 600;\n\n/** AWS SigV4 presign maximum (7 days), in seconds. */\nexport const S3_MAX_EXPIRES_IN = 604_800;\n\n/** S3 POST object maximum (5 GiB), in bytes. */\nexport const S3_MAX_POST_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;\n\n/** S3 multipart part number maximum. */\nexport const S3_MAX_PART_NUMBER = 10_000;\n\n/** Max user-defined metadata entries on an upload body. */\nexport const S3_MAX_METADATA_ENTRIES = 32;\n\n/** Named file-route identifier (`avatars`, `uploads`, …). */\nexport const ROUTE_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;\n\n/** Non-empty trimmed string. */\nexport const trimmedString = z.string().trim().min(1);\n\n/** Optional trimmed string. Blank or whitespace-only values are omitted. */\nexport const optionalTrimmedString = z.preprocess((value: unknown) => {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n return trimmed === \"\" ? undefined : trimmed;\n}, z.string().optional());\n\nexport const routeNameSchema = trimmedString.regex(\n ROUTE_NAME_PATTERN,\n \"Invalid route name\",\n);\n\n/** Stored object key — normalized, no `.` / `..` / NUL / backslash segments. */\nexport const objectKeySchema = trimmedString\n .max(S3_MAX_OBJECT_KEY_LENGTH)\n .transform((value, ctx) => {\n const normalized = normalizeObjectKey(value);\n if (normalized == null) {\n ctx.issues.push({\n code: \"custom\",\n message: \"Invalid object key\",\n input: value,\n });\n return z.NEVER;\n }\n return normalized;\n });\n\n/** 1-based S3 multipart part number. */\nexport const partNumberSchema = z.int().min(1).max(S3_MAX_PART_NUMBER);\n\nexport const s3ObjectAclSchema = z.enum([\"private\", \"public-read\"]);\n\n/**\n * S3 `ChecksumSHA256` — 32-byte SHA-256 as standard base64 (padding optional).\n * Matches `sha256Base64()` output and the padded form AWS also accepts.\n */\nexport const sha256ChecksumSchema = z.stringFormat(\n \"sha256-base64\",\n /^[A-Za-z0-9+/]{43}=?$/,\n);\n\n/** Optional checksum; blank / whitespace-only values are omitted. */\nexport const optionalChecksumSchema = optionalTrimmedString.pipe(\n sha256ChecksumSchema.optional(),\n);\n\nconst metadataKeySchema = z\n .string()\n .regex(/^[a-z0-9][a-z0-9-]*$/i, \"Invalid metadata key\")\n .max(128);\n\nexport const metadataSchema = z\n .record(metadataKeySchema, z.string().max(2048))\n .refine((value) => Object.keys(value).length <= S3_MAX_METADATA_ENTRIES, {\n message: \"Too many metadata entries\",\n });\n","import * as z from \"zod\";\nimport {\n metadataSchema,\n objectKeySchema,\n optionalChecksumSchema,\n optionalTrimmedString,\n routeNameSchema,\n trimmedString,\n} from \"./shared\";\n\nexport const uploadBodySchema = z.strictObject({\n route: routeNameSchema,\n fileName: trimmedString,\n fileSize: z.int().positive(),\n contentType: optionalTrimmedString,\n metadata: metadataSchema.optional(),\n /** Unpadded base64 SHA-256. Required when the route sets `upload.checksum`. */\n checksum: optionalChecksumSchema,\n});\n\nexport const confirmBodySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n});\n","import * as z from \"zod\";\nimport type { S3RouteName } from \"@/types/routes\";\nimport { routeNameSchema } from \"./shared\";\n\nexport const downloadDispositionSchema = z.enum([\"inline\", \"attachment\"]);\nexport const downloadModeSchema = z.enum([\"presign\", \"proxy\"]);\n\nexport const routeCatalogUploadSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({\n enabled: z.literal(true),\n fileTypes: z.array(z.string()).optional(),\n maxFileSize: z.int().positive().optional(),\n multipart: z.boolean(),\n checksum: z.boolean().optional(),\n replace: z.literal(\"overwrite\").optional(),\n }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogDownloadSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({\n enabled: z.literal(true),\n disposition: downloadDispositionSchema.optional(),\n mode: downloadModeSchema.optional(),\n }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogDeleteSchema = z.discriminatedUnion(\"enabled\", [\n z.strictObject({ enabled: z.literal(true) }),\n z.strictObject({ enabled: z.literal(false) }),\n]);\n\nexport const routeCatalogEntrySchema = z.strictObject({\n upload: routeCatalogUploadSchema,\n download: routeCatalogDownloadSchema,\n delete: routeCatalogDeleteSchema,\n});\n\nexport const routeCatalogResponseSchema = z.strictObject({\n routes: z.record(routeNameSchema, routeCatalogEntrySchema),\n});\n\nexport type RouteCatalogEntry = z.output<typeof routeCatalogEntrySchema>;\nexport type RouteCatalogResponse = {\n routes: Record<S3RouteName, RouteCatalogEntry>;\n};\n","import * as z from \"zod\";\nimport { downloadDispositionSchema } from \"./catalog\";\nimport {\n objectKeySchema,\n optionalTrimmedString,\n routeNameSchema,\n} from \"./shared\";\n\n/** Query string — numbers arrive as strings. Extra keys are rejected. */\nexport const downloadQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n fileName: optionalTrimmedString,\n disposition: downloadDispositionSchema.optional(),\n});\n","import * as z from \"zod\";\nimport { objectKeySchema, routeNameSchema } from \"./shared\";\n\nexport const DELETE_BATCH_MAX_KEYS = 100;\n\nexport const deleteQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n});\n\nexport const deleteBatchBodySchema = z.strictObject({\n route: routeNameSchema,\n keys: z.array(objectKeySchema).min(1).max(DELETE_BATCH_MAX_KEYS),\n});\n","import * as z from \"zod\";\nimport { downloadDispositionSchema } from \"./catalog\";\nimport {\n objectKeySchema,\n optionalTrimmedString,\n routeNameSchema,\n} from \"./shared\";\n\n/** Query for the same-origin proxy download (`GET /file`). */\nexport const fileQuerySchema = z.strictObject({\n route: routeNameSchema,\n key: objectKeySchema,\n fileName: optionalTrimmedString,\n disposition: downloadDispositionSchema.optional(),\n});\n","import * as z from \"zod\";\nimport { uploadBodySchema } from \"./upload\";\nimport {\n objectKeySchema,\n partNumberSchema,\n routeNameSchema,\n trimmedString,\n} from \"./shared\";\n\nexport const multipartInitBodySchema = uploadBodySchema;\n\nconst multipartSessionFields = {\n route: routeNameSchema,\n key: objectKeySchema,\n uploadId: trimmedString,\n};\n\nexport const multipartSignPartBodySchema = z.strictObject({\n ...multipartSessionFields,\n partNumber: partNumberSchema,\n partSize: z.int().positive(),\n});\n\nexport const multipartListPartsQuerySchema = z.strictObject({\n ...multipartSessionFields,\n});\n\nexport const multipartCompletedPartSchema = z.strictObject({\n partNumber: partNumberSchema,\n});\n\nexport const multipartCompleteBodySchema = z.strictObject({\n ...multipartSessionFields,\n parts: z.array(multipartCompletedPartSchema).min(1),\n});\n\nexport const multipartAbortBodySchema = z.strictObject({\n ...multipartSessionFields,\n});\n","import * as z from \"zod\";\n\n/** `params` bag on API error JSON. */\nexport const s3ErrorParamsSchema = z.record(\n z.string(),\n z.union([z.string(), z.number()]),\n);\n\n/**\n * better-fetch `errorSchema` — same `{ message, code?, params? }` body\n * better-call serializes from `APIError`.\n */\nexport const s3FetchErrorSchema = z.object({\n message: z.string(),\n code: z.string().optional(),\n params: s3ErrorParamsSchema.optional(),\n});\n\nexport type S3FetchError = z.output<typeof s3FetchErrorSchema>;\n","/**\n * Pair each stable API `code` with its English `message`.\n * Same shape as Better Auth `defineErrorCodes`.\n */\nexport function defineErrorCodes<const T extends Record<string, string>>(\n messages: T,\n): { readonly [K in keyof T]: { readonly code: K; readonly message: T[K] } } {\n const codes = {} as {\n [K in keyof T]: { readonly code: K; readonly message: T[K] };\n };\n for (const code of Object.keys(messages) as (keyof T)[]) {\n codes[code] = { code, message: messages[code] };\n }\n return codes;\n}\n\n/**\n * Domain error catalog. Zod failures share {@link S3_ERROR_CODES.VALIDATION_ERROR};\n * HTTP 404 for unknown routes uses {@link S3_ERROR_CODES.NOT_FOUND}.\n */\nexport const S3_ERROR_CODES = defineErrorCodes({\n NOT_FOUND: \"Not Found\",\n UNAUTHORIZED: \"Unauthorized\",\n FORBIDDEN: \"Forbidden\",\n CONFLICT: \"Conflict\",\n INTERNAL_ERROR: \"Internal server error\",\n OBJECT_NOT_FOUND: \"Object not found\",\n FEATURE_DISABLED: \"{feature} is disabled\",\n INVALID_KEY: \"Object key is invalid\",\n UNKNOWN_ROUTE: \"Unknown file route\",\n FILE_TYPE_NOT_ALLOWED: \"File type is not allowed\",\n S3_NETWORK_ERROR:\n \"S3 endpoint unreachable ({code}): check your endpoint URL and network connectivity\",\n MULTIPART_PART_MISSING: \"Uploaded part {partNumber} was not found\",\n PAYLOAD_TOO_LARGE: \"Payload too large\",\n QUOTA_EXCEEDED: \"Storage quota exceeded\",\n VALIDATION_ERROR: \"Validation Error\",\n});\n\nexport type S3ErrorCode = keyof typeof S3_ERROR_CODES;\n","import { APIError as BetterCallAPIError } from \"better-call/error\";\nimport { type S3ErrorCode } from \"./error-codes\";\n\nexport {\n defineErrorCodes,\n S3_ERROR_CODES,\n type S3ErrorCode,\n} from \"./error-codes\";\n\ntype NamedStatus = ConstructorParameters<typeof BetterCallAPIError>[0];\ntype APIErrorStatus = NamedStatus | number;\ntype APIErrorBody = ConstructorParameters<typeof BetterCallAPIError>[1] & {\n params?: Record<string, string | number>;\n cause?: unknown;\n};\n\n/**\n * better-call `APIError` — same name and `(status, body)` constructor as\n * `ctx.error(...)`. HTTP serializes `{ message, code?, params? }` via native\n * `toResponse`.\n */\nexport class APIError extends BetterCallAPIError {\n constructor(\n status: APIErrorStatus = \"BAD_REQUEST\",\n body?: APIErrorBody,\n headers?: HeadersInit,\n ) {\n const { cause, ...rest } = body ?? {};\n super(\n status as NamedStatus,\n Object.keys(rest).length > 0 ? rest : undefined,\n headers,\n );\n this.name = \"APIError\";\n if (cause !== undefined) {\n this.cause = cause;\n }\n }\n\n get code(): string | undefined {\n return this.body?.code;\n }\n\n get params(): Record<string, string | number> | undefined {\n return this.body?.params as Record<string, string | number> | undefined;\n }\n\n /** Throw a catalog (or custom) `{ code, message }` with an HTTP status. */\n static from(\n status: APIErrorStatus,\n error: {\n code: string;\n message: string;\n params?: Record<string, string | number>;\n },\n ): APIError {\n return new APIError(status, {\n message: error.message,\n code: error.code,\n ...(error.params !== undefined ? { params: error.params } : {}),\n });\n }\n\n static fromStatus(status: APIErrorStatus, body?: APIErrorBody): APIError {\n return new APIError(status, body);\n }\n}\n\n/** True for {@link APIError} and better-call copies (including duck-typed). */\nexport function isAPIError(error: unknown): error is APIError {\n return (\n error instanceof BetterCallAPIError ||\n error instanceof APIError ||\n (error as { name?: string } | null)?.name === \"APIError\"\n );\n}\n\n/** True when `error` is an {@link APIError} with this catalog `code`. */\nexport function isS3ErrorCode<C extends S3ErrorCode>(\n error: unknown,\n code: C,\n): error is APIError & { code: C } {\n return isAPIError(error) && error.code === code;\n}\n","/** Default mount path for the catch-all route (`app/api/s3/[...s3]/route.ts`). */\nexport const S3_API_BASE_PATH = \"/api/s3\";\n\nexport function normalizeS3ApiBasePath(basePath: string): string {\n return basePath.replace(/\\/$/, \"\");\n}\n\n/** Relative paths under {@link S3_API_BASE_PATH}. Always start with `/`. */\nexport const S3_API_ROUTES = {\n upload: \"/presign/upload\",\n uploadConfirm: \"/presign/upload/confirm\",\n download: \"/presign/download\",\n file: \"/file\",\n catalog: \"/routes\",\n delete: \"/delete\",\n deleteBatch: \"/delete/batch\",\n multipartInit: \"/presign/multipart/init\",\n multipartPart: \"/presign/multipart/part\",\n multipartComplete: \"/presign/multipart/complete\",\n multipartAbort: \"/presign/multipart/abort\",\n multipartListParts: \"/presign/multipart/parts\",\n} as const;\n","import { createFetch } from \"@better-fetch/fetch\";\nimport { APIError } from \"@/error\";\nimport { s3FetchErrorSchema } from \"@/schema/error\";\nimport type { S3ClientFetchOptions, S3Fetch } from \"./types\";\n\nasync function resolveHeaders(\n headers: S3ClientFetchOptions[\"headers\"],\n): Promise<HeadersInit | undefined> {\n if (headers == null) return undefined;\n if (typeof headers === \"function\") return headers();\n return headers;\n}\n\nfunction fallbackMessage(error: {\n statusText: string;\n error?: unknown;\n}): string {\n if (typeof error.error === \"string\" && error.error.trim()) {\n return error.error;\n }\n return error.statusText || \"Request failed\";\n}\n\n/**\n * better-fetch `onError` receives the JSON body spread with `status` /\n * `statusText` — not a `BetterFetchError` instance.\n */\nfunction apiErrorFromFetch(error: {\n status: number;\n statusText: string;\n error?: unknown;\n}): APIError {\n const parsed = s3FetchErrorSchema.safeParse(error);\n if (parsed.success) {\n const { message, code, params } = parsed.data;\n return new APIError(error.status, {\n message,\n ...(code !== undefined ? { code } : {}),\n ...(params !== undefined ? { params } : {}),\n });\n }\n return new APIError(error.status, { message: fallbackMessage(error) });\n}\n\n/**\n * Shared `$fetch` for core routes and client plugins.\n * `base` is a normalized API prefix (e.g. `/api/s3`).\n *\n * Non-OK JSON matching {@link s3FetchErrorSchema} throws {@link APIError}.\n * `throw: true` is the better-fetch flag; `onError` maps onto the same class\n * the server throws so `instanceof APIError` works in the browser.\n */\nexport function createS3Fetch(\n base: string,\n options?: S3ClientFetchOptions,\n): S3Fetch {\n return createFetch({\n baseURL: base,\n throw: true,\n errorSchema: s3FetchErrorSchema,\n customFetchImpl: options?.fetch,\n credentials: options?.credentials,\n onRequest: async (ctx) => {\n const extra = await resolveHeaders(options?.headers);\n if (!extra) return ctx;\n const headers = new Headers(ctx.headers);\n new Headers(extra).forEach((value, key) => {\n headers.set(key, value);\n });\n return { ...ctx, headers };\n },\n onError: (ctx) => {\n throw apiErrorFromFetch(ctx.error);\n },\n });\n}\n","import type { S3ClientPlugin } from \"./types\";\n\n/**\n * Identity helper that preserves literal `id` and method types for\n * {@link createS3Client} inference (`api[id]`).\n *\n * `$InferServerPlugin` must share the same `id` as the client plugin.\n *\n * ```ts\n * export function dbClient() {\n * return defineClientPlugin({\n * id: \"db\",\n * $InferServerPlugin: {} as ReturnType<typeof db>,\n * getActions: ($fetch) => ({\n * listObjects: () => $fetch(\"/db/objects\", { method: \"GET\" }),\n * }),\n * });\n * }\n * ```\n */\nexport function defineClientPlugin<\n Id extends string,\n TMethods extends Record<string, unknown> = Record<string, unknown>,\n TServer extends { id: Id } = { id: Id },\n>(\n plugin: S3ClientPlugin<Id, TMethods, TServer>,\n): S3ClientPlugin<Id, TMethods, TServer> {\n return plugin;\n}\n","import { ROUTE_NAME_PATTERN } from \"@/schema/shared\";\n\n/**\n * Build a plugin HTTP path under `basePath`.\n * Server endpoints and client `getActions` share this so URLs never diverge.\n *\n * @example\n * pluginPath(\"db\", \"objects\") // \"/db/objects\"\n */\nexport function pluginPath(pluginId: string, path: string): string {\n if (!ROUTE_NAME_PATTERN.test(pluginId)) {\n throw new Error(`Invalid plugin id \"${pluginId}\"`);\n }\n return `/${pluginId}/${path.replace(/^\\/+/, \"\")}`;\n}\n","import type { BetterFetch } from \"@better-fetch/fetch\";\n\n/**\n * Shared `$fetch` for core routes and client plugins.\n * Always created with `throw: true` and `errorSchema` (`s3FetchErrorSchema`) —\n * non-OK JSON becomes {@link APIError} via `onError`.\n */\nexport type S3Fetch = BetterFetch<{ throw: true }>;\n\n/**\n * Optional fetch configuration for {@link createS3Client}.\n * Applied to core routes and every client plugin sharing the same `$fetch`.\n */\nexport type S3ClientFetchOptions = {\n /** Defaults to global `fetch` — override for SSR, tests, or logging. */\n fetch?: typeof fetch;\n /** e.g. `\"include\"` to send cookies cross-origin. */\n credentials?: RequestCredentials;\n /**\n * Static headers or a (possibly async) factory called per request —\n * useful for Authorization tokens.\n */\n headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);\n};\n\n/**\n * Browser / isomorphic client plugin — mirrors server `DimahS3Plugin`\n * (literal `id` + methods flattened onto the `createS3Client` result).\n *\n * @typeParam Id — unique plugin id; becomes `api[id]`.\n * @typeParam TMethods — methods returned by {@link S3ClientPlugin.getActions}.\n * @typeParam TServer — matching server plugin; `$InferServerPlugin` must share `id`.\n */\nexport type S3ClientPlugin<\n Id extends string = string,\n TMethods extends Record<string, unknown> = Record<string, unknown>,\n TServer extends { id: string } = { id: Id },\n> = {\n id: Id;\n /**\n * Type-only pointer at the matching server plugin (`ReturnType<typeof db>`).\n * Constrains `id` to match the server plugin's `id`.\n */\n $InferServerPlugin?: TServer & { id: Id };\n /** Build typed methods that call plugin endpoints via the shared `$fetch`. */\n getActions: ($fetch: S3Fetch) => TMethods;\n};\n\n/** Map client plugin ids → their method bags. */\nexport type ClientPluginMethodsMap<P extends readonly S3ClientPlugin[]> = {\n [K in P[number] as K[\"id\"]]: K extends S3ClientPlugin<string, infer M>\n ? M\n : never;\n};\n\n/** Keys reserved on the `createS3Client` result — client plugins may not use these as ids. */\nexport const RESERVED_CLIENT_KEYS = [\n \"upload\",\n \"confirm\",\n \"download\",\n \"catalog\",\n \"delete\",\n \"deleteMany\",\n \"multipart\",\n \"$ERROR_CODES\",\n \"$fetch\",\n \"$Infer\",\n \"Provider\",\n \"useApi\",\n] as const;\n\nexport type ReservedClientKey = (typeof RESERVED_CLIENT_KEYS)[number];\n","import type {\n DeleteBatchResponse,\n DeleteResponse,\n MultipartAbortResponse,\n MultipartCompleteResponse,\n MultipartInitResponse,\n MultipartListPartsResponse,\n MultipartPartResponse,\n DownloadPresignResponse,\n S3Api,\n UploadConfirmResponse,\n UploadPresignResponse,\n RouteCatalogResponse,\n} from \"./types\";\nimport { sanitizeFileName } from \"./helpers/sanitize-file-name\";\nimport { S3_ERROR_CODES } from \"./error\";\nimport {\n createS3Fetch,\n RESERVED_CLIENT_KEYS,\n type ClientPluginMethodsMap,\n type S3ClientFetchOptions,\n type S3ClientPlugin,\n type S3Fetch,\n} from \"./plugin\";\nimport {\n normalizeS3ApiBasePath,\n S3_API_BASE_PATH,\n S3_API_ROUTES,\n} from \"./routes\";\n\n/** Options for {@link createS3Client}. */\nexport type CreateS3ClientOptions<\n P extends readonly S3ClientPlugin[] = readonly S3ClientPlugin[],\n> = {\n /** API path prefix — must match server `basePath`. @default \"/api/s3\" */\n basePath?: string;\n /**\n * Absolute client origin + path (e.g. `https://api.example.com/api/s3`).\n * Wins over {@link basePath} when both are set.\n */\n baseURL?: string;\n /** Client plugins (e.g. `dbClient()` from `@dimah-s3/db/client`). */\n plugins?: P;\n} & S3ClientFetchOptions;\n\n/** Strip server-only `headers` before sending over HTTP. */\nfunction withoutHeaders<T extends { headers?: HeadersInit }>(\n value: T,\n): Omit<T, \"headers\"> {\n const { headers: _headers, ...rest } = value;\n return rest;\n}\n\nfunction createCoreApi($fetch: S3Fetch): S3Api {\n return {\n upload(payload) {\n return $fetch<UploadPresignResponse>(S3_API_ROUTES.upload, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n confirm(payload) {\n return $fetch<UploadConfirmResponse>(S3_API_ROUTES.uploadConfirm, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n download(payload) {\n const { route, key, fileName, disposition } = withoutHeaders(payload);\n return $fetch<DownloadPresignResponse>(S3_API_ROUTES.download, {\n method: \"GET\",\n query: {\n route,\n key,\n fileName: fileName ? sanitizeFileName(fileName) : undefined,\n disposition,\n },\n });\n },\n\n catalog() {\n return $fetch<RouteCatalogResponse>(S3_API_ROUTES.catalog, {\n method: \"GET\",\n });\n },\n\n delete(payload) {\n const { route, key } = withoutHeaders(payload);\n return $fetch<DeleteResponse>(S3_API_ROUTES.delete, {\n method: \"DELETE\",\n query: { route, key },\n });\n },\n\n deleteMany(payload) {\n return $fetch<DeleteBatchResponse>(S3_API_ROUTES.deleteBatch, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n multipart: {\n init(payload) {\n return $fetch<MultipartInitResponse>(S3_API_ROUTES.multipartInit, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n signPart(payload) {\n return $fetch<MultipartPartResponse>(S3_API_ROUTES.multipartPart, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n\n listParts(payload) {\n const { route, key, uploadId } = withoutHeaders(payload);\n return $fetch<MultipartListPartsResponse>(\n S3_API_ROUTES.multipartListParts,\n { method: \"GET\", query: { route, key, uploadId } },\n );\n },\n\n complete(payload) {\n return $fetch<MultipartCompleteResponse>(\n S3_API_ROUTES.multipartComplete,\n {\n method: \"POST\",\n body: withoutHeaders(payload),\n },\n );\n },\n\n abort(payload) {\n return $fetch<MultipartAbortResponse>(S3_API_ROUTES.multipartAbort, {\n method: \"POST\",\n body: withoutHeaders(payload),\n });\n },\n },\n };\n}\n\n/** Browser client returned by {@link createS3Client}. */\nexport type CreateS3ClientResult<P extends readonly S3ClientPlugin[] = []> =\n S3Api &\n ClientPluginMethodsMap<P> & {\n $ERROR_CODES: typeof S3_ERROR_CODES;\n $fetch: S3Fetch;\n $Infer: { plugins: P };\n };\n\n/**\n * Browser (or isomorphic) client for the dimah-s3 HTTP API.\n *\n * For React apps prefer `createS3Client` from `@dimah-s3/react` — same options,\n * plus a bound `Provider` / typed `useApi` on the client object.\n *\n * ```ts\n * import { createS3Client } from \"@dimah-s3/core\";\n * import { dbClient } from \"@dimah-s3/db/client\";\n *\n * export const api = createS3Client({\n * basePath: \"/api/s3\",\n * plugins: [dbClient()],\n * });\n *\n * await api.db.listObjects();\n * ```\n */\nexport function createS3Client<const P extends readonly S3ClientPlugin[] = []>(\n options?: CreateS3ClientOptions<P>,\n): CreateS3ClientResult<P> {\n const { basePath, baseURL, plugins, ...fetchOptions } = options ?? {};\n const base = normalizeS3ApiBasePath(baseURL ?? basePath ?? S3_API_BASE_PATH);\n const $fetch = createS3Fetch(base, fetchOptions);\n\n const api = createCoreApi($fetch);\n\n const pluginMethods: Record<string, unknown> = {};\n for (const plugin of plugins ?? []) {\n if ((RESERVED_CLIENT_KEYS as readonly string[]).includes(plugin.id)) {\n throw new Error(\n `Client plugin id \"${plugin.id}\" is reserved on the S3 client.`,\n );\n }\n if (plugin.id in pluginMethods) {\n throw new Error(`Duplicate client plugin id \"${plugin.id}\".`);\n }\n pluginMethods[plugin.id] = plugin.getActions($fetch);\n }\n\n return {\n ...api,\n ...pluginMethods,\n $ERROR_CODES: S3_ERROR_CODES,\n $fetch,\n $Infer: {} as CreateS3ClientResult<P>[\"$Infer\"],\n } as CreateS3ClientResult<P>;\n}\n"]}
|
|
@@ -3,9 +3,9 @@ import type { S3ClientFetchOptions, S3Fetch } from "./types";
|
|
|
3
3
|
* Shared `$fetch` for core routes and client plugins.
|
|
4
4
|
* `base` is a normalized API prefix (e.g. `/api/s3`).
|
|
5
5
|
*
|
|
6
|
-
* Non-OK JSON matching {@link s3FetchErrorSchema} throws {@link
|
|
6
|
+
* Non-OK JSON matching {@link s3FetchErrorSchema} throws {@link APIError}.
|
|
7
7
|
* `throw: true` is the better-fetch flag; `onError` maps onto the same class
|
|
8
|
-
* the server throws so `instanceof
|
|
8
|
+
* the server throws so `instanceof APIError` works in the browser.
|
|
9
9
|
*/
|
|
10
10
|
export declare function createS3Fetch(base: string, options?: S3ClientFetchOptions): S3Fetch;
|
|
11
11
|
//# sourceMappingURL=create-s3-fetch.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-s3-fetch.d.ts","sourceRoot":"","sources":["../../src/plugin/create-s3-fetch.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"create-s3-fetch.d.ts","sourceRoot":"","sources":["../../src/plugin/create-s3-fetch.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,oBAAoB,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAyC7D;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,oBAAoB,GAC7B,OAAO,CAoBT"}
|
package/dist/plugin/types.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { BetterFetch } from "@better-fetch/fetch";
|
|
|
2
2
|
/**
|
|
3
3
|
* Shared `$fetch` for core routes and client plugins.
|
|
4
4
|
* Always created with `throw: true` and `errorSchema` (`s3FetchErrorSchema`) —
|
|
5
|
-
* non-OK JSON becomes {@link
|
|
5
|
+
* non-OK JSON becomes {@link APIError} via `onError`.
|
|
6
6
|
*/
|
|
7
7
|
export type S3Fetch = BetterFetch<{
|
|
8
8
|
throw: true;
|
package/dist/schema/error.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import * as z from "zod";
|
|
|
3
3
|
export declare const s3ErrorParamsSchema: z.ZodRecord<z.ZodString, z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>;
|
|
4
4
|
/**
|
|
5
5
|
* better-fetch `errorSchema` — same `{ message, code?, params? }` body
|
|
6
|
-
* better-call serializes from `
|
|
6
|
+
* better-call serializes from `APIError`.
|
|
7
7
|
*/
|
|
8
8
|
export declare const s3FetchErrorSchema: z.ZodObject<{
|
|
9
9
|
message: z.ZodString;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dimah-s3/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Typed S3 presign protocol and fetch client shared by @dimah-s3/server and @dimah-s3/react",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"s3",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"@workspace/eslint-config": "0.0.1",
|
|
45
45
|
"@workspace/typescript-config": "0.0.1",
|
|
46
46
|
"eslint": "^10.9.1",
|
|
47
|
-
"tsc-alias": "^1.9.
|
|
47
|
+
"tsc-alias": "^1.9.3",
|
|
48
48
|
"tsup": "^8.5.1",
|
|
49
49
|
"typescript": "7.0.2",
|
|
50
50
|
"vitest": "^4.1.11"
|