@rebasepro/server 0.19.1 → 0.19.2-canary.g09316f6
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/dist/{GCSStorageController-ZXPoNqW3.js → GCSStorageController-CLIJXwGS.js} +2 -2
- package/dist/{GCSStorageController-ZXPoNqW3.js.map → GCSStorageController-CLIJXwGS.js.map} +1 -1
- package/dist/{S3StorageController-5pAXyv31.js → S3StorageController-Dcuf8lMA.js} +2 -2
- package/dist/{S3StorageController-5pAXyv31.js.map → S3StorageController-Dcuf8lMA.js.map} +1 -1
- package/dist/api/errors.d.ts +6 -1
- package/dist/api/rest/api-generator.d.ts +80 -0
- package/dist/api/rest/batch.d.ts +71 -0
- package/dist/api/rest/conflict-target.d.ts +20 -0
- package/dist/api/rest/etag.d.ts +55 -0
- package/dist/api/rest/field-access-query.d.ts +66 -0
- package/dist/api/rest/field-ops.d.ts +86 -0
- package/dist/api/rest/query-parser.d.ts +16 -2
- package/dist/api/rest/soft-delete-params.d.ts +37 -0
- package/dist/api/rest/write-validation.d.ts +51 -8
- package/dist/api/types.d.ts +28 -3
- package/dist/{ast-schema-editor-CNgFJ3NF.js → ast-schema-editor-C6mDz0XN.js} +2 -2
- package/dist/{ast-schema-editor-CNgFJ3NF.js.map → ast-schema-editor-C6mDz0XN.js.map} +1 -1
- package/dist/auth/jwt.d.ts +17 -0
- package/dist/auth/rls-scope.d.ts +1 -0
- package/dist/{auth-BRiOuyq8.js → auth-DJsLXsCR.js} +61 -60
- package/dist/auth-DJsLXsCR.js.map +1 -0
- package/dist/{backup-C8P6Cl3G.js → backup-DGu0v9Ku.js} +2 -2
- package/dist/{backup-C8P6Cl3G.js.map → backup-DGu0v9Ku.js.map} +1 -1
- package/dist/boot/bundle.d.ts +12 -3
- package/dist/boot/driver.d.ts +11 -4
- package/dist/boot/env.d.ts +2 -2
- package/dist/{contract-routes-CusnEB5h.js → contract-routes-eLxV0le1.js} +2 -2
- package/dist/{contract-routes-CusnEB5h.js.map → contract-routes-eLxV0le1.js.map} +1 -1
- package/dist/{cron-loader-DnmIePn_.js → cron-loader-CQjvjpEw.js} +2 -2
- package/dist/{cron-loader-DnmIePn_.js.map → cron-loader-CQjvjpEw.js.map} +1 -1
- package/dist/{cron-routes-D3x2ydMa.js → cron-routes-Bfwni8Zg.js} +3 -3
- package/dist/{cron-routes-D3x2ydMa.js.map → cron-routes-Bfwni8Zg.js.map} +1 -1
- package/dist/{cron-store-CCQXwgVL.js → cron-store-Bsiw4Q6u.js} +3 -3
- package/dist/{cron-store-CCQXwgVL.js.map → cron-store-Bsiw4Q6u.js.map} +1 -1
- package/dist/{errors-HjfaPlvY.js → errors-DMImyqyR.js} +8 -3
- package/dist/errors-DMImyqyR.js.map +1 -0
- package/dist/{function-routes-gQ0EShVG.js → function-routes-C4nB2h0z.js} +2 -2
- package/dist/{function-routes-gQ0EShVG.js.map → function-routes-C4nB2h0z.js.map} +1 -1
- package/dist/functions/index.js +7 -2
- package/dist/functions/index.js.map +1 -1
- package/dist/{history-recorder-B1FwXx9J.js → history-recorder-r5_IzSHK.js} +2 -2
- package/dist/{history-recorder-B1FwXx9J.js.map → history-recorder-r5_IzSHK.js.map} +1 -1
- package/dist/{history-store-LHXaQywp.js → history-store-D4RVK-uZ.js} +2 -2
- package/dist/{history-store-LHXaQywp.js.map → history-store-D4RVK-uZ.js.map} +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.es.js +2429 -7303
- package/dist/index.es.js.map +1 -1
- package/dist/{jobs-DkkD9mPV.js → jobs-CW5lm_Ix.js} +3 -3
- package/dist/{jobs-DkkD9mPV.js.map → jobs-CW5lm_Ix.js.map} +1 -1
- package/dist/{jwt-DkhXwMzR.js → jwt-DATvkKB_.js} +39 -3
- package/dist/{jwt-DkhXwMzR.js.map → jwt-DATvkKB_.js.map} +1 -1
- package/dist/{keys-g8lbVC_o.js → keys-Qfc4XieN.js} +2 -2
- package/dist/{keys-g8lbVC_o.js.map → keys-Qfc4XieN.js.map} +1 -1
- package/dist/{logs-routes-CbsTpozn.js → logs-routes-DnJINsMu.js} +2 -2
- package/dist/{logs-routes-CbsTpozn.js.map → logs-routes-DnJINsMu.js.map} +1 -1
- package/dist/{openapi-generator-BIBbO1Tq.js → openapi-generator-DGyLbISS.js} +374 -48
- package/dist/openapi-generator-DGyLbISS.js.map +1 -0
- package/dist/{query-parser-C68Q9EX4.js → query-parser-BQiPZrM-.js} +257 -17
- package/dist/query-parser-BQiPZrM-.js.map +1 -0
- package/dist/{request-timeout-DESvlfrS.js → request-timeout-BR-OBwES.js} +2 -2
- package/dist/{request-timeout-DESvlfrS.js.map → request-timeout-BR-OBwES.js.map} +1 -1
- package/dist/{schema-editor-routes-CcZKh50q.js → schema-editor-routes-C3TLZqAC.js} +13 -13
- package/dist/{schema-editor-routes-CcZKh50q.js.map → schema-editor-routes-C3TLZqAC.js.map} +1 -1
- package/dist/{src-DHK4fHkw.js → src-Br6ARbs6.js} +26 -2
- package/dist/src-Br6ARbs6.js.map +1 -0
- package/dist/{src-Dq-I3Ybx.js → src-DqZ9YiGA.js} +1387 -94
- package/dist/src-DqZ9YiGA.js.map +1 -0
- package/dist/storage/index.d.ts +2 -0
- package/dist/storage/property-limits.d.ts +77 -0
- package/dist/storage/routes.d.ts +13 -0
- package/dist/storage/tus-handler.d.ts +22 -1
- package/package.json +7 -6
- package/dist/auth-BRiOuyq8.js.map +0 -1
- package/dist/errors-HjfaPlvY.js.map +0 -1
- package/dist/openapi-generator-BIBbO1Tq.js.map +0 -1
- package/dist/query-parser-C68Q9EX4.js.map +0 -1
- package/dist/schemas-C3234HWE.js +0 -6827
- package/dist/schemas-C3234HWE.js.map +0 -1
- package/dist/src-DHK4fHkw.js.map +0 -1
- package/dist/src-Dq-I3Ybx.js.map +0 -1
|
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
|
-
import { o as folderKey, s as listingPrefix } from "./keys-
|
|
6
|
+
import { o as folderKey, s as listingPrefix } from "./keys-Qfc4XieN.js";
|
|
7
7
|
import "./types-BfKcm9do.js";
|
|
8
8
|
//#region src/storage/GCSStorageController.ts
|
|
9
9
|
/**
|
|
@@ -225,4 +225,4 @@ function isNotFoundError(error) {
|
|
|
225
225
|
//#endregion
|
|
226
226
|
export { GCSStorageController_exports as n, GCSStorageController as t };
|
|
227
227
|
|
|
228
|
-
//# sourceMappingURL=GCSStorageController-
|
|
228
|
+
//# sourceMappingURL=GCSStorageController-CLIJXwGS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"GCSStorageController-ZXPoNqW3.js","names":[],"sources":["../src/storage/GCSStorageController.ts"],"sourcesContent":["/**\n * Google Cloud Storage controller (works with GCS and Firebase Storage)\n *\n * The `@google-cloud/storage` package is loaded lazily so it remains an\n * optional peer dependency — users who don't need GCS never pay for the\n * import cost or need it installed.\n */\n\nimport {\n StorageController,\n GCSStorageConfig,\n DEFAULT_MAX_FILE_SIZE\n} from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n UploadFileProps,\n UploadFileResult,\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference\n} from \"@rebasepro/types\";\n\n// ---------------------------------------------------------------------------\n// Lazy import of @google-cloud/storage\n// ---------------------------------------------------------------------------\n\nlet gcsModule: typeof import(\"@google-cloud/storage\") | null = null;\n\nasync function loadGCS(): Promise<typeof import(\"@google-cloud/storage\")> {\n if (gcsModule) return gcsModule;\n try {\n gcsModule = await import(\"@google-cloud/storage\");\n return gcsModule;\n } catch {\n throw new Error(\n \"Google Cloud Storage is required for the GCS storage controller. \" +\n \"Install it with: pnpm add @google-cloud/storage\"\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// GCSStorageController\n// ---------------------------------------------------------------------------\n\n/**\n * Google Cloud Storage implementation of `StorageController`.\n *\n * Works with standard GCS buckets **and** Firebase Storage buckets\n * (e.g. `\"my-project.appspot.com\"`).\n */\nexport class GCSStorageController implements StorageController {\n private config: GCSStorageConfig;\n private client: InstanceType<typeof import(\"@google-cloud/storage\").Storage> | null = null;\n\n constructor(config: GCSStorageConfig) {\n this.config = config;\n }\n\n // ------------------------------------------------------------------\n // Lazy client initialisation\n // ------------------------------------------------------------------\n\n private async getClient(): Promise<InstanceType<typeof import(\"@google-cloud/storage\").Storage>> {\n if (this.client) return this.client;\n const { Storage } = await loadGCS();\n this.client = new Storage({\n projectId: this.config.projectId,\n keyFilename: this.config.keyFilename,\n credentials: this.config.credentials\n });\n return this.client;\n }\n\n // ------------------------------------------------------------------\n // StorageController interface\n // ------------------------------------------------------------------\n\n getType(): \"gcs\" {\n return \"gcs\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n * @see S3StorageController.knownBuckets\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n const client = await this.getClient();\n const gcsFile = client.bucket(usedBucket).file(key);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n await gcsFile.save(buffer, {\n contentType: file.type,\n metadata: metadata ? { metadata: this.flattenMetadata(metadata) } : undefined\n });\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `gs://${usedBucket}/${key}`\n };\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n // Get metadata first to check existence and populate response\n const [fileMetadata] = await gcsFile.getMetadata();\n\n // Generate a signed URL\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const [url] = await gcsFile.getSignedUrl({\n action: \"read\",\n expires: Date.now() + expiresIn * 1000\n });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: Number(fileMetadata.size) || 0,\n contentType: fileMetadata.contentType || \"application/octet-stream\",\n customMetadata: (fileMetadata.metadata as Record<string, string> | undefined) || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n const [contents] = await gcsFile.download();\n\n // Get content type from metadata\n const [fileMetadata] = await gcsFile.getMetadata();\n const contentType = fileMetadata.contentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([new Uint8Array(contents)], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n await gcsFile.delete({ ignoreNotFound: true });\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n const client = await this.getClient();\n const gcsBucket = client.bucket(resolvedBucket);\n\n // Fetch files (objects) matching the prefix\n const [files, , filesApiResponse] = await gcsBucket.getFiles({\n prefix: listingPrefix(prefix),\n delimiter: \"/\",\n maxResults: options?.maxResults ?? 1000,\n pageToken: options?.pageToken,\n autoPaginate: false\n });\n\n const items: StorageReference[] = files.map(file => ({\n bucket: resolvedBucket,\n fullPath: file.name,\n name: file.name.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${file.name}`\n }));\n\n // Common prefixes (folder-like entries) come from the API response\n const apiPrefixes: string[] =\n (filesApiResponse as Record<string, unknown> | undefined)?.prefixes as string[] ?? [];\n\n const prefixes: StorageReference[] = apiPrefixes.map(p => {\n // Without the trailing slash GCS puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(p);\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${folder}`\n };\n });\n\n // The next page token is returned on the query object (second element)\n const nextPageToken =\n (filesApiResponse as Record<string, unknown> | undefined)?.nextPageToken as string | undefined;\n\n return {\n items,\n prefixes,\n nextPageToken\n };\n }\n\n // ------------------------------------------------------------------\n // Private helpers\n // ------------------------------------------------------------------\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name — either from parameter or config.\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for GCS it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n /**\n * Flatten nested metadata to string values (GCS custom metadata requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether an error represents a 404 / Not Found from the GCS client.\n */\nfunction isNotFoundError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const err = error as Record<string, unknown>;\n if (err[\"code\"] === 404) return true;\n if (typeof err[\"message\"] === \"string\" && /not found/i.test(err[\"message\"])) return true;\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,IAAI,YAA2D;AAE/D,eAAe,UAA2D;CACtE,IAAI,WAAW,OAAO;CACtB,IAAI;EACA,YAAY,MAAM,OAAO;EACzB,OAAO;CACX,QAAQ;EACJ,MAAM,IAAI,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AAI,OAAO,IAAI,eAAe,YAAY,aAAa,KAAK,IAAI,UAAU,GAAG,OAAO;CACpF,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"GCSStorageController-CLIJXwGS.js","names":[],"sources":["../src/storage/GCSStorageController.ts"],"sourcesContent":["/**\n * Google Cloud Storage controller (works with GCS and Firebase Storage)\n *\n * The `@google-cloud/storage` package is loaded lazily so it remains an\n * optional peer dependency — users who don't need GCS never pay for the\n * import cost or need it installed.\n */\n\nimport {\n StorageController,\n GCSStorageConfig,\n DEFAULT_MAX_FILE_SIZE\n} from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n UploadFileProps,\n UploadFileResult,\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference\n} from \"@rebasepro/types\";\n\n// ---------------------------------------------------------------------------\n// Lazy import of @google-cloud/storage\n// ---------------------------------------------------------------------------\n\nlet gcsModule: typeof import(\"@google-cloud/storage\") | null = null;\n\nasync function loadGCS(): Promise<typeof import(\"@google-cloud/storage\")> {\n if (gcsModule) return gcsModule;\n try {\n gcsModule = await import(\"@google-cloud/storage\");\n return gcsModule;\n } catch {\n throw new Error(\n \"Google Cloud Storage is required for the GCS storage controller. \" +\n \"Install it with: pnpm add @google-cloud/storage\"\n );\n }\n}\n\n// ---------------------------------------------------------------------------\n// GCSStorageController\n// ---------------------------------------------------------------------------\n\n/**\n * Google Cloud Storage implementation of `StorageController`.\n *\n * Works with standard GCS buckets **and** Firebase Storage buckets\n * (e.g. `\"my-project.appspot.com\"`).\n */\nexport class GCSStorageController implements StorageController {\n private config: GCSStorageConfig;\n private client: InstanceType<typeof import(\"@google-cloud/storage\").Storage> | null = null;\n\n constructor(config: GCSStorageConfig) {\n this.config = config;\n }\n\n // ------------------------------------------------------------------\n // Lazy client initialisation\n // ------------------------------------------------------------------\n\n private async getClient(): Promise<InstanceType<typeof import(\"@google-cloud/storage\").Storage>> {\n if (this.client) return this.client;\n const { Storage } = await loadGCS();\n this.client = new Storage({\n projectId: this.config.projectId,\n keyFilename: this.config.keyFilename,\n credentials: this.config.credentials\n });\n return this.client;\n }\n\n // ------------------------------------------------------------------\n // StorageController interface\n // ------------------------------------------------------------------\n\n getType(): \"gcs\" {\n return \"gcs\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n * @see S3StorageController.knownBuckets\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n const client = await this.getClient();\n const gcsFile = client.bucket(usedBucket).file(key);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n await gcsFile.save(buffer, {\n contentType: file.type,\n metadata: metadata ? { metadata: this.flattenMetadata(metadata) } : undefined\n });\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `gs://${usedBucket}/${key}`\n };\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n // Get metadata first to check existence and populate response\n const [fileMetadata] = await gcsFile.getMetadata();\n\n // Generate a signed URL\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const [url] = await gcsFile.getSignedUrl({\n action: \"read\",\n expires: Date.now() + expiresIn * 1000\n });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: Number(fileMetadata.size) || 0,\n contentType: fileMetadata.contentType || \"application/octet-stream\",\n customMetadata: (fileMetadata.metadata as Record<string, string> | undefined) || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n const [contents] = await gcsFile.download();\n\n // Get content type from metadata\n const [fileMetadata] = await gcsFile.getMetadata();\n const contentType = fileMetadata.contentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([new Uint8Array(contents)], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle gs:// and s3:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(gs|s3):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const client = await this.getClient();\n const gcsFile = client.bucket(resolvedBucket).file(resolvedPath);\n\n await gcsFile.delete({ ignoreNotFound: true });\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n const client = await this.getClient();\n const gcsBucket = client.bucket(resolvedBucket);\n\n // Fetch files (objects) matching the prefix\n const [files, , filesApiResponse] = await gcsBucket.getFiles({\n prefix: listingPrefix(prefix),\n delimiter: \"/\",\n maxResults: options?.maxResults ?? 1000,\n pageToken: options?.pageToken,\n autoPaginate: false\n });\n\n const items: StorageReference[] = files.map(file => ({\n bucket: resolvedBucket,\n fullPath: file.name,\n name: file.name.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${file.name}`\n }));\n\n // Common prefixes (folder-like entries) come from the API response\n const apiPrefixes: string[] =\n (filesApiResponse as Record<string, unknown> | undefined)?.prefixes as string[] ?? [];\n\n const prefixes: StorageReference[] = apiPrefixes.map(p => {\n // Without the trailing slash GCS puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(p);\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `gs://${resolvedBucket}/${folder}`\n };\n });\n\n // The next page token is returned on the query object (second element)\n const nextPageToken =\n (filesApiResponse as Record<string, unknown> | undefined)?.nextPageToken as string | undefined;\n\n return {\n items,\n prefixes,\n nextPageToken\n };\n }\n\n // ------------------------------------------------------------------\n // Private helpers\n // ------------------------------------------------------------------\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name — either from parameter or config.\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for GCS it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n /**\n * Flatten nested metadata to string values (GCS custom metadata requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Error helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Check whether an error represents a 404 / Not Found from the GCS client.\n */\nfunction isNotFoundError(error: unknown): boolean {\n if (typeof error !== \"object\" || error === null) return false;\n const err = error as Record<string, unknown>;\n if (err[\"code\"] === 404) return true;\n if (typeof err[\"message\"] === \"string\" && /not found/i.test(err[\"message\"])) return true;\n return false;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2BA,IAAI,YAA2D;AAE/D,eAAe,UAA2D;CACtE,IAAI,WAAW,OAAO;CACtB,IAAI;EACA,YAAY,MAAM,OAAO;EACzB,OAAO;CACX,QAAQ;EACJ,MAAM,IAAI,MACN,kHAEJ;CACJ;AACJ;;;;;;;AAYA,IAAa,uBAAb,MAA+D;CAC3D;CACA,SAAsF;CAEtF,YAAY,QAA0B;EAClC,KAAK,SAAS;CAClB;CAMA,MAAc,YAAmF;EAC7F,IAAI,KAAK,QAAQ,OAAO,KAAK;EAC7B,MAAM,EAAE,YAAY,MAAM,QAAQ;EAClC,KAAK,SAAS,IAAI,QAAQ;GACtB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,aAAa,KAAK,OAAO;EAC7B,CAAC;EACD,OAAO,KAAK;CAChB;CAMA,UAAi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C,kBAA0D;EAM/D;CACJ;;;;CASA,aAAqB,MAAkB;EACnC,MAAM,UAAU,KAAK,OAAO,eAAA;EAC5B,IAAI,KAAK,OAAO,SACZ,MAAM,IAAI,MAAM,aAAa,KAAK,KAAK,gCAAgC,SAAS;EAGpF,IAAI,KAAK,OAAO,oBAAoB,KAAK,OAAO,iBAAiB,SAAS;OAClE,CAAC,KAAK,OAAO,iBAAiB,SAAS,KAAK,IAAI,GAChD,MAAM,IAAI,MAAM,aAAa,KAAK,KAAK,kCAAkC,KAAK,OAAO,iBAAiB,KAAK,IAAI,GAAG;EAAA;CAG9H;;;;CAKA,UAAkB,QAAyB;EAGvC,IAAI,CAAC,UAAU,WAAW,WAAW,OAAO,KAAK,OAAO;EACxD,OAAO;CACX;;;;CAKA,gBAAwB,UAA2D;EAC/E,MAAM,YAAoC,CAAC;EAC3C,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,GAC9C,IAAI,OAAO,UAAU,UACjB,UAAU,OAAO;OACd,IAAI,UAAU,KAAA,KAAa,UAAU,MACxC,UAAU,OAAO,KAAK,UAAU,KAAK;EAG7C,OAAO;CACX;AACJ;;;;AASA,SAAS,gBAAgB,OAAyB;CAC9C,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,MAAM;CACZ,IAAI,IAAI,YAAY,KAAK,OAAO;CAChC,IAAI,OAAO,IAAI,eAAe,YAAY,aAAa,KAAK,IAAI,UAAU,GAAG,OAAO;CACpF,OAAO;AACX"}
|
|
@@ -3,7 +3,7 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
|
-
import { o as folderKey, s as listingPrefix } from "./keys-
|
|
6
|
+
import { o as folderKey, s as listingPrefix } from "./keys-Qfc4XieN.js";
|
|
7
7
|
import "./types-BfKcm9do.js";
|
|
8
8
|
//#region src/storage/S3StorageController.ts
|
|
9
9
|
var S3StorageController_exports = /* @__PURE__ */ __exportAll({ S3StorageController: () => S3StorageController });
|
|
@@ -261,4 +261,4 @@ var S3StorageController = class {
|
|
|
261
261
|
//#endregion
|
|
262
262
|
export { S3StorageController_exports as n, S3StorageController as t };
|
|
263
263
|
|
|
264
|
-
//# sourceMappingURL=S3StorageController-
|
|
264
|
+
//# sourceMappingURL=S3StorageController-Dcuf8lMA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"S3StorageController-5pAXyv31.js","names":[],"sources":["../src/storage/S3StorageController.ts"],"sourcesContent":["/**\n * S3-compatible storage controller (works with AWS S3 and MinIO)\n */\n\nimport type { S3Client as S3ClientType, } from \"@aws-sdk/client-s3\";\nimport { DEFAULT_MAX_FILE_SIZE, S3StorageConfig, StorageController } from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference,\n UploadFileProps,\n UploadFileResult\n} from \"@rebasepro/types\";\n\nlet _s3Module: typeof import(\"@aws-sdk/client-s3\") | undefined;\nlet _presignerModule: typeof import(\"@aws-sdk/s3-request-presigner\") | undefined;\n\nasync function loadS3() {\n if (!_s3Module) {\n try {\n _s3Module = await import(\"@aws-sdk/client-s3\");\n } catch {\n throw new Error(\n \"@aws-sdk/client-s3 is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _s3Module;\n}\n\nasync function loadPresigner() {\n if (!_presignerModule) {\n try {\n _presignerModule = await import(\"@aws-sdk/s3-request-presigner\");\n } catch {\n throw new Error(\n \"@aws-sdk/s3-request-presigner is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _presignerModule;\n}\n\n/**\n * S3-compatible storage implementation\n * Works with AWS S3 and MinIO (with forcePathStyle option)\n */\nexport class S3StorageController implements StorageController {\n private config: S3StorageConfig;\n private _client: S3ClientType | undefined;\n\n constructor(config: S3StorageConfig) {\n this.config = config;\n }\n\n /**\n * Lazily create and cache the S3 client on first use\n */\n private async getClient(): Promise<S3ClientType> {\n if (!this._client) {\n const s3 = await loadS3();\n this._client = new s3.S3Client({\n region: this.config.region || \"us-east-1\",\n endpoint: this.config.endpoint,\n forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint, // Auto-enable for custom endpoints (MinIO)\n credentials: {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey\n }\n });\n }\n return this._client;\n }\n\n getType(): \"s3\" {\n return \"s3\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n *\n * Any other name went straight to S3 as a bucket name, so the request\n * parameter was a way to address *any* bucket the deployment's credentials\n * can reach — and a mistyped one came back as \"file not found\".\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name - either from parameter or config\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for S3 it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.PutObjectCommand({\n Bucket: usedBucket,\n Key: key,\n Body: buffer,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n });\n\n await client.send(command);\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Flatten nested metadata to string values (S3 requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle s3:// and gs:// URLs for backward compatibility\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const presigner = await loadPresigner();\n const client = await this.getClient();\n\n // First check if the object exists and get metadata\n const headCommand = new s3.HeadObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const headResult = await client.send(headCommand);\n\n // Generate a signed URL\n const getCommand = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: headResult.ContentLength || 0,\n contentType: headResult.ContentType || \"application/octet-stream\",\n customMetadata: headResult.Metadata || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NotFound\" || s3Error.$metadata?.httpStatusCode === 404) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const response = await client.send(command);\n\n if (!response.Body) {\n return null;\n }\n\n // Convert stream to buffer\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n\n const contentType = response.ContentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.DeleteObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n // Deleting something that is already gone is the outcome the caller\n // wanted, so it is not an error. AWS itself answers DeleteObject with\n // 204 for a key that never existed, but S3-compatible backends (MinIO,\n // Ceph, R2 in some configurations) do raise NoSuchKey — and the local\n // controller has always returned quietly in this case. Without this,\n // which of those a deployment happens to run decides whether\n // `DELETE /api/storage/:path` on a stale reference is a 200 or a 500.\n try {\n await client.send(command);\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return;\n }\n throw error;\n }\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: listingPrefix(prefix),\n MaxKeys: options?.maxResults ?? 1000,\n ContinuationToken: options?.pageToken,\n Delimiter: \"/\" // This gives us folder-like behavior\n });\n\n const response = await client.send(command);\n\n const items: StorageReference[] = (response.Contents || []).map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${obj.Key}`\n }));\n\n const prefixes: StorageReference[] = (response.CommonPrefixes || []).map(common => {\n // Without the trailing slash S3 puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(common.Prefix || \"\");\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${folder}`\n };\n });\n\n return {\n items,\n prefixes,\n nextPageToken: response.NextContinuationToken\n };\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,IAAI;AACJ,IAAI;AAEJ,eAAe,SAAS;CACpB,IAAI,CAAC,WACD,IAAI;EACA,YAAY,MAAM,OAAO;CAC7B,QAAQ;EACJ,MAAM,IAAI,MACN,sHAEJ;CACJ;CAEJ,OAAO;AACX;AAEA,eAAe,gBAAgB;CAC3B,IAAI,CAAC,kBACD,IAAI;EACA,mBAAmB,MAAM,OAAO;CACpC,QAAQ;EACJ,MAAM,IAAI,MACN,iIAEJ;CACJ;CAEJ,OAAO;AACX;;;;;AAMA,IAAa,sBAAb,MAA8D;CAC1D;CACA;CAEA,YAAY,QAAyB;EACjC,KAAK,SAAS;CAClB;;;;CAKA,MAAc,YAAmC;EAC7C,IAAI,CAAC,KAAK,SAAS;GACf,MAAM,KAAK,MAAM,OAAO;GACxB,KAAK,UAAU,IAAI,GAAG,SAAS;IAC3B,QAAQ,KAAK,OAAO,UAAU;IAC9B,UAAU,KAAK,OAAO;IACtB,gBAAgB,KAAK,OAAO,kBAAkB,CAAC,CAAC,KAAK,OAAO;IAC5D,aAAa;KACT,aAAa,KAAK,OAAO;KACzB,iBAAiB,KAAK,OAAO;IACjC;GACJ,CAAC;EACL;EACA,OAAO,KAAK;CAChB;CAEA,UAAgB;EACZ,OAAO;CACX;;;;;;;;CASA,eAAyB;EACrB,OAAO,CAAC,WAAW,KAAK,OAAO,MAAM;CACzC;;;;CAKA,aAAqB,MAAkB;EACnC,MAAM,UAAU,KAAK,OAAO,eAAA;EAC5B,IAAI,KAAK,OAAO,SACZ,MAAM,IAAI,MAAM,aAAa,KAAK,KAAK,gCAAgC,SAAS;EAGpF,IAAI,KAAK,OAAO,oBAAoB,KAAK,OAAO,iBAAiB,SAAS;OAClE,CAAC,KAAK,OAAO,iBAAiB,SAAS,KAAK,I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I;GACA,MAAM,OAAO,KAAK,OAAO;EAC7B,SAAS,OAAgB;GACrB,MAAM,UAAU;GAChB,IAAI,QAAQ,SAAS,eAAe,QAAQ,WAAW,mBAAmB,KACtE;GAEJ,MAAM;EACV;CACJ;CAEA,MAAM,YAAY,QAAgB,SAIH;EAC3B,MAAM,iBAAiB,KAAK,UAAU,SAAS,MAAM;EAErD,MAAM,KAAK,MAAM,OAAO;EACxB,MAAM,SAAS,MAAM,KAAK,UAAU;EAEpC,MAAM,UAAU,IAAI,GAAG,qBAAqB;GACxC,QAAQ;GACR,QAAQ,cAAc,MAAM;GAC5B,SAAS,SAAS,cAAc;GAChC,mBAAmB,SAAS;GAC5B,WAAW;EACf,CAAC;EAED,MAAM,WAAW,MAAM,OAAO,KAAK,OAAO;EAyB1C,OAAO;GACH,QAxB+B,SAAS,YAAY,CAAC,EAAA,CAAG,KAAI,SAAQ;IACpE,QAAQ;IACR,UAAU,IAAI,OAAO;IACrB,OAAO,IAAI,OAAO,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;IAC1C,QAAQ;IACR,MAAM;IACN,gBAAgB,QAAQ,eAAe,GAAG,IAAI;GAClD,EAiBI;GACA,WAhBkC,SAAS,kBAAkB,CAAC,EAAA,CAAG,KAAI,WAAU;IAG/E,MAAM,SAAS,UAAU,OAAO,UAAU,EAAE;IAC5C,OAAO;KACH,QAAQ;KACR,UAAU;KACV,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;KACjC,QAAQ;KACR,MAAM;KACN,gBAAgB,QAAQ,eAAe,GAAG;IAC9C;GACJ,CAII;GACA,eAAe,SAAS;EAC5B;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"S3StorageController-Dcuf8lMA.js","names":[],"sources":["../src/storage/S3StorageController.ts"],"sourcesContent":["/**\n * S3-compatible storage controller (works with AWS S3 and MinIO)\n */\n\nimport type { S3Client as S3ClientType, } from \"@aws-sdk/client-s3\";\nimport { DEFAULT_MAX_FILE_SIZE, S3StorageConfig, StorageController } from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport {\n DownloadConfig,\n DownloadMetadata,\n StorageListResult,\n StorageReference,\n UploadFileProps,\n UploadFileResult\n} from \"@rebasepro/types\";\n\nlet _s3Module: typeof import(\"@aws-sdk/client-s3\") | undefined;\nlet _presignerModule: typeof import(\"@aws-sdk/s3-request-presigner\") | undefined;\n\nasync function loadS3() {\n if (!_s3Module) {\n try {\n _s3Module = await import(\"@aws-sdk/client-s3\");\n } catch {\n throw new Error(\n \"@aws-sdk/client-s3 is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _s3Module;\n}\n\nasync function loadPresigner() {\n if (!_presignerModule) {\n try {\n _presignerModule = await import(\"@aws-sdk/s3-request-presigner\");\n } catch {\n throw new Error(\n \"@aws-sdk/s3-request-presigner is required for S3 storage. \" +\n \"Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner\"\n );\n }\n }\n return _presignerModule;\n}\n\n/**\n * S3-compatible storage implementation\n * Works with AWS S3 and MinIO (with forcePathStyle option)\n */\nexport class S3StorageController implements StorageController {\n private config: S3StorageConfig;\n private _client: S3ClientType | undefined;\n\n constructor(config: S3StorageConfig) {\n this.config = config;\n }\n\n /**\n * Lazily create and cache the S3 client on first use\n */\n private async getClient(): Promise<S3ClientType> {\n if (!this._client) {\n const s3 = await loadS3();\n this._client = new s3.S3Client({\n region: this.config.region || \"us-east-1\",\n endpoint: this.config.endpoint,\n forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint, // Auto-enable for custom endpoints (MinIO)\n credentials: {\n accessKeyId: this.config.accessKeyId,\n secretAccessKey: this.config.secretAccessKey\n }\n });\n }\n return this._client;\n }\n\n getType(): \"s3\" {\n return \"s3\";\n }\n\n /**\n * The configured bucket, and the logical `default` that maps to it.\n *\n * Any other name went straight to S3 as a bucket name, so the request\n * parameter was a way to address *any* bucket the deployment's credentials\n * can reach — and a mistyped one came back as \"file not found\".\n */\n knownBuckets(): string[] {\n return [\"default\", this.config.bucket];\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n const maxSize = this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n if (file.size > maxSize) {\n throw new Error(`File size ${file.size} exceeds maximum allowed size ${maxSize}`);\n }\n\n if (this.config.allowedMimeTypes && this.config.allowedMimeTypes.length > 0) {\n if (!this.config.allowedMimeTypes.includes(file.type)) {\n throw new Error(`File type ${file.type} is not allowed. Allowed types: ${this.config.allowedMimeTypes.join(\", \")}`);\n }\n }\n }\n\n /**\n * Get the bucket name - either from parameter or config\n */\n private getBucket(bucket?: string): string {\n // \"default\" is a logical bucket name used by local storage;\n // for S3 it should resolve to the configured bucket.\n if (!bucket || bucket === \"default\") return this.config.bucket;\n return bucket;\n }\n\n async putObject({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps): Promise<UploadFileResult> {\n this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n\n // Convert File to Buffer\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.PutObjectCommand({\n Bucket: usedBucket,\n Key: key,\n Body: buffer,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n });\n\n await client.send(command);\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Flatten nested metadata to string values (S3 requirement)\n */\n private flattenMetadata(metadata: Record<string, unknown>): Record<string, string> {\n const flattened: Record<string, string> = {};\n for (const [key, value] of Object.entries(metadata)) {\n if (typeof value === \"string\") {\n flattened[key] = value;\n } else if (value !== undefined && value !== null) {\n flattened[key] = JSON.stringify(value);\n }\n }\n return flattened;\n }\n\n async getSignedUrl(key: string, bucket?: string): Promise<DownloadConfig> {\n // Handle s3:// and gs:// URLs for backward compatibility\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const presigner = await loadPresigner();\n const client = await this.getClient();\n\n // First check if the object exists and get metadata\n const headCommand = new s3.HeadObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const headResult = await client.send(headCommand);\n\n // Generate a signed URL\n const getCommand = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const expiresIn = this.config.signedUrlExpiration ?? 3600;\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn });\n\n const metadata: DownloadMetadata = {\n bucket: resolvedBucket,\n fullPath: resolvedPath,\n name: resolvedPath.split(\"/\").pop() || resolvedPath,\n size: headResult.ContentLength || 0,\n contentType: headResult.ContentType || \"application/octet-stream\",\n customMetadata: headResult.Metadata || {}\n };\n\n return {\n url,\n metadata\n };\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NotFound\" || s3Error.$metadata?.httpStatusCode === 404) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw error;\n }\n }\n\n async getObject(key: string, bucket?: string): Promise<File | null> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n try {\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.GetObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n const response = await client.send(command);\n\n if (!response.Body) {\n return null;\n }\n\n // Convert stream to buffer\n const chunks: Uint8Array[] = [];\n for await (const chunk of response.Body as AsyncIterable<Uint8Array>) {\n chunks.push(chunk);\n }\n const buffer = Buffer.concat(chunks);\n\n const contentType = response.ContentType || \"application/octet-stream\";\n const fileName = resolvedPath.split(\"/\").pop() || resolvedPath;\n\n const blob = new Blob([buffer], { type: contentType });\n return new File([blob], fileName, { type: contentType });\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return null;\n }\n throw error;\n }\n }\n\n async deleteObject(key: string, bucket?: string): Promise<void> {\n // Handle s3:// and gs:// URLs\n let resolvedPath = key;\n let resolvedBucket = this.getBucket(bucket);\n\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const protocolLength = match[0].length;\n const withoutProtocol = key.substring(protocolLength);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n resolvedBucket = withoutProtocol.substring(0, firstSlash);\n resolvedPath = withoutProtocol.substring(firstSlash + 1);\n }\n }\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.DeleteObjectCommand({\n Bucket: resolvedBucket,\n Key: resolvedPath\n });\n\n // Deleting something that is already gone is the outcome the caller\n // wanted, so it is not an error. AWS itself answers DeleteObject with\n // 204 for a key that never existed, but S3-compatible backends (MinIO,\n // Ceph, R2 in some configurations) do raise NoSuchKey — and the local\n // controller has always returned quietly in this case. Without this,\n // which of those a deployment happens to run decides whether\n // `DELETE /api/storage/:path` on a stale reference is a 200 or a 500.\n try {\n await client.send(command);\n } catch (error: unknown) {\n const s3Error = error as { name?: string; $metadata?: { httpStatusCode?: number } };\n if (s3Error.name === \"NoSuchKey\" || s3Error.$metadata?.httpStatusCode === 404) {\n return;\n }\n throw error;\n }\n }\n\n async listObjects(prefix: string, options?: {\n bucket?: string;\n maxResults?: number;\n pageToken?: string;\n }): Promise<StorageListResult> {\n const resolvedBucket = this.getBucket(options?.bucket);\n\n const s3 = await loadS3();\n const client = await this.getClient();\n\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: listingPrefix(prefix),\n MaxKeys: options?.maxResults ?? 1000,\n ContinuationToken: options?.pageToken,\n Delimiter: \"/\" // This gives us folder-like behavior\n });\n\n const response = await client.send(command);\n\n const items: StorageReference[] = (response.Contents || []).map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${obj.Key}`\n }));\n\n const prefixes: StorageReference[] = (response.CommonPrefixes || []).map(common => {\n // Without the trailing slash S3 puts on a common prefix, so a\n // `fullPath` from a listing is a key any controller accepts.\n const folder = folderKey(common.Prefix || \"\");\n return {\n bucket: resolvedBucket,\n fullPath: folder,\n name: folder.split(\"/\").pop() || \"\",\n parent: null as never,\n root: null as never,\n toString: () => `s3://${resolvedBucket}/${folder}`\n };\n });\n\n return {\n items,\n prefixes,\n nextPageToken: response.NextContinuationToken\n };\n }\n}\n"],"mappings":";;;;;;;;;AAgBA,IAAI;AACJ,IAAI;AAEJ,eAAe,SAAS;CACpB,IAAI,CAAC,WACD,IAAI;EACA,YAAY,MAAM,OAAO;CAC7B,QAAQ;EACJ,MAAM,IAAI,MACN,sHAEJ;CACJ;CAEJ,OAAO;AACX;AAEA,eAAe,gBAAgB;CAC3B,IAAI,CAAC,kBACD,IAAI;EACA,mBAAmB,MAAM,OAAO;CACpC,QAAQ;EACJ,MAAM,IAAI,MACN,iIAEJ;CACJ;CAEJ,OAAO;AACX;;;;;AAMA,IAAa,sBAAb,MAA8D;CAC1D;CACA;CAEA,YAAY,QAAyB;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YAAY,CAAC,EAAA,CAAG,KAAI,SAAQ;IACpE,QAAQ;IACR,UAAU,IAAI,OAAO;IACrB,OAAO,IAAI,OAAO,GAAA,CAAI,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;IAC1C,QAAQ;IACR,MAAM;IACN,gBAAgB,QAAQ,eAAe,GAAG,IAAI;GAClD,EAiBI;GACA,WAhBkC,SAAS,kBAAkB,CAAC,EAAA,CAAG,KAAI,WAAU;IAG/E,MAAM,SAAS,UAAU,OAAO,UAAU,EAAE;IAC5C,OAAO;KACH,QAAQ;KACR,UAAU;KACV,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,IAAI,KAAK;KACjC,QAAQ;KACR,MAAM;KACN,gBAAgB,QAAQ,eAAe,GAAG;IAC9C;GACJ,CAII;GACA,eAAe,SAAS;EAC5B;CACJ;AACJ"}
|
package/dist/api/errors.d.ts
CHANGED
|
@@ -64,7 +64,12 @@ export declare class ApiError extends Error {
|
|
|
64
64
|
static unauthenticated(message: string, code?: string): ApiError;
|
|
65
65
|
static forbidden(message: string, code?: string): ApiError;
|
|
66
66
|
static notFound(message: string, code?: string): ApiError;
|
|
67
|
-
|
|
67
|
+
/**
|
|
68
|
+
* `details` because a 409 is usually a `23505`, and the one thing the
|
|
69
|
+
* caller needs is *which field* collided. The column name goes in; the
|
|
70
|
+
* value never does — see `pgFieldViolations`.
|
|
71
|
+
*/
|
|
72
|
+
static conflict(message: string, code?: string, details?: unknown): ApiError;
|
|
68
73
|
static internal(message: string, code?: string): ApiError;
|
|
69
74
|
static serviceUnavailable(message: string, code?: string): ApiError;
|
|
70
75
|
}
|
|
@@ -32,6 +32,28 @@ export declare class RestApiGenerator {
|
|
|
32
32
|
* Generate REST routes using existing DataDriver
|
|
33
33
|
*/
|
|
34
34
|
generateRoutes(): Hono<HonoEnv>;
|
|
35
|
+
/**
|
|
36
|
+
* `POST /api/data/_batch` — writes across collections, as one transaction.
|
|
37
|
+
*
|
|
38
|
+
* `/bulk` is one collection at a time, which is the wrong shape for the
|
|
39
|
+
* writes that most need to be atomic: an order and its line items, a user
|
|
40
|
+
* and their membership row, a document and its audit entry. Sent as
|
|
41
|
+
* separate requests those half-succeed, and the recovery — read back, work
|
|
42
|
+
* out which half landed, undo it — is code nobody writes and everybody
|
|
43
|
+
* needs.
|
|
44
|
+
*
|
|
45
|
+
* Underscored so it cannot collide with a collection: a slug is a table
|
|
46
|
+
* name and Postgres identifiers do not start with one, so `_batch` is a
|
|
47
|
+
* name no `db push` can produce.
|
|
48
|
+
*
|
|
49
|
+
* Every operation is checked before the transaction opens — shape, unknown
|
|
50
|
+
* collections, unknown fields, value constraints, field operations,
|
|
51
|
+
* conflict targets, forward `$ref`s — because a batch is all-or-nothing and
|
|
52
|
+
* finding a typo at operation 40 costs the rollback of the 39 writes before
|
|
53
|
+
* it. Inside, each operation runs the pipeline its single-row route runs:
|
|
54
|
+
* the same callbacks, the same row-level security, as the same role.
|
|
55
|
+
*/
|
|
56
|
+
private createBatchRoute;
|
|
35
57
|
/**
|
|
36
58
|
* A 404 that says which row was not found, and names the other reason.
|
|
37
59
|
*
|
|
@@ -124,6 +146,50 @@ export declare class RestApiGenerator {
|
|
|
124
146
|
* back to the unscoped `this.driver` to avoid bypassing RLS/auth.
|
|
125
147
|
*/
|
|
126
148
|
private getScopedDriver;
|
|
149
|
+
/**
|
|
150
|
+
* Run a write under an idempotency key.
|
|
151
|
+
*
|
|
152
|
+
* Every keyed route needs the identical claim-before-write dance — claim,
|
|
153
|
+
* replay on a repeat, 409 while one is in flight, release on failure,
|
|
154
|
+
* complete on success — and getting one of those steps wrong is exactly the
|
|
155
|
+
* bug the key exists to prevent. Written once so they cannot drift into
|
|
156
|
+
* different notions of "already done".
|
|
157
|
+
*
|
|
158
|
+
* It lived inside `createCollectionRoutes` and served the three bulk routes
|
|
159
|
+
* only, which is why the single-row `PATCH` and `DELETE` ignored the header
|
|
160
|
+
* the SDK has always sent them: the mechanism was one closure away from
|
|
161
|
+
* them, and nothing said so. A method reaches every route, including the
|
|
162
|
+
* cross-collection batch.
|
|
163
|
+
*
|
|
164
|
+
* `body` is what the key is claimed *for*: the same key on a different
|
|
165
|
+
* request is a caller mistake, and replaying a create's answer to a delete
|
|
166
|
+
* would report a deletion that never happened.
|
|
167
|
+
*
|
|
168
|
+
* `respond` is applied to the *stored* result rather than the stored result
|
|
169
|
+
* being a response, so a replay honours the `Prefer` header of the request
|
|
170
|
+
* replaying it rather than the one that first answered.
|
|
171
|
+
*/
|
|
172
|
+
private runIdempotent;
|
|
173
|
+
/**
|
|
174
|
+
* The row as the read routes serve it, for hashing into an `ETag`.
|
|
175
|
+
*
|
|
176
|
+
* A tag derived from a version column is the same whichever read produced
|
|
177
|
+
* the row, so nothing extra is fetched for it. The fallback hashes the row
|
|
178
|
+
* itself, and there the *shape* matters: `GET /:id` serves the REST walk
|
|
179
|
+
* while the write routes read through `driver.fetchOne` (the admin view
|
|
180
|
+
* model), so hashing whichever one happened to be in hand would give the
|
|
181
|
+
* same row two different tags and make every `If-Match` a coin toss.
|
|
182
|
+
*/
|
|
183
|
+
private rowForETag;
|
|
184
|
+
/**
|
|
185
|
+
* Answer a bulk write, honouring `Prefer: return=minimal`.
|
|
186
|
+
*
|
|
187
|
+
* Minimal is a 200 carrying the ids rather than a 204 — see
|
|
188
|
+
* {@link rowIdentity} for why a batch keeps them when a single write does
|
|
189
|
+
* not. `meta.written` is unchanged either way, so a caller that only wants
|
|
190
|
+
* the count never has to ask for the rows.
|
|
191
|
+
*/
|
|
192
|
+
private respondBulk;
|
|
127
193
|
/**
|
|
128
194
|
* Create REST routes for a collection using existing Rebase patterns
|
|
129
195
|
*/
|
|
@@ -151,6 +217,20 @@ export declare class RestApiGenerator {
|
|
|
151
217
|
* Format successful API response
|
|
152
218
|
*/
|
|
153
219
|
private formatResponse;
|
|
220
|
+
/**
|
|
221
|
+
* One page of a listing: the rows, and the `meta` that describes them.
|
|
222
|
+
*
|
|
223
|
+
* Written once because it was written twice — the root listing and the
|
|
224
|
+
* nested one each built their own `meta`, from their own idea of what
|
|
225
|
+
* `hasMore` meant, over reads assembled from slightly different option
|
|
226
|
+
* lists. Anything added to one (a cursor, a distinct read, an `include`
|
|
227
|
+
* that now nests) had to be remembered in the other, and the nested route
|
|
228
|
+
* is the one that kept being forgotten.
|
|
229
|
+
*
|
|
230
|
+
* @param collectionPath the path to read — a nested listing passes its own
|
|
231
|
+
* `parent/:id/child` path, which the driver resolves.
|
|
232
|
+
*/
|
|
233
|
+
private readPage;
|
|
154
234
|
/**
|
|
155
235
|
* Fetch raw collection data without Entity wrapper (fallback for non-Postgres)
|
|
156
236
|
*/
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { BATCH_REF_KEY } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Cross-collection writes that land together or not at all.
|
|
4
|
+
*
|
|
5
|
+
* `/bulk` is one collection at a time, which is the wrong shape for the writes
|
|
6
|
+
* that most need atomicity: an order and its line items, a user and their
|
|
7
|
+
* membership row, a document and its audit entry. Sent as separate requests
|
|
8
|
+
* they can half-succeed, and the recovery — read back, work out which half
|
|
9
|
+
* landed, undo it — is code nobody writes and everybody needs.
|
|
10
|
+
*
|
|
11
|
+
* A batch is one transaction under the caller's own RLS role, with every
|
|
12
|
+
* operation running the same pipeline the single routes run: the same
|
|
13
|
+
* validation, the same callbacks, the same policies. The one thing it adds is
|
|
14
|
+
* `$ref`, because the sequence it exists to express — create a parent, then
|
|
15
|
+
* point children at it — needs a value the caller cannot know before sending.
|
|
16
|
+
*
|
|
17
|
+
* @module
|
|
18
|
+
*/
|
|
19
|
+
/**
|
|
20
|
+
* The marker key, re-exported from `@rebasepro/types` where it is declared
|
|
21
|
+
* beside the field operators — the two share the `$`-prefixed namespace, and
|
|
22
|
+
* the predicate that recognises a field operation has to know this one is not.
|
|
23
|
+
*/
|
|
24
|
+
export { BATCH_REF_KEY };
|
|
25
|
+
/** Operations accepted in one batch, mirroring the single-row routes. */
|
|
26
|
+
export declare const BATCH_OPS: readonly ["create", "update", "upsert", "delete"];
|
|
27
|
+
export type BatchOp = typeof BATCH_OPS[number];
|
|
28
|
+
/** One operation, after the envelope has been checked but before RLS sees it. */
|
|
29
|
+
export interface ParsedBatchOperation {
|
|
30
|
+
op: BatchOp;
|
|
31
|
+
/** The collection slug, validated against the collections this API serves. */
|
|
32
|
+
collection: string;
|
|
33
|
+
id?: unknown;
|
|
34
|
+
values?: Record<string, unknown>;
|
|
35
|
+
onConflict?: string[];
|
|
36
|
+
/** The name later operations may reference this one's result by. */
|
|
37
|
+
ref?: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Replace every `$ref` marker under `value` with what the named operation wrote.
|
|
41
|
+
*
|
|
42
|
+
* Recursive rather than top-level-only: a foreign key is usually a top-level
|
|
43
|
+
* column, but a `map` column holding `{ meta: { orderId: … } }` is an ordinary
|
|
44
|
+
* shape and there is no principled reason for the marker to stop working one
|
|
45
|
+
* level down.
|
|
46
|
+
*
|
|
47
|
+
* Runs inside the transaction, because that is the only place the earlier
|
|
48
|
+
* operation's result exists.
|
|
49
|
+
*/
|
|
50
|
+
export declare function resolveBatchRefs(value: unknown, resolved: ReadonlyMap<string, Record<string, unknown>>): unknown;
|
|
51
|
+
/**
|
|
52
|
+
* Check the envelope of a batch body and hand back the operations.
|
|
53
|
+
*
|
|
54
|
+
* Everything here is decided before the transaction opens. A batch is
|
|
55
|
+
* all-or-nothing, so a shape error found half-way in costs a rollback of every
|
|
56
|
+
* operation before it — and the caller learns about entry 40 only after 39
|
|
57
|
+
* writes have been done and undone.
|
|
58
|
+
*/
|
|
59
|
+
export declare function parseBatchBody(body: unknown, options: {
|
|
60
|
+
knownCollections: ReadonlySet<string>;
|
|
61
|
+
maxOperations: number;
|
|
62
|
+
}): ParsedBatchOperation[];
|
|
63
|
+
/**
|
|
64
|
+
* Refuse a `$ref` that points at an operation which does not exist, or which
|
|
65
|
+
* comes later.
|
|
66
|
+
*
|
|
67
|
+
* Checked up front rather than left to fail inside the transaction: a forward
|
|
68
|
+
* reference is a static property of the body, and finding it at operation 40
|
|
69
|
+
* costs the rollback of the 39 writes before it.
|
|
70
|
+
*/
|
|
71
|
+
export declare function assertRefsResolvable(operations: readonly ParsedBatchOperation[]): void;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { CollectionConfig } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Every column set this collection declares a uniqueness guarantee over.
|
|
4
|
+
*
|
|
5
|
+
* Three sources, and they are not interchangeable:
|
|
6
|
+
* - the primary key, which is always there and is the default target;
|
|
7
|
+
* - `validation.unique` on a property, which compiles to an inline `UNIQUE`;
|
|
8
|
+
* - a `unique: true` btree index, which is the *only* way to declare a
|
|
9
|
+
* composite guarantee (see `BtreeIndex.unique`).
|
|
10
|
+
*/
|
|
11
|
+
export declare function declaredUniqueTargets(collection: CollectionConfig): string[][];
|
|
12
|
+
/**
|
|
13
|
+
* Parse and check the columns an upsert wants to match on.
|
|
14
|
+
*
|
|
15
|
+
* Returns `undefined` when the caller named none, which means the primary key —
|
|
16
|
+
* the behaviour bulk `upsert: true` has always had.
|
|
17
|
+
*/
|
|
18
|
+
export declare function resolveConflictTarget(raw: unknown, collection: CollectionConfig, options?: {
|
|
19
|
+
where?: string;
|
|
20
|
+
}): string[] | undefined;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { CollectionConfig } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Optimistic concurrency for the row routes: an edit that names the version it
|
|
4
|
+
* was made against, and is refused when that version has moved on.
|
|
5
|
+
*
|
|
6
|
+
* Without it every `PATCH` is last-writer-wins over whatever it did not send.
|
|
7
|
+
* That is fine for a single field typed into a form; it is wrong for the shape
|
|
8
|
+
* the admin, the CMS and every SDK caller actually produce — read the row,
|
|
9
|
+
* change part of it, send the merge back. Two editors doing that a second apart
|
|
10
|
+
* both succeed, and the first one's change is gone with no error anywhere.
|
|
11
|
+
*
|
|
12
|
+
* The mechanism is HTTP's own: `GET` hands back an `ETag`, and a later write
|
|
13
|
+
* sends it as `If-Match`. A mismatch is `412 Precondition Failed`, which says
|
|
14
|
+
* "re-read and try again" — a thing a client can act on, unlike silence.
|
|
15
|
+
*
|
|
16
|
+
* @module
|
|
17
|
+
*/
|
|
18
|
+
/** The response/request header names, spelled once. */
|
|
19
|
+
export declare const ETAG_HEADER = "ETag";
|
|
20
|
+
export declare const IF_MATCH_HEADER = "If-Match";
|
|
21
|
+
/**
|
|
22
|
+
* The property whose value is the row's version, when the collection has one.
|
|
23
|
+
*
|
|
24
|
+
* A `date` property with `autoValue: "on_update"` is stamped by the database on
|
|
25
|
+
* every write, so it already *is* a version — deriving the tag from it means
|
|
26
|
+
* the tag changes when and only when the row does, and two backends serving the
|
|
27
|
+
* same table agree on it. The alternative below (hashing the row) is correct
|
|
28
|
+
* but coarser: it changes when the *serialisation* changes, which includes
|
|
29
|
+
* columns a caller cannot see and excludes nothing.
|
|
30
|
+
*
|
|
31
|
+
* The first such property in declaration order, so a collection with two of
|
|
32
|
+
* them picks deterministically rather than by object-key luck.
|
|
33
|
+
*/
|
|
34
|
+
export declare function versionProperty(collection: CollectionConfig | undefined): string | undefined;
|
|
35
|
+
/**
|
|
36
|
+
* The entity tag for a row: quoted, per RFC 9110, and strong.
|
|
37
|
+
*
|
|
38
|
+
* Strong rather than weak (`W/"…"`) because it is derived from the stored
|
|
39
|
+
* values themselves, not from a rendering of them — two responses with this tag
|
|
40
|
+
* describe the same row, byte differences in transport encoding aside. `If-Match`
|
|
41
|
+
* is defined to use strong comparison, so a weak tag would be refused by a
|
|
42
|
+
* conditional write in every conforming intermediary.
|
|
43
|
+
*/
|
|
44
|
+
export declare function rowETag(row: Record<string, unknown> | undefined, collection: CollectionConfig | undefined): Promise<string | undefined>;
|
|
45
|
+
/**
|
|
46
|
+
* Refuse the write when the row has moved on since the caller read it.
|
|
47
|
+
*
|
|
48
|
+
* No header means no precondition — the write proceeds, which keeps every
|
|
49
|
+
* existing client working and makes concurrency control something a caller
|
|
50
|
+
* opts into per request rather than a mode the server is in.
|
|
51
|
+
*/
|
|
52
|
+
export declare function assertIfMatch(ifMatch: string | undefined, row: Record<string, unknown> | undefined, collection: CollectionConfig | undefined, context: {
|
|
53
|
+
collection: string;
|
|
54
|
+
id: string;
|
|
55
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { CollectionConfig } from "@rebasepro/types";
|
|
2
|
+
import type { LogicalCondition } from "@rebasepro/types";
|
|
3
|
+
import { type FieldViewer } from "@rebasepro/common";
|
|
4
|
+
/**
|
|
5
|
+
* A read may not name a field the caller cannot read.
|
|
6
|
+
*
|
|
7
|
+
* The strip in the row pipeline is what keeps the *value* off the wire. This is
|
|
8
|
+
* the other half, and without it the value is still readable one bit at a time:
|
|
9
|
+
* `?salary=gt.100000` returns the rows whose withheld salary is above 100k, and
|
|
10
|
+
* `?orderBy=salary` returns them in order of it. A column no response can carry
|
|
11
|
+
* has to be a column no query can interrogate, or the read rule is decoration.
|
|
12
|
+
*
|
|
13
|
+
* The refusal names the field. That is deliberate and it is not a leak: the
|
|
14
|
+
* published OpenAPI lists every property of every collection, including the ones
|
|
15
|
+
* a given caller cannot read, because the document is one document and is served
|
|
16
|
+
* off the app rather than off the authenticated data router. Hiding the name
|
|
17
|
+
* here would protect nothing and would answer a caller's genuine typo with
|
|
18
|
+
* "unknown field", sending them to look for a spelling mistake that is not
|
|
19
|
+
* there. Field *names* are public; field *values* are not.
|
|
20
|
+
*
|
|
21
|
+
* @module
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* The roles behind a request, as a viewer a field rule can judge.
|
|
25
|
+
*
|
|
26
|
+
* Never `undefined`, and that is the point. `undefined` means the trusted server
|
|
27
|
+
* plane in {@link FieldViewer}, which satisfies every non-empty role list — so
|
|
28
|
+
* returning it for a request that merely has no `user` on the context would
|
|
29
|
+
* hand an unauthenticated caller every field in the database. The auth
|
|
30
|
+
* middleware scopes such a request's driver as `roles: ["anon"]` but sets no
|
|
31
|
+
* `user`, so the fallback here has to be the same list the driver was scoped
|
|
32
|
+
* with, not nothing.
|
|
33
|
+
*
|
|
34
|
+
* @param c anything carrying the Hono context's `get` — the batch route passes a
|
|
35
|
+
* shim rather than the context itself, exactly as the API-key
|
|
36
|
+
* permission check does.
|
|
37
|
+
*/
|
|
38
|
+
export declare function requestViewer(c: {
|
|
39
|
+
get: (key: never) => unknown;
|
|
40
|
+
}): FieldViewer;
|
|
41
|
+
/** Which query parameter a refused field arrived in, for the message. */
|
|
42
|
+
type Where = "filter" | "orderBy" | "fields" | "select" | "groupBy";
|
|
43
|
+
/**
|
|
44
|
+
* Refuse the request when any of `names` is a field this caller cannot read.
|
|
45
|
+
*
|
|
46
|
+
* Exported so the aggregate route — whose `select` and `groupBy` are parsed
|
|
47
|
+
* outside `parseQueryOptions` — applies the identical rule. `count(*)` over a
|
|
48
|
+
* withheld column is the same disclosure as reading it, one predicate at a time.
|
|
49
|
+
*/
|
|
50
|
+
export declare function assertReadableFields(names: readonly (string | undefined)[], collection: CollectionConfig, viewer: FieldViewer | undefined, where: Where): void;
|
|
51
|
+
/**
|
|
52
|
+
* The whole of a parsed read request, checked in one pass.
|
|
53
|
+
*
|
|
54
|
+
* One call rather than five, because five call sites is five chances to add a
|
|
55
|
+
* sixth query parameter and forget it — which is exactly how `?or=` came to be
|
|
56
|
+
* parsed and then dropped by the list route.
|
|
57
|
+
*/
|
|
58
|
+
export declare function assertQueryFieldsReadable(options: {
|
|
59
|
+
where?: Record<string, unknown>;
|
|
60
|
+
logical?: LogicalCondition;
|
|
61
|
+
orderBy?: {
|
|
62
|
+
field: string;
|
|
63
|
+
}[];
|
|
64
|
+
fields?: string[];
|
|
65
|
+
}, collection: CollectionConfig, viewer: FieldViewer | undefined): void;
|
|
66
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { CollectionConfig, FieldOperation, FIELD_OPERATORS, isFieldOperation } from "@rebasepro/types";
|
|
2
|
+
/**
|
|
3
|
+
* Writes expressed as a change to the column's current value.
|
|
4
|
+
*
|
|
5
|
+
* `PATCH { views: 5 }` says what the number becomes. Saying what *happens* to
|
|
6
|
+
* it needs a read first — and that read is where the counter is lost: two
|
|
7
|
+
* requests that each read `4`, add one and write `5` end at `5`, not `6`, and
|
|
8
|
+
* nothing in the response tells either of them an increment went missing. It is
|
|
9
|
+
* not a rare interleaving either; it is the ordinary shape of a view counter, a
|
|
10
|
+
* stock level, an inventory reservation, a tag list two people edit.
|
|
11
|
+
*
|
|
12
|
+
* `{ views: { $inc: 1 } }` compiles to `SET views = views + 1`, so the
|
|
13
|
+
* arithmetic happens inside the statement that already holds the row lock and
|
|
14
|
+
* there is no window to lose. Same for the array and jsonb forms.
|
|
15
|
+
*
|
|
16
|
+
* This module is the *contract* — what the operators are, what shapes they
|
|
17
|
+
* accept, and which property types they are legal on. Compiling one to SQL is
|
|
18
|
+
* the driver's job (`@rebasepro/server-postgres`), because only the driver
|
|
19
|
+
* knows whether an `array` property is a native `text[]` or a jsonb document,
|
|
20
|
+
* and those need different statements.
|
|
21
|
+
*
|
|
22
|
+
* @module
|
|
23
|
+
*/
|
|
24
|
+
export type FieldOperator = typeof FIELD_OPERATORS[number];
|
|
25
|
+
/** One parsed operation: which operator, and what it was given. */
|
|
26
|
+
export interface ParsedFieldOp {
|
|
27
|
+
operator: FieldOperator;
|
|
28
|
+
operand: unknown;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Whether a value is *trying* to be a field operation, misspellings included.
|
|
32
|
+
*
|
|
33
|
+
* That is the point: `{ $increment: 1 }` silently stored as a jsonb document on
|
|
34
|
+
* a number column is the failure mode this module exists to make impossible, so
|
|
35
|
+
* an attempted operation that is not a legal one has to be an error rather than
|
|
36
|
+
* a value. The predicate itself lives in `@rebasepro/types` beside the operator
|
|
37
|
+
* list, because the offline queue has to recognise one too and cannot import
|
|
38
|
+
* this package.
|
|
39
|
+
*/
|
|
40
|
+
export declare const looksLikeFieldOp: typeof isFieldOperation;
|
|
41
|
+
/** True when any value in the payload is (or is attempting to be) an operation. */
|
|
42
|
+
export declare function hasFieldOps(values: Record<string, unknown> | undefined): boolean;
|
|
43
|
+
/**
|
|
44
|
+
* Parse one value as an operation, or report why it is not a legal one.
|
|
45
|
+
*
|
|
46
|
+
* Returns `undefined` for an ordinary value. Throws for a value that reads as
|
|
47
|
+
* an operation and is malformed, so a typo cannot be written as data.
|
|
48
|
+
*/
|
|
49
|
+
export declare function parseFieldOp(key: string, value: unknown): ParsedFieldOp | undefined;
|
|
50
|
+
/**
|
|
51
|
+
* Split a write payload into ordinary values and field operations.
|
|
52
|
+
*
|
|
53
|
+
* The two travel together in one body — `{ title: "x", views: { $inc: 1 } }` is
|
|
54
|
+
* a single `PATCH` — and are applied in one statement, so a caller never has to
|
|
55
|
+
* choose between setting a column and incrementing another.
|
|
56
|
+
*/
|
|
57
|
+
export declare function splitFieldOps(values: Record<string, unknown>): {
|
|
58
|
+
values: Record<string, unknown>;
|
|
59
|
+
fieldOps: Record<string, ParsedFieldOp>;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Refuse an operation the collection's own schema says cannot apply.
|
|
63
|
+
*
|
|
64
|
+
* Checked here rather than left to Postgres because the database's answer
|
|
65
|
+
* arrives as a type error naming a generated column expression, from inside a
|
|
66
|
+
* transaction that has already run other operations of the same batch — and
|
|
67
|
+
* because `$push` on a `number` is a caller mistake, which is a 400, not a 500.
|
|
68
|
+
*
|
|
69
|
+
* `rowIndex` names the entry when the payload came from a bulk route, for the
|
|
70
|
+
* same reason the other bulk validators take one: "the batch failed" is
|
|
71
|
+
* unactionable at a thousand rows.
|
|
72
|
+
*/
|
|
73
|
+
export declare function assertFieldOpsValid(values: Record<string, unknown>, collection: CollectionConfig, options?: {
|
|
74
|
+
rowIndex?: number;
|
|
75
|
+
operationIndex?: number;
|
|
76
|
+
}): void;
|
|
77
|
+
/**
|
|
78
|
+
* Field operations describe a change to a value that is already there, so they
|
|
79
|
+
* are meaningless on an insert — `views + 1` over a row that does not exist yet
|
|
80
|
+
* is just `1`, and accepting it would make `$inc` mean two different things
|
|
81
|
+
* depending on a race the caller cannot observe.
|
|
82
|
+
*/
|
|
83
|
+
export declare function assertNoFieldOpsOnCreate(values: Record<string, unknown>, context: string): void;
|
|
84
|
+
/** Re-exported so callers type against one definition of the wire shape. */
|
|
85
|
+
export type { FieldOperation };
|
|
86
|
+
export { FIELD_OPERATORS };
|