@rebasepro/server 0.24.0 → 0.24.1-canary.g56af4a4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/GCSStorageController-DivE9bAx.js +402 -0
  2. package/dist/GCSStorageController-DivE9bAx.js.map +1 -0
  3. package/dist/S3StorageController-D_vKs4kP.js +480 -0
  4. package/dist/S3StorageController-D_vKs4kP.js.map +1 -0
  5. package/dist/api/rest/api-generator.d.ts +53 -1
  6. package/dist/api/rest/auth-collection-writes.d.ts +28 -21
  7. package/dist/api/rest/field-access-query.d.ts +28 -8
  8. package/dist/api/rest/field-ops.d.ts +19 -7
  9. package/dist/api/rest/query-body.d.ts +10 -0
  10. package/dist/api/rest/write-validation.d.ts +7 -5
  11. package/dist/api/schema-editor-routes.d.ts +10 -1
  12. package/dist/api/sql-export-routes.d.ts +8 -0
  13. package/dist/api/types.d.ts +11 -0
  14. package/dist/{ast-schema-editor-CWqS_sLJ.js → ast-schema-editor-CSdL0iCk.js} +2 -2
  15. package/dist/{ast-schema-editor-CWqS_sLJ.js.map → ast-schema-editor-CSdL0iCk.js.map} +1 -1
  16. package/dist/auth/access.d.ts +16 -0
  17. package/dist/auth/admin-user-ops.d.ts +24 -2
  18. package/dist/auth/admin-users-route.d.ts +1 -0
  19. package/dist/auth/expired-token-sweep.d.ts +5 -1
  20. package/dist/auth/interfaces.d.ts +10 -0
  21. package/dist/auth/jwt-crypto.d.ts +7 -0
  22. package/dist/auth/jwt-keys.d.ts +4 -0
  23. package/dist/auth/jwt.d.ts +6 -1
  24. package/dist/auth/rate-limiter.d.ts +13 -1
  25. package/dist/auth/registration-policy.d.ts +17 -0
  26. package/dist/auth/user-picking.d.ts +35 -0
  27. package/dist/{auth-DMLngxn_.js → auth-OPq_FeMs.js} +972 -85
  28. package/dist/auth-OPq_FeMs.js.map +1 -0
  29. package/dist/auth_adapter-CIItCTc8.js +21 -0
  30. package/dist/auth_adapter-CIItCTc8.js.map +1 -0
  31. package/dist/backend-DTAOsLQc.js.map +1 -1
  32. package/dist/backup/backup-common.d.ts +14 -3
  33. package/dist/backup/backup-routes.d.ts +23 -2
  34. package/dist/backup/backup-storage.d.ts +3 -1
  35. package/dist/backup/index.d.ts +3 -1
  36. package/dist/{backup-CN0s50D2.js → backup-5d7XhLX3.js} +170 -33
  37. package/dist/backup-5d7XhLX3.js.map +1 -0
  38. package/dist/boot/driver.d.ts +3 -0
  39. package/dist/boot/env.d.ts +7 -0
  40. package/dist/boot/http-server.d.ts +22 -0
  41. package/dist/boot/options.d.ts +16 -1
  42. package/dist/boot/runtime-cors.d.ts +17 -0
  43. package/dist/boot/static-routing.d.ts +9 -0
  44. package/dist/{contract-routes-fz8i4pxs.js → contract-routes-02lASyJI.js} +3 -19
  45. package/dist/contract-routes-02lASyJI.js.map +1 -0
  46. package/dist/cron/cron-routes.d.ts +1 -1
  47. package/dist/cron/cron-scheduler.d.ts +69 -3
  48. package/dist/cron/cron-store.d.ts +27 -4
  49. package/dist/cron/define-cron.d.ts +6 -2
  50. package/dist/cron/index.d.ts +1 -1
  51. package/dist/{cron-loader-CwaANlOG.js → cron-loader-D7OmleAb.js} +8 -4
  52. package/dist/cron-loader-D7OmleAb.js.map +1 -0
  53. package/dist/{cron-routes-Bc-SB0Se.js → cron-routes-CBfiaqEL.js} +27 -4
  54. package/dist/cron-routes-CBfiaqEL.js.map +1 -0
  55. package/dist/{cron-scheduler-CYQgco86.js → cron-scheduler-C2vbETMo.js} +298 -32
  56. package/dist/cron-scheduler-C2vbETMo.js.map +1 -0
  57. package/dist/cron-store-B2Ih0gCN.js +540 -0
  58. package/dist/cron-store-B2Ih0gCN.js.map +1 -0
  59. package/dist/email/smtp-email-service.d.ts +23 -0
  60. package/dist/email/types.d.ts +18 -0
  61. package/dist/env.d.ts +0 -37
  62. package/dist/filter-dialect-REl-TjZr.js +1628 -0
  63. package/dist/filter-dialect-REl-TjZr.js.map +1 -0
  64. package/dist/{function-loader-D7o5Epjj.js → function-loader-BDKKiBmy.js} +4 -3
  65. package/dist/function-loader-BDKKiBmy.js.map +1 -0
  66. package/dist/{function-routes-CaNG4waN.js → function-routes-DWB7BBsi.js} +2 -2
  67. package/dist/function-routes-DWB7BBsi.js.map +1 -0
  68. package/dist/functions/context.d.ts +9 -0
  69. package/dist/functions/define-function.d.ts +7 -4
  70. package/dist/functions/index.d.ts +1 -1
  71. package/dist/functions/index.js +25 -2
  72. package/dist/functions/index.js.map +1 -1
  73. package/dist/functions/request-timeout.d.ts +7 -5
  74. package/dist/history/history-routes.d.ts +9 -0
  75. package/dist/history/retention-sweep.d.ts +81 -0
  76. package/dist/{history-recorder-Nr8zLvoU.js → history-recorder-DHenr3lm.js} +2 -2
  77. package/dist/{history-recorder-Nr8zLvoU.js.map → history-recorder-DHenr3lm.js.map} +1 -1
  78. package/dist/{history-store-rcAm_xFR.js → history-store-DPofGVDp.js} +2 -2
  79. package/dist/{history-store-rcAm_xFR.js.map → history-store-DPofGVDp.js.map} +1 -1
  80. package/dist/index.d.ts +6 -5
  81. package/dist/index.es.js +22671 -19191
  82. package/dist/index.es.js.map +1 -1
  83. package/dist/init/shutdown.d.ts +12 -2
  84. package/dist/init.d.ts +16 -6
  85. package/dist/internal-tables-L2t39RdT.js +136 -0
  86. package/dist/internal-tables-L2t39RdT.js.map +1 -0
  87. package/dist/jobs/job-queue.d.ts +8 -0
  88. package/dist/jobs/job-store.d.ts +24 -0
  89. package/dist/jobs/types.d.ts +25 -4
  90. package/dist/{jobs-DqYNfquG.js → jobs-BpD4Q0qR.js} +232 -22
  91. package/dist/jobs-BpD4Q0qR.js.map +1 -0
  92. package/dist/{jwt-R6bSPMjk.js → jwt-Bqcu7cGt.js} +171 -65
  93. package/dist/jwt-Bqcu7cGt.js.map +1 -0
  94. package/dist/load-failure-UvzZgGXT.js +48 -0
  95. package/dist/load-failure-UvzZgGXT.js.map +1 -0
  96. package/dist/mcp/mcp-tools.d.ts +8 -0
  97. package/dist/metrics/index.d.ts +18 -0
  98. package/dist/metrics/pool-wait.d.ts +50 -0
  99. package/dist/offline-8Ks3yp9n-CadBKm2D.js +3305 -0
  100. package/dist/offline-8Ks3yp9n-CadBKm2D.js.map +1 -0
  101. package/dist/offline-store-D9ytNNaa-BCr2vsFB.js +1903 -0
  102. package/dist/offline-store-D9ytNNaa-BCr2vsFB.js.map +1 -0
  103. package/dist/{openapi-generator-DAq_XVDu.js → openapi-generator-BqoUh4Ij.js} +365 -81
  104. package/dist/openapi-generator-BqoUh4Ij.js.map +1 -0
  105. package/dist/policy-PdzX-Opd.js +121 -0
  106. package/dist/policy-PdzX-Opd.js.map +1 -0
  107. package/dist/project_manifest-R6y_KHms.js +59 -0
  108. package/dist/project_manifest-R6y_KHms.js.map +1 -0
  109. package/dist/{query-parser-BgiKJKvc.js → query-parser-DK9eMkb9.js} +510 -15
  110. package/dist/query-parser-DK9eMkb9.js.map +1 -0
  111. package/dist/{request-timeout-DgH7j8qO.js → request-timeout-Dnl2_OBc.js} +15 -8
  112. package/dist/request-timeout-Dnl2_OBc.js.map +1 -0
  113. package/dist/resumable-upload-threshold-CKv-Ry0l.js +24 -0
  114. package/dist/resumable-upload-threshold-CKv-Ry0l.js.map +1 -0
  115. package/dist/schema-edit/apply-schema-change.d.ts +10 -0
  116. package/dist/schema-edit/local-source.d.ts +29 -0
  117. package/dist/schema-edit/remote-source.d.ts +13 -3
  118. package/dist/schema-edit/source-editor.d.ts +28 -0
  119. package/dist/{schema-editor-routes-oIyuWl3L.js → schema-editor-routes-BFf3i8jm.js} +53 -9
  120. package/dist/schema-editor-routes-BFf3i8jm.js.map +1 -0
  121. package/dist/services/outbound-post.d.ts +50 -0
  122. package/dist/services/outbound-url-guard.d.ts +34 -5
  123. package/dist/services/routed-realtime-service.d.ts +5 -0
  124. package/dist/services/webhook-service.d.ts +66 -14
  125. package/dist/soft-delete-params-47yBGs3_.js +668 -0
  126. package/dist/soft-delete-params-47yBGs3_.js.map +1 -0
  127. package/dist/sql-export-routes-BNNuGGLP.js +240 -0
  128. package/dist/sql-export-routes-BNNuGGLP.js.map +1 -0
  129. package/dist/src-CatHFUym.js.map +1 -1
  130. package/dist/storage/GCSStorageController.d.ts +46 -2
  131. package/dist/storage/LocalStorageController.d.ts +67 -2
  132. package/dist/storage/S3StorageController.d.ts +37 -3
  133. package/dist/storage/image-transform.d.ts +5 -0
  134. package/dist/storage/maintenance-routes.d.ts +23 -0
  135. package/dist/storage/maintenance.d.ts +126 -0
  136. package/dist/storage/rendition-cache.d.ts +9 -11
  137. package/dist/storage/request-principals.d.ts +30 -0
  138. package/dist/storage/routes.d.ts +20 -0
  139. package/dist/storage/source-variables.d.ts +10 -0
  140. package/dist/storage/streams.d.ts +42 -0
  141. package/dist/storage/tus-handler.d.ts +46 -2
  142. package/dist/storage/types.d.ts +82 -7
  143. package/dist/storage/upload-validation.d.ts +13 -0
  144. package/dist/storage-resumable-VO-cMpse-C_YX71pO.js +125 -0
  145. package/dist/storage-resumable-VO-cMpse-C_YX71pO.js.map +1 -0
  146. package/dist/strings.es-BeZWAodn.js +256 -0
  147. package/dist/strings.es-BeZWAodn.js.map +1 -0
  148. package/dist/upload-validation-Dd-fnsbA.js +172 -0
  149. package/dist/upload-validation-Dd-fnsbA.js.map +1 -0
  150. package/dist/utils/byte-size.d.ts +10 -0
  151. package/dist/utils/compression.d.ts +6 -0
  152. package/dist/utils/load-failure.d.ts +14 -0
  153. package/package.json +5 -5
  154. package/dist/GCSStorageController-BSiP1c-f.js +0 -256
  155. package/dist/GCSStorageController-BSiP1c-f.js.map +0 -1
  156. package/dist/S3StorageController-CAwFRgjV.js +0 -276
  157. package/dist/S3StorageController-CAwFRgjV.js.map +0 -1
  158. package/dist/auth-DMLngxn_.js.map +0 -1
  159. package/dist/backup-CN0s50D2.js.map +0 -1
  160. package/dist/contract-routes-fz8i4pxs.js.map +0 -1
  161. package/dist/cron-loader-CwaANlOG.js.map +0 -1
  162. package/dist/cron-routes-Bc-SB0Se.js.map +0 -1
  163. package/dist/cron-scheduler-CYQgco86.js.map +0 -1
  164. package/dist/cron-store-D2Q9-Aco.js +0 -300
  165. package/dist/cron-store-D2Q9-Aco.js.map +0 -1
  166. package/dist/dynamic-import-X40pTZUQ.js +0 -23
  167. package/dist/dynamic-import-X40pTZUQ.js.map +0 -1
  168. package/dist/function-loader-D7o5Epjj.js.map +0 -1
  169. package/dist/function-routes-CaNG4waN.js.map +0 -1
  170. package/dist/jobs-DqYNfquG.js.map +0 -1
  171. package/dist/jwt-R6bSPMjk.js.map +0 -1
  172. package/dist/openapi-generator-DAq_XVDu.js.map +0 -1
  173. package/dist/query-parser-BgiKJKvc.js.map +0 -1
  174. package/dist/request-timeout-DgH7j8qO.js.map +0 -1
  175. package/dist/schema-editor-routes-oIyuWl3L.js.map +0 -1
  176. package/dist/soft-delete-params-BWPilMPF.js +0 -59
  177. package/dist/soft-delete-params-BWPilMPF.js.map +0 -1
  178. package/dist/src-I3aG1PcY.js +0 -6870
  179. package/dist/src-I3aG1PcY.js.map +0 -1
  180. package/dist/types-BfKcm9do.js +0 -39
  181. package/dist/types-BfKcm9do.js.map +0 -1
@@ -0,0 +1,480 @@
1
+ import { createRequire as __rebaseCreateRequire } from "module";
2
+ import __rebaseProcess from "process";
3
+ globalThis.process ??= __rebaseProcess;
4
+ __rebaseCreateRequire(import.meta.url);
5
+ import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
+ import { t as ApiError } from "./errors-D6_y86c5.js";
7
+ import { c as listingPrefix, s as folderKey } from "./keys-GAVZqbqx.js";
8
+ import { o as webStreamFrom, t as validateUploadedFile } from "./upload-validation-Dd-fnsbA.js";
9
+ //#region src/storage/S3StorageController.ts
10
+ var S3StorageController_exports = /* @__PURE__ */ __exportAll({ S3StorageController: () => S3StorageController });
11
+ var _s3Module;
12
+ var _presignerModule;
13
+ async function loadS3() {
14
+ if (!_s3Module) try {
15
+ _s3Module = await import("@aws-sdk/client-s3");
16
+ } catch {
17
+ throw new Error("@aws-sdk/client-s3 is required for S3 storage. Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner");
18
+ }
19
+ return _s3Module;
20
+ }
21
+ async function loadPresigner() {
22
+ if (!_presignerModule) try {
23
+ _presignerModule = await import("@aws-sdk/s3-request-presigner");
24
+ } catch {
25
+ throw new Error("@aws-sdk/s3-request-presigner is required for S3 storage. Install it: pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner");
26
+ }
27
+ return _presignerModule;
28
+ }
29
+ /** Files up to this size are one `PutObject`; larger ones are uploaded in parts of (at least) this size. */
30
+ var MULTIPART_PART_SIZE = 8 * 1024 * 1024;
31
+ /** S3's limit on the parts of one upload. */
32
+ var MAX_MULTIPART_PARTS = 1e4;
33
+ /**
34
+ * S3-compatible storage implementation
35
+ * Works with AWS S3 and MinIO (with forcePathStyle option)
36
+ */
37
+ var S3StorageController = class {
38
+ config;
39
+ _client;
40
+ constructor(config) {
41
+ this.config = config;
42
+ }
43
+ /**
44
+ * Lazily create and cache the S3 client on first use
45
+ */
46
+ async getClient() {
47
+ if (!this._client) {
48
+ const s3 = await loadS3();
49
+ this._client = new s3.S3Client({
50
+ region: this.config.region || "us-east-1",
51
+ endpoint: this.config.endpoint,
52
+ forcePathStyle: this.config.forcePathStyle ?? !!this.config.endpoint,
53
+ credentials: {
54
+ accessKeyId: this.config.accessKeyId,
55
+ secretAccessKey: this.config.secretAccessKey
56
+ }
57
+ });
58
+ }
59
+ return this._client;
60
+ }
61
+ getType() {
62
+ return "s3";
63
+ }
64
+ /**
65
+ * The configured bucket, and the logical `default` that maps to it.
66
+ *
67
+ * Any other name went straight to S3 as a bucket name, so the request
68
+ * parameter was a way to address *any* bucket the deployment's credentials
69
+ * can reach — and a mistyped one came back as "file not found".
70
+ */
71
+ knownBuckets() {
72
+ return ["default", this.config.bucket];
73
+ }
74
+ /** See {@link StorageController.maxFileSize}. */
75
+ maxFileSize() {
76
+ return this.config.maxFileSize ?? 52428800;
77
+ }
78
+ /**
79
+ * Validate file before upload
80
+ */
81
+ validateFile(file) {
82
+ validateUploadedFile(file, this.maxFileSize(), this.config.allowedMimeTypes);
83
+ }
84
+ /**
85
+ * Get the bucket name - either from parameter or config
86
+ */
87
+ getBucket(bucket) {
88
+ if (!bucket || bucket === "default") return this.config.bucket;
89
+ return bucket;
90
+ }
91
+ async putObject({ file, key, metadata, bucket }, options) {
92
+ if (options?.uploadLimits !== false) this.validateFile(file);
93
+ const usedBucket = this.getBucket(bucket);
94
+ const s3 = await loadS3();
95
+ const client = await this.getClient();
96
+ const target = {
97
+ Bucket: usedBucket,
98
+ Key: key,
99
+ ContentType: file.type,
100
+ Metadata: metadata ? this.flattenMetadata(metadata) : void 0
101
+ };
102
+ if (file.size <= MULTIPART_PART_SIZE) await client.send(new s3.PutObjectCommand({
103
+ ...target,
104
+ Body: Buffer.from(await file.arrayBuffer())
105
+ })).catch((error) => {
106
+ throw misconfiguredOr(error, usedBucket);
107
+ });
108
+ else await this.putMultipart(target, file);
109
+ return {
110
+ key,
111
+ bucket: usedBucket,
112
+ storageUrl: `s3://${usedBucket}/${key}`
113
+ };
114
+ }
115
+ /**
116
+ * Upload a large file in parts, one part in memory at a time.
117
+ *
118
+ * Reading the whole file into one buffer held it twice over (the
119
+ * `arrayBuffer()`, then the SDK's view and the multipart parser's copy
120
+ * before it), and `PutObject` stops at 5 GB regardless. A slice of a
121
+ * `File` reads only that range — from disk, for the disk-backed files TUS
122
+ * and backups hand over — so memory is one part whatever the file's size.
123
+ * A failure aborts the upload: no partial object appears at the key, and
124
+ * no orphaned parts are kept (and billed).
125
+ */
126
+ async putMultipart(target, file) {
127
+ const s3 = await loadS3();
128
+ const client = await this.getClient();
129
+ const partSize = Math.max(MULTIPART_PART_SIZE, Math.ceil(file.size / MAX_MULTIPART_PARTS));
130
+ const { UploadId } = await client.send(new s3.CreateMultipartUploadCommand(target)).catch((error) => {
131
+ throw misconfiguredOr(error, target.Bucket);
132
+ });
133
+ if (!UploadId) throw new Error(`S3 did not start a multipart upload for ${target.Key}.`);
134
+ const { Bucket, Key } = target;
135
+ try {
136
+ const parts = [];
137
+ for (let offset = 0, PartNumber = 1; offset < file.size; offset += partSize, PartNumber++) {
138
+ const Body = Buffer.from(await file.slice(offset, Math.min(offset + partSize, file.size)).arrayBuffer());
139
+ const { ETag } = await client.send(new s3.UploadPartCommand({
140
+ Bucket,
141
+ Key,
142
+ UploadId,
143
+ PartNumber,
144
+ Body
145
+ }));
146
+ parts.push({
147
+ ETag,
148
+ PartNumber
149
+ });
150
+ }
151
+ await client.send(new s3.CompleteMultipartUploadCommand({
152
+ Bucket,
153
+ Key,
154
+ UploadId,
155
+ MultipartUpload: { Parts: parts }
156
+ }));
157
+ } catch (error) {
158
+ await client.send(new s3.AbortMultipartUploadCommand({
159
+ Bucket,
160
+ Key,
161
+ UploadId
162
+ })).catch(() => void 0);
163
+ throw misconfiguredOr(error, Bucket);
164
+ }
165
+ }
166
+ /**
167
+ * Flatten nested metadata to string values (S3 requirement)
168
+ */
169
+ flattenMetadata(metadata) {
170
+ const flattened = {};
171
+ for (const [key, value] of Object.entries(metadata)) if (typeof value === "string") flattened[key] = value;
172
+ else if (value !== void 0 && value !== null) flattened[key] = JSON.stringify(value);
173
+ return flattened;
174
+ }
175
+ async getSignedUrl(key, bucket) {
176
+ let resolvedPath = key;
177
+ let resolvedBucket = this.getBucket(bucket);
178
+ const match = key.match(/^(s3|gs):\/\//);
179
+ if (match) {
180
+ const protocolLength = match[0].length;
181
+ const withoutProtocol = key.substring(protocolLength);
182
+ const firstSlash = withoutProtocol.indexOf("/");
183
+ if (firstSlash > 0) {
184
+ resolvedBucket = withoutProtocol.substring(0, firstSlash);
185
+ resolvedPath = withoutProtocol.substring(firstSlash + 1);
186
+ }
187
+ }
188
+ try {
189
+ const s3 = await loadS3();
190
+ const presigner = await loadPresigner();
191
+ const client = await this.getClient();
192
+ const headCommand = new s3.HeadObjectCommand({
193
+ Bucket: resolvedBucket,
194
+ Key: resolvedPath
195
+ });
196
+ const headResult = await client.send(headCommand);
197
+ const getCommand = new s3.GetObjectCommand({
198
+ Bucket: resolvedBucket,
199
+ Key: resolvedPath
200
+ });
201
+ return {
202
+ url: await presigner.getSignedUrl(client, getCommand, { expiresIn: 3600 }),
203
+ metadata: {
204
+ bucket: resolvedBucket,
205
+ fullPath: resolvedPath,
206
+ name: resolvedPath.split("/").pop() || resolvedPath,
207
+ size: headResult.ContentLength || 0,
208
+ contentType: headResult.ContentType || "application/octet-stream",
209
+ customMetadata: headResult.Metadata || {}
210
+ }
211
+ };
212
+ } catch (error) {
213
+ if (isS3NotFound(error)) return {
214
+ url: null,
215
+ fileNotFound: true
216
+ };
217
+ throw misconfiguredOr(error, resolvedBucket);
218
+ }
219
+ }
220
+ async getObject(key, bucket) {
221
+ let resolvedPath = key;
222
+ let resolvedBucket = this.getBucket(bucket);
223
+ const match = key.match(/^(s3|gs):\/\//);
224
+ if (match) {
225
+ const protocolLength = match[0].length;
226
+ const withoutProtocol = key.substring(protocolLength);
227
+ const firstSlash = withoutProtocol.indexOf("/");
228
+ if (firstSlash > 0) {
229
+ resolvedBucket = withoutProtocol.substring(0, firstSlash);
230
+ resolvedPath = withoutProtocol.substring(firstSlash + 1);
231
+ }
232
+ }
233
+ try {
234
+ const s3 = await loadS3();
235
+ const client = await this.getClient();
236
+ const command = new s3.GetObjectCommand({
237
+ Bucket: resolvedBucket,
238
+ Key: resolvedPath
239
+ });
240
+ const response = await client.send(command);
241
+ if (!response.Body) return null;
242
+ const chunks = [];
243
+ for await (const chunk of response.Body) chunks.push(chunk);
244
+ const buffer = Buffer.concat(chunks);
245
+ const contentType = response.ContentType || "application/octet-stream";
246
+ const fileName = resolvedPath.split("/").pop() || resolvedPath;
247
+ const blob = new Blob([buffer], { type: contentType });
248
+ return new File([blob], fileName, {
249
+ type: contentType,
250
+ lastModified: response.LastModified?.getTime()
251
+ });
252
+ } catch (error) {
253
+ if (isS3NotFound(error)) return null;
254
+ throw misconfiguredOr(error, resolvedBucket);
255
+ }
256
+ }
257
+ /**
258
+ * The bucket and key a call addresses: an `s3://` or `gs://` URL names its
259
+ * own bucket, anything else is a key in the given (or configured) bucket.
260
+ */
261
+ resolveLocation(key, bucket) {
262
+ const match = key.match(/^(s3|gs):\/\//);
263
+ if (match) {
264
+ const withoutProtocol = key.substring(match[0].length);
265
+ const firstSlash = withoutProtocol.indexOf("/");
266
+ if (firstSlash > 0) return {
267
+ bucket: withoutProtocol.substring(0, firstSlash),
268
+ key: withoutProtocol.substring(firstSlash + 1)
269
+ };
270
+ }
271
+ return {
272
+ bucket: this.getBucket(bucket),
273
+ key
274
+ };
275
+ }
276
+ /**
277
+ * See {@link StorageController.getMetadata}. One `HeadObject`. Without it,
278
+ * `GET /metadata/*` fell back to `getSignedUrl`, which signed a URL per
279
+ * call — ~134 µs of CPU — only for the route to throw it away.
280
+ */
281
+ async getMetadata(key, bucket) {
282
+ const location = this.resolveLocation(key, bucket);
283
+ const s3 = await loadS3();
284
+ const client = await this.getClient();
285
+ try {
286
+ const head = await client.send(new s3.HeadObjectCommand({
287
+ Bucket: location.bucket,
288
+ Key: location.key
289
+ }));
290
+ return {
291
+ bucket: location.bucket,
292
+ fullPath: location.key,
293
+ name: location.key.split("/").pop() || location.key,
294
+ size: head.ContentLength || 0,
295
+ contentType: head.ContentType || "application/octet-stream",
296
+ customMetadata: head.Metadata || {}
297
+ };
298
+ } catch (error) {
299
+ if (isS3NotFound(error)) return null;
300
+ throw misconfiguredOr(error, location.bucket);
301
+ }
302
+ }
303
+ /** See {@link StorageController.statObject}. One `HeadObject`; no body is read. */
304
+ async statObject(key, bucket) {
305
+ const location = this.resolveLocation(key, bucket);
306
+ const s3 = await loadS3();
307
+ const client = await this.getClient();
308
+ try {
309
+ const head = await client.send(new s3.HeadObjectCommand({
310
+ Bucket: location.bucket,
311
+ Key: location.key
312
+ }));
313
+ return {
314
+ size: head.ContentLength ?? 0,
315
+ contentType: head.ContentType || "application/octet-stream",
316
+ lastModified: head.LastModified?.getTime() ?? Date.now()
317
+ };
318
+ } catch (error) {
319
+ if (isS3NotFound(error)) return null;
320
+ throw misconfiguredOr(error, location.bucket);
321
+ }
322
+ }
323
+ /**
324
+ * See {@link StorageController.getObjectStream}. One `GetObject`, with a
325
+ * `Range` when one is asked for, so only those bytes leave the bucket; the
326
+ * body is handed on as it arrives rather than collected first.
327
+ */
328
+ async getObjectStream(key, options) {
329
+ const location = this.resolveLocation(key, options?.bucket);
330
+ const range = options?.range;
331
+ const s3 = await loadS3();
332
+ const client = await this.getClient();
333
+ let response;
334
+ try {
335
+ response = await client.send(new s3.GetObjectCommand({
336
+ Bucket: location.bucket,
337
+ Key: location.key,
338
+ ...range ? { Range: `bytes=${range.start}-${range.end}` } : {}
339
+ }));
340
+ } catch (error) {
341
+ if (isS3NotFound(error)) return null;
342
+ if (range && isS3RangeNotSatisfiable(error)) return this.getObjectStream(key, { bucket: options?.bucket });
343
+ throw misconfiguredOr(error, location.bucket);
344
+ }
345
+ const body = response.Body;
346
+ if (!body) return null;
347
+ const total = range ? /\/(\d+)\s*$/.exec(response.ContentRange ?? "")?.[1] : void 0;
348
+ const served = range && total !== void 0 ? range : void 0;
349
+ return {
350
+ stream: isByteIterable(body) ? webStreamFrom(body) : body.transformToWebStream(),
351
+ size: total !== void 0 ? Number(total) : response.ContentLength ?? 0,
352
+ contentType: response.ContentType || "application/octet-stream",
353
+ lastModified: response.LastModified?.getTime() ?? Date.now(),
354
+ ...served ? { range: served } : {}
355
+ };
356
+ }
357
+ async deleteObject(key, bucket) {
358
+ let resolvedPath = key;
359
+ let resolvedBucket = this.getBucket(bucket);
360
+ const match = key.match(/^(s3|gs):\/\//);
361
+ if (match) {
362
+ const protocolLength = match[0].length;
363
+ const withoutProtocol = key.substring(protocolLength);
364
+ const firstSlash = withoutProtocol.indexOf("/");
365
+ if (firstSlash > 0) {
366
+ resolvedBucket = withoutProtocol.substring(0, firstSlash);
367
+ resolvedPath = withoutProtocol.substring(firstSlash + 1);
368
+ }
369
+ }
370
+ const s3 = await loadS3();
371
+ const client = await this.getClient();
372
+ const command = new s3.DeleteObjectCommand({
373
+ Bucket: resolvedBucket,
374
+ Key: resolvedPath
375
+ });
376
+ try {
377
+ await client.send(command);
378
+ } catch (error) {
379
+ if (isS3NotFound(error)) return;
380
+ throw misconfiguredOr(error, resolvedBucket);
381
+ }
382
+ }
383
+ async listObjects(prefix, options) {
384
+ const resolvedBucket = this.getBucket(options?.bucket);
385
+ const s3 = await loadS3();
386
+ const client = await this.getClient();
387
+ const folderPrefix = listingPrefix(prefix);
388
+ const command = new s3.ListObjectsV2Command({
389
+ Bucket: resolvedBucket,
390
+ Prefix: folderPrefix,
391
+ MaxKeys: options?.maxResults ?? 1e3,
392
+ ContinuationToken: options?.pageToken,
393
+ Delimiter: "/"
394
+ });
395
+ const response = await client.send(command).catch((error) => {
396
+ throw misconfiguredOr(error, resolvedBucket);
397
+ });
398
+ return {
399
+ items: (response.Contents || []).filter((obj) => obj.Key !== folderPrefix).map((obj) => ({
400
+ bucket: resolvedBucket,
401
+ fullPath: obj.Key || "",
402
+ name: (obj.Key || "").split("/").pop() || "",
403
+ ...typeof obj.Size === "number" ? { size: obj.Size } : {},
404
+ ...obj.LastModified instanceof Date ? { updated: obj.LastModified.toISOString() } : {},
405
+ parent: null,
406
+ root: null,
407
+ toString: () => `s3://${resolvedBucket}/${obj.Key}`
408
+ })),
409
+ prefixes: (response.CommonPrefixes || []).map((common) => {
410
+ const folder = folderKey(common.Prefix || "");
411
+ return {
412
+ bucket: resolvedBucket,
413
+ fullPath: folder,
414
+ name: folder.split("/").pop() || "",
415
+ parent: null,
416
+ root: null,
417
+ toString: () => `s3://${resolvedBucket}/${folder}`
418
+ };
419
+ }),
420
+ nextPageToken: response.NextContinuationToken
421
+ };
422
+ }
423
+ };
424
+ /** The error name and HTTP status an SDK error carries, read without assuming its shape. */
425
+ function s3ErrorFacts(error) {
426
+ if (typeof error !== "object" || error === null) return {};
427
+ const name = "name" in error && typeof error.name === "string" ? error.name : void 0;
428
+ const meta = "$metadata" in error ? error.$metadata : void 0;
429
+ return {
430
+ name,
431
+ status: typeof meta === "object" && meta !== null && "httpStatusCode" in meta && typeof meta.httpStatusCode === "number" ? meta.httpStatusCode : void 0
432
+ };
433
+ }
434
+ /**
435
+ * A missing object, as `GetObject` (`NoSuchKey`) and `HeadObject` (`NotFound`, no body) report it.
436
+ *
437
+ * Not a missing bucket, which is a 404 too: read as a missing object, a typo in
438
+ * `S3_BUCKET` made every file of the deployment "not found", and a delete
439
+ * report success. (A `HeadObject` on a missing bucket carries no error name, so
440
+ * that one call still cannot tell the two apart.)
441
+ */
442
+ function isS3NotFound(error) {
443
+ const { name, status } = s3ErrorFacts(error);
444
+ if (name === "NoSuchBucket") return false;
445
+ return name === "NoSuchKey" || name === "NotFound" || status === 404;
446
+ }
447
+ /** What S3 answers when the deployment's configuration, not the request, is wrong. */
448
+ var MISCONFIGURATION_ERRORS = /* @__PURE__ */ new Set([
449
+ "NoSuchBucket",
450
+ "AccessDenied",
451
+ "InvalidAccessKeyId",
452
+ "SignatureDoesNotMatch"
453
+ ]);
454
+ /**
455
+ * A provider error that says this deployment's storage is misconfigured, as a
456
+ * `502 STORAGE_MISCONFIGURED` naming the bucket — or the error as it was.
457
+ *
458
+ * These used to reach the caller as a bare 500 "Internal Server Error", with
459
+ * nothing to say the bucket or its credentials were the problem.
460
+ */
461
+ function misconfiguredOr(error, bucket) {
462
+ const { name } = s3ErrorFacts(error);
463
+ if (!name || !MISCONFIGURATION_ERRORS.has(name)) return error;
464
+ return new ApiError(502, "STORAGE_MISCONFIGURED", name === "NoSuchBucket" ? `The storage bucket "${bucket}" does not exist. Check the bucket name this source is configured with (S3_BUCKET, or S3_BUCKET__<KEY> for a named source).` : `The storage provider refused this deployment's credentials for bucket "${bucket}" (${name}). Check the access key and its permissions on the bucket.`, {
465
+ bucket,
466
+ reason: name
467
+ });
468
+ }
469
+ function isS3RangeNotSatisfiable(error) {
470
+ const { name, status } = s3ErrorFacts(error);
471
+ return name === "InvalidRange" || status === 416;
472
+ }
473
+ /** A Node response body — what the SDK hands over on Node — rather than a browser one. */
474
+ function isByteIterable(value) {
475
+ return typeof value === "object" && value !== null && Symbol.asyncIterator in value;
476
+ }
477
+ //#endregion
478
+ export { S3StorageController_exports as n, S3StorageController as t };
479
+
480
+ //# sourceMappingURL=S3StorageController-D_vKs4kP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"S3StorageController-D_vKs4kP.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 {\n DEFAULT_MAX_FILE_SIZE,\n S3StorageConfig,\n StorageController,\n type StoredObjectInfo,\n type StoredObjectRange,\n type PutObjectOptions,\n type StoredObjectStream\n} from \"./types\";\nimport { folderKey, listingPrefix } from \"./keys\";\nimport { webStreamFrom } from \"./streams\";\nimport { ApiError } from \"../api/errors\";\nimport { validateUploadedFile } from \"./upload-validation\";\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/** Files up to this size are one `PutObject`; larger ones are uploaded in parts of (at least) this size. */\nconst MULTIPART_PART_SIZE = 8 * 1024 * 1024;\n/** S3's limit on the parts of one upload. */\nconst MAX_MULTIPART_PARTS = 10_000;\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 /** See {@link StorageController.maxFileSize}. */\n maxFileSize(): number {\n return this.config.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;\n }\n\n /**\n * Validate file before upload\n */\n private validateFile(file: File): void {\n validateUploadedFile(file, this.maxFileSize(), this.config.allowedMimeTypes);\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, options?: PutObjectOptions): Promise<UploadFileResult> {\n if (options?.uploadLimits !== false) this.validateFile(file);\n\n const usedBucket = this.getBucket(bucket);\n const s3 = await loadS3();\n const client = await this.getClient();\n const target = {\n Bucket: usedBucket,\n Key: key,\n ContentType: file.type,\n Metadata: metadata ? this.flattenMetadata(metadata) : undefined\n };\n\n if (file.size <= MULTIPART_PART_SIZE) {\n // One request from one buffer, as always: a small file is no bigger\n // than a part. `Buffer.from(arrayBuffer)` is a view, not a copy.\n await client.send(new s3.PutObjectCommand({ ...target, Body: Buffer.from(await file.arrayBuffer()) }))\n .catch((error: unknown) => { throw misconfiguredOr(error, usedBucket); });\n } else {\n await this.putMultipart(target, file);\n }\n\n return {\n key,\n bucket: usedBucket,\n storageUrl: `s3://${usedBucket}/${key}`\n };\n }\n\n /**\n * Upload a large file in parts, one part in memory at a time.\n *\n * Reading the whole file into one buffer held it twice over (the\n * `arrayBuffer()`, then the SDK's view and the multipart parser's copy\n * before it), and `PutObject` stops at 5 GB regardless. A slice of a\n * `File` reads only that range — from disk, for the disk-backed files TUS\n * and backups hand over — so memory is one part whatever the file's size.\n * A failure aborts the upload: no partial object appears at the key, and\n * no orphaned parts are kept (and billed).\n */\n private async putMultipart(\n target: { Bucket: string; Key: string; ContentType: string; Metadata?: Record<string, string> },\n file: Blob\n ): Promise<void> {\n const s3 = await loadS3();\n const client = await this.getClient();\n // At most 10,000 parts: a part grows past 8 MiB only beyond 80 GB.\n const partSize = Math.max(MULTIPART_PART_SIZE, Math.ceil(file.size / MAX_MULTIPART_PARTS));\n const { UploadId } = await client.send(new s3.CreateMultipartUploadCommand(target))\n .catch((error: unknown) => { throw misconfiguredOr(error, target.Bucket); });\n if (!UploadId) throw new Error(`S3 did not start a multipart upload for ${target.Key}.`);\n const { Bucket, Key } = target;\n try {\n const parts: { ETag?: string; PartNumber: number }[] = [];\n for (let offset = 0, PartNumber = 1; offset < file.size; offset += partSize, PartNumber++) {\n const Body = Buffer.from(await file.slice(offset, Math.min(offset + partSize, file.size)).arrayBuffer());\n const { ETag } = await client.send(new s3.UploadPartCommand({ Bucket, Key, UploadId, PartNumber, Body }));\n parts.push({ ETag, PartNumber });\n }\n await client.send(new s3.CompleteMultipartUploadCommand({ Bucket, Key, UploadId, MultipartUpload: { Parts: parts } }));\n } catch (error: unknown) {\n await client.send(new s3.AbortMultipartUploadCommand({ Bucket, Key, UploadId })).catch(() => undefined);\n throw misconfiguredOr(error, Bucket);\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 // Good for an hour. Server-side callers only: no route hands it out.\n const url = await presigner.getSignedUrl(client, getCommand, { expiresIn: 3600 });\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 if (isS3NotFound(error)) {\n return {\n url: null,\n fileNotFound: true\n };\n }\n throw misconfiguredOr(error, resolvedBucket);\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 // The object's own version. Left out, `File` stamps `Date.now()`,\n // and the routes build the `ETag`, `Last-Modified` and the\n // transform cache key from this — so every read was a new version:\n // no 304, no cache hit, and a fresh rendition written per request.\n return new File([blob], fileName, {\n type: contentType,\n lastModified: response.LastModified?.getTime()\n });\n } catch (error: unknown) {\n if (isS3NotFound(error)) {\n return null;\n }\n throw misconfiguredOr(error, resolvedBucket);\n }\n }\n\n /**\n * The bucket and key a call addresses: an `s3://` or `gs://` URL names its\n * own bucket, anything else is a key in the given (or configured) bucket.\n */\n private resolveLocation(key: string, bucket?: string): { bucket: string; key: string } {\n const match = key.match(/^(s3|gs):\\/\\//);\n if (match) {\n const withoutProtocol = key.substring(match[0].length);\n const firstSlash = withoutProtocol.indexOf(\"/\");\n if (firstSlash > 0) {\n return { bucket: withoutProtocol.substring(0, firstSlash), key: withoutProtocol.substring(firstSlash + 1) };\n }\n }\n return { bucket: this.getBucket(bucket), key };\n }\n\n /**\n * See {@link StorageController.getMetadata}. One `HeadObject`. Without it,\n * `GET /metadata/*` fell back to `getSignedUrl`, which signed a URL per\n * call — ~134 µs of CPU — only for the route to throw it away.\n */\n async getMetadata(key: string, bucket?: string): Promise<DownloadMetadata | null> {\n const location = this.resolveLocation(key, bucket);\n const s3 = await loadS3();\n const client = await this.getClient();\n try {\n const head = await client.send(new s3.HeadObjectCommand({ Bucket: location.bucket, Key: location.key }));\n return {\n bucket: location.bucket,\n fullPath: location.key,\n name: location.key.split(\"/\").pop() || location.key,\n size: head.ContentLength || 0,\n contentType: head.ContentType || \"application/octet-stream\",\n customMetadata: head.Metadata || {}\n };\n } catch (error: unknown) {\n if (isS3NotFound(error)) return null;\n throw misconfiguredOr(error, location.bucket);\n }\n }\n\n /** See {@link StorageController.statObject}. One `HeadObject`; no body is read. */\n async statObject(key: string, bucket?: string): Promise<StoredObjectInfo | null> {\n const location = this.resolveLocation(key, bucket);\n const s3 = await loadS3();\n const client = await this.getClient();\n try {\n const head = await client.send(new s3.HeadObjectCommand({ Bucket: location.bucket, Key: location.key }));\n return {\n size: head.ContentLength ?? 0,\n contentType: head.ContentType || \"application/octet-stream\",\n // The object's version — see `getObject` on why a missing one\n // must not become a stable value.\n lastModified: head.LastModified?.getTime() ?? Date.now()\n };\n } catch (error: unknown) {\n if (isS3NotFound(error)) return null;\n throw misconfiguredOr(error, location.bucket);\n }\n }\n\n /**\n * See {@link StorageController.getObjectStream}. One `GetObject`, with a\n * `Range` when one is asked for, so only those bytes leave the bucket; the\n * body is handed on as it arrives rather than collected first.\n */\n async getObjectStream(\n key: string,\n options?: { bucket?: string; range?: StoredObjectRange }\n ): Promise<StoredObjectStream | null> {\n const location = this.resolveLocation(key, options?.bucket);\n const range = options?.range;\n const s3 = await loadS3();\n const client = await this.getClient();\n let response;\n try {\n response = await client.send(new s3.GetObjectCommand({\n Bucket: location.bucket,\n Key: location.key,\n ...(range ? { Range: `bytes=${range.start}-${range.end}` } : {})\n }));\n } catch (error: unknown) {\n if (isS3NotFound(error)) return null;\n // The object shrank below the range since it was described. Read\n // it whole: the caller serves a whole object as a 200, which HTTP\n // allows for any range request.\n if (range && isS3RangeNotSatisfiable(error)) return this.getObjectStream(key, { bucket: options?.bucket });\n throw misconfiguredOr(error, location.bucket);\n }\n const body = response.Body;\n if (!body) return null;\n\n // A ranged answer says the whole object's size after the slash of its\n // `Content-Range`. A store that ignored the `Range` sent no\n // `Content-Range` and the whole object, which is what this then says.\n const total = range ? /\\/(\\d+)\\s*$/.exec(response.ContentRange ?? \"\")?.[1] : undefined;\n const served = range && total !== undefined ? range : undefined;\n return {\n stream: isByteIterable(body) ? webStreamFrom(body) : body.transformToWebStream(),\n size: total !== undefined ? Number(total) : response.ContentLength ?? 0,\n contentType: response.ContentType || \"application/octet-stream\",\n lastModified: response.LastModified?.getTime() ?? Date.now(),\n ...(served ? { range: served } : {})\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 if (isS3NotFound(error)) {\n return;\n }\n throw misconfiguredOr(error, resolvedBucket);\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 folderPrefix = listingPrefix(prefix);\n const command = new s3.ListObjectsV2Command({\n Bucket: resolvedBucket,\n Prefix: folderPrefix,\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 .catch((error: unknown) => { throw misconfiguredOr(error, resolvedBucket); });\n\n // The folder's own marker — the zero-byte `folder/` object that\n // `POST /folder` writes — is in `Contents` when the listed prefix is\n // that folder. It is how the folder exists, not something in it, and\n // listed it is an entry with an empty name. Local storage has no such\n // object to list.\n const objects = (response.Contents || []).filter(obj => obj.Key !== folderPrefix);\n const items: StorageReference[] = objects.map(obj => ({\n bucket: resolvedBucket,\n fullPath: obj.Key || \"\",\n name: (obj.Key || \"\").split(\"/\").pop() || \"\",\n // What the listing already carries, so a folder can be shown\n // without a HEAD per file. ListObjectsV2 has no content type.\n ...(typeof obj.Size === \"number\" ? { size: obj.Size } : {}),\n ...(obj.LastModified instanceof Date ? { updated: obj.LastModified.toISOString() } : {}),\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\n/** The error name and HTTP status an SDK error carries, read without assuming its shape. */\nfunction s3ErrorFacts(error: unknown): { name?: string; status?: number } {\n if (typeof error !== \"object\" || error === null) return {};\n const name = \"name\" in error && typeof error.name === \"string\" ? error.name : undefined;\n const meta = \"$metadata\" in error ? error.$metadata : undefined;\n const status = typeof meta === \"object\" && meta !== null && \"httpStatusCode\" in meta && typeof meta.httpStatusCode === \"number\"\n ? meta.httpStatusCode\n : undefined;\n return { name, status };\n}\n\n/**\n * A missing object, as `GetObject` (`NoSuchKey`) and `HeadObject` (`NotFound`, no body) report it.\n *\n * Not a missing bucket, which is a 404 too: read as a missing object, a typo in\n * `S3_BUCKET` made every file of the deployment \"not found\", and a delete\n * report success. (A `HeadObject` on a missing bucket carries no error name, so\n * that one call still cannot tell the two apart.)\n */\nfunction isS3NotFound(error: unknown): boolean {\n const { name, status } = s3ErrorFacts(error);\n if (name === \"NoSuchBucket\") return false;\n return name === \"NoSuchKey\" || name === \"NotFound\" || status === 404;\n}\n\n/** What S3 answers when the deployment's configuration, not the request, is wrong. */\nconst MISCONFIGURATION_ERRORS = new Set([\"NoSuchBucket\", \"AccessDenied\", \"InvalidAccessKeyId\", \"SignatureDoesNotMatch\"]);\n\n/**\n * A provider error that says this deployment's storage is misconfigured, as a\n * `502 STORAGE_MISCONFIGURED` naming the bucket — or the error as it was.\n *\n * These used to reach the caller as a bare 500 \"Internal Server Error\", with\n * nothing to say the bucket or its credentials were the problem.\n */\nfunction misconfiguredOr(error: unknown, bucket: string): unknown {\n const { name } = s3ErrorFacts(error);\n if (!name || !MISCONFIGURATION_ERRORS.has(name)) return error;\n return new ApiError(\n 502,\n \"STORAGE_MISCONFIGURED\",\n name === \"NoSuchBucket\"\n ? `The storage bucket \"${bucket}\" does not exist. Check the bucket name this source is configured with (S3_BUCKET, or S3_BUCKET__<KEY> for a named source).`\n : `The storage provider refused this deployment's credentials for bucket \"${bucket}\" (${name}). Check the access key and its permissions on the bucket.`,\n { bucket, reason: name }\n );\n}\n\nfunction isS3RangeNotSatisfiable(error: unknown): boolean {\n const { name, status } = s3ErrorFacts(error);\n return name === \"InvalidRange\" || status === 416;\n}\n\n/** A Node response body — what the SDK hands over on Node — rather than a browser one. */\nfunction isByteIterable(value: unknown): value is AsyncIterable<Uint8Array> {\n return typeof value === \"object\" && value !== null && Symbol.asyncIterator in value;\n}\n"],"mappings":";;;;;;;;;;AA2BA,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;;AAGA,IAAM,sBAAsB,IAAI,OAAO;;AAEvC,IAAM,sBAAsB;;;;;AAM5B,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,e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,7 +265,9 @@ export declare class RestApiGenerator {
265
265
  *
266
266
  * `respond` is applied to the *stored* result rather than the stored result
267
267
  * being a response, so a replay honours the `Prefer` header of the request
268
- * replaying it rather than the one that first answered.
268
+ * replaying it rather than the one that first answered. `replayed` says
269
+ * the result is the stored one, so a route can restore what it put in a
270
+ * header rather than the body (the `PATCH`'s `ETag`).
269
271
  */
270
272
  private runIdempotent;
271
273
  /**
@@ -330,11 +332,61 @@ export declare class RestApiGenerator {
330
332
  * through a parent. Errors are not re-classified; see {@link createRow}.
331
333
  */
332
334
  private updateRow;
335
+ /**
336
+ * The 404 and the `If-Match` of an update or a delete, as a precondition
337
+ * the driver runs inside the write — or, for a driver that cannot, and for
338
+ * the auth collection, the same judgement made here on a read first.
339
+ *
340
+ * Inside the write is the point. The route used to read the row in a
341
+ * transaction of its own, through the admin's view-model walk, before
342
+ * writing it: every declared relation of the row was loaded — all 200,000
343
+ * comments of a post, for a PATCH of its title — and thrown away, and the
344
+ * write's own read of the row then repeated the lookup. And two writes
345
+ * carrying the same tag could both pass: each compared before either had
346
+ * written. Judged on the write's own read, after the row is locked when a
347
+ * tag is sent, the second one reads what the first wrote and is a 412.
348
+ *
349
+ * The auth collection is still read here first, without relations: the
350
+ * adapter's steps run before the write (`prepareUserUpdates`, and a
351
+ * deletion's `beforeUserDelete` veto, a hook of the application's), and an
352
+ * unknown uid must be the 404 before them, as it always was.
353
+ *
354
+ * @returns The precondition to hand the driver, or `undefined` for a driver
355
+ * that does not run one (the row was judged here).
356
+ */
357
+ private storedRowPrecondition;
333
358
  /**
334
359
  * Delete one row: `DELETE /<collection>/<id>`, and the same row reached
335
360
  * through a parent.
336
361
  */
337
362
  private deleteRow;
363
+ /**
364
+ * A listing — `GET /<collection>` and `POST /<collection>/query`, and the
365
+ * same two through a parent — from the parameters as the `GET` reads them
366
+ * off its URL.
367
+ *
368
+ * One method for both verbs is the whole contract of the POST route: the
369
+ * same parser, the same field-access refusals, the same page, count,
370
+ * cursor and include, the same errors. The caller has already checked the
371
+ * credential's scope for `collection`.
372
+ *
373
+ * @param collectionPath a nested listing's `parent/:id/child` path; unset
374
+ * for the collection's own.
375
+ */
376
+ private listRows;
377
+ /**
378
+ * A collection's count, from the query parameters in `queryDict`: the
379
+ * URL's for `GET …/count`, a body's for `POST …/count`. One method for
380
+ * both, as {@link listRows} is for the listing — the same parser, the same
381
+ * field-access refusals, the same count. The caller has already checked
382
+ * the credential's scope for `collection`.
383
+ *
384
+ * @param collectionPath a nested count's `parent/:id/child` path; unset
385
+ * for the collection's own.
386
+ */
387
+ private countRows;
388
+ /** A `POST …/query` or `POST …/count` body, as the dictionary {@link listRows} and {@link countRows} read. See `query-body.ts`. */
389
+ private queryDictFromRequest;
338
390
  /**
339
391
  * Create REST routes for a collection using existing Rebase patterns
340
392
  */