@rebasepro/server 0.24.0 → 0.24.1-canary.g19596ef

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 (240) hide show
  1. package/README.md +27 -2
  2. package/dist/GCSStorageController-DEga1ULx.js +402 -0
  3. package/dist/GCSStorageController-DEga1ULx.js.map +1 -0
  4. package/dist/S3StorageController-Btx-6bJ5.js +480 -0
  5. package/dist/S3StorageController-Btx-6bJ5.js.map +1 -0
  6. package/dist/api/errors.d.ts +32 -0
  7. package/dist/api/live-schema-routes.d.ts +27 -3
  8. package/dist/api/mount-path.d.ts +30 -0
  9. package/dist/api/mount.d.ts +6 -13
  10. package/dist/api/rest/api-generator.d.ts +53 -1
  11. package/dist/api/rest/auth-collection-writes.d.ts +28 -21
  12. package/dist/api/rest/field-access-query.d.ts +28 -8
  13. package/dist/api/rest/field-ops.d.ts +19 -7
  14. package/dist/api/rest/query-body.d.ts +10 -0
  15. package/dist/api/rest/write-validation.d.ts +7 -5
  16. package/dist/api/schema-editor-routes.d.ts +10 -1
  17. package/dist/api/sql-export-routes.d.ts +8 -0
  18. package/dist/api/types.d.ts +35 -0
  19. package/dist/{ast-schema-editor-CWqS_sLJ.js → ast-schema-editor-mCeSC03x.js} +3 -3
  20. package/dist/{ast-schema-editor-CWqS_sLJ.js.map → ast-schema-editor-mCeSC03x.js.map} +1 -1
  21. package/dist/auth/access.d.ts +62 -11
  22. package/dist/auth/admin-user-ops.d.ts +24 -2
  23. package/dist/auth/admin-users-route.d.ts +1 -0
  24. package/dist/auth/api-keys/api-key-middleware.d.ts +10 -3
  25. package/dist/auth/api-keys/api-key-routes.d.ts +4 -1
  26. package/dist/auth/builtin-auth-adapter.d.ts +13 -0
  27. package/dist/auth/email-change-routes.d.ts +3 -0
  28. package/dist/auth/expired-token-sweep.d.ts +5 -1
  29. package/dist/auth/interfaces.d.ts +10 -0
  30. package/dist/auth/jwks-routes.d.ts +5 -1
  31. package/dist/auth/jwt-crypto.d.ts +7 -0
  32. package/dist/auth/jwt-keys.d.ts +4 -0
  33. package/dist/auth/jwt.d.ts +282 -166
  34. package/dist/auth/magic-link-routes.d.ts +3 -0
  35. package/dist/auth/mfa-crypto.d.ts +9 -3
  36. package/dist/auth/mfa-gate.d.ts +4 -2
  37. package/dist/auth/mfa-routes.d.ts +6 -0
  38. package/dist/auth/middleware.d.ts +9 -2
  39. package/dist/auth/otp-routes.d.ts +3 -0
  40. package/dist/auth/rate-limiter.d.ts +61 -34
  41. package/dist/auth/registration-policy.d.ts +17 -0
  42. package/dist/auth/require-auth.d.ts +1 -1
  43. package/dist/auth/routes.d.ts +16 -0
  44. package/dist/auth/session-routes.d.ts +6 -0
  45. package/dist/auth/token-revocation.d.ts +6 -0
  46. package/dist/auth/user-picking.d.ts +37 -0
  47. package/dist/auth/verify-credential.d.ts +25 -4
  48. package/dist/{auth-DMLngxn_.js → auth-CSBky1mt.js} +2927 -1882
  49. package/dist/auth-CSBky1mt.js.map +1 -0
  50. package/dist/auth_adapter-CIItCTc8.js +21 -0
  51. package/dist/auth_adapter-CIItCTc8.js.map +1 -0
  52. package/dist/backend/create-backend.d.ts +281 -0
  53. package/dist/backend/default-backend.d.ts +35 -0
  54. package/dist/backend/no-collections.d.ts +19 -0
  55. package/dist/backend/options.d.ts +912 -0
  56. package/dist/backend/scope.d.ts +23 -0
  57. package/dist/backend/services.d.ts +54 -0
  58. package/dist/backend-DTAOsLQc.js.map +1 -1
  59. package/dist/backup/backup-common.d.ts +14 -3
  60. package/dist/backup/backup-routes.d.ts +23 -2
  61. package/dist/backup/backup-storage.d.ts +3 -1
  62. package/dist/backup/index.d.ts +3 -1
  63. package/dist/{backup-CN0s50D2.js → backup-DBGRUVTS.js} +178 -37
  64. package/dist/backup-DBGRUVTS.js.map +1 -0
  65. package/dist/boot/boot.d.ts +2 -2
  66. package/dist/boot/driver.d.ts +3 -0
  67. package/dist/boot/env.d.ts +9 -2
  68. package/dist/boot/http-server.d.ts +22 -0
  69. package/dist/boot/options.d.ts +16 -1
  70. package/dist/boot/provision.d.ts +4 -2
  71. package/dist/boot/resource-adapters.d.ts +11 -14
  72. package/dist/boot/runtime-cors.d.ts +17 -0
  73. package/dist/boot/sources.d.ts +9 -0
  74. package/dist/boot/static-routing.d.ts +9 -0
  75. package/dist/{contract-routes-fz8i4pxs.js → contract-routes-DiFwiLg2.js} +5 -21
  76. package/dist/contract-routes-DiFwiLg2.js.map +1 -0
  77. package/dist/cron/cron-loader.d.ts +77 -18
  78. package/dist/cron/cron-routes.d.ts +1 -1
  79. package/dist/cron/cron-scheduler.d.ts +69 -3
  80. package/dist/cron/cron-store.d.ts +33 -5
  81. package/dist/cron/define-cron.d.ts +6 -2
  82. package/dist/cron/index.d.ts +3 -3
  83. package/dist/cron-loader-NHqRfKF0.js +202 -0
  84. package/dist/cron-loader-NHqRfKF0.js.map +1 -0
  85. package/dist/{cron-routes-Bc-SB0Se.js → cron-routes-DsH8Jwn5.js} +29 -6
  86. package/dist/cron-routes-DsH8Jwn5.js.map +1 -0
  87. package/dist/{cron-scheduler-CYQgco86.js → cron-scheduler-D1DT0nw5.js} +300 -34
  88. package/dist/cron-scheduler-D1DT0nw5.js.map +1 -0
  89. package/dist/cron-store-DEpVstUU.js +577 -0
  90. package/dist/cron-store-DEpVstUU.js.map +1 -0
  91. package/dist/{ddl-bootstrap-BaqMSa4Y.js → ddl-bootstrap-BNqi2NZe.js} +2 -2
  92. package/dist/{ddl-bootstrap-BaqMSa4Y.js.map → ddl-bootstrap-BNqi2NZe.js.map} +1 -1
  93. package/dist/email/smtp-email-service.d.ts +23 -0
  94. package/dist/email/types.d.ts +18 -0
  95. package/dist/env.d.ts +0 -37
  96. package/dist/{errors-D6_y86c5.js → errors-Cqp86KnA.js} +166 -7
  97. package/dist/errors-Cqp86KnA.js.map +1 -0
  98. package/dist/filter-dialect-O1HK6Nvr.js +1628 -0
  99. package/dist/filter-dialect-O1HK6Nvr.js.map +1 -0
  100. package/dist/{function-loader-D7o5Epjj.js → function-loader-DbCSoNJj.js} +69 -39
  101. package/dist/function-loader-DbCSoNJj.js.map +1 -0
  102. package/dist/{function-routes-CaNG4waN.js → function-routes-BSTClQNa.js} +6 -5
  103. package/dist/function-routes-BSTClQNa.js.map +1 -0
  104. package/dist/functions/context.d.ts +9 -0
  105. package/dist/functions/define-function.d.ts +10 -6
  106. package/dist/functions/function-loader.d.ts +75 -18
  107. package/dist/functions/function-routes.d.ts +2 -1
  108. package/dist/functions/index.d.ts +5 -4
  109. package/dist/functions/index.js +59 -15
  110. package/dist/functions/index.js.map +1 -1
  111. package/dist/functions/internal.d.ts +2 -2
  112. package/dist/functions/proxy.d.ts +6 -2
  113. package/dist/functions/request-timeout.d.ts +7 -5
  114. package/dist/history/history-routes.d.ts +9 -0
  115. package/dist/history/retention-sweep.d.ts +81 -0
  116. package/dist/{history-recorder-Nr8zLvoU.js → history-recorder-RZ1Ow4YY.js} +4 -4
  117. package/dist/{history-recorder-Nr8zLvoU.js.map → history-recorder-RZ1Ow4YY.js.map} +1 -1
  118. package/dist/{history-store-rcAm_xFR.js → history-store-DPofGVDp.js} +2 -2
  119. package/dist/{history-store-rcAm_xFR.js.map → history-store-DPofGVDp.js.map} +1 -1
  120. package/dist/index.d.ts +24 -11
  121. package/dist/index.es.js +24758 -20153
  122. package/dist/index.es.js.map +1 -1
  123. package/dist/init/docs.d.ts +35 -10
  124. package/dist/init/process-safety.d.ts +7 -2
  125. package/dist/init/shutdown.d.ts +18 -3
  126. package/dist/init.d.ts +49 -865
  127. package/dist/internal-tables-L2t39RdT.js +136 -0
  128. package/dist/internal-tables-L2t39RdT.js.map +1 -0
  129. package/dist/jobs/job-queue.d.ts +8 -0
  130. package/dist/jobs/job-store.d.ts +24 -0
  131. package/dist/jobs/types.d.ts +25 -4
  132. package/dist/{jobs-DqYNfquG.js → jobs-8G-_agld.js} +235 -25
  133. package/dist/jobs-8G-_agld.js.map +1 -0
  134. package/dist/{jwt-R6bSPMjk.js → jwt-CBaFc34Y.js} +530 -455
  135. package/dist/jwt-CBaFc34Y.js.map +1 -0
  136. package/dist/{keys-GAVZqbqx.js → keys-COzQ2aE8.js} +2 -2
  137. package/dist/{keys-GAVZqbqx.js.map → keys-COzQ2aE8.js.map} +1 -1
  138. package/dist/load-failure-L5hvfDoG.js +80 -0
  139. package/dist/load-failure-L5hvfDoG.js.map +1 -0
  140. package/dist/{logger-D-S-hO5e.js → logger-Bt32sHFw.js} +17 -4
  141. package/dist/logger-Bt32sHFw.js.map +1 -0
  142. package/dist/{logs-routes-DAdv37GI.js → logs-routes-DQJhrf-b.js} +3 -3
  143. package/dist/{logs-routes-DAdv37GI.js.map → logs-routes-DQJhrf-b.js.map} +1 -1
  144. package/dist/mcp/mcp-routes.d.ts +6 -0
  145. package/dist/mcp/mcp-tools.d.ts +8 -0
  146. package/dist/mcp/oauth-routes.d.ts +7 -0
  147. package/dist/metrics/index.d.ts +18 -0
  148. package/dist/metrics/pool-wait.d.ts +50 -0
  149. package/dist/offline-QNQgsPOq-B2yGeXkn.js +3305 -0
  150. package/dist/offline-QNQgsPOq-B2yGeXkn.js.map +1 -0
  151. package/dist/offline-store-Cm5sAX81-CALiO4Gn.js +1915 -0
  152. package/dist/offline-store-Cm5sAX81-CALiO4Gn.js.map +1 -0
  153. package/dist/{openapi-generator-DAq_XVDu.js → openapi-generator-CeGW2dLC.js} +366 -82
  154. package/dist/openapi-generator-CeGW2dLC.js.map +1 -0
  155. package/dist/policy-PdzX-Opd.js +121 -0
  156. package/dist/policy-PdzX-Opd.js.map +1 -0
  157. package/dist/project_manifest-R6y_KHms.js +59 -0
  158. package/dist/project_manifest-R6y_KHms.js.map +1 -0
  159. package/dist/{proxy-qRlqeUmO.js → proxy-BEKbsil6.js} +5 -4
  160. package/dist/proxy-BEKbsil6.js.map +1 -0
  161. package/dist/{query-parser-BgiKJKvc.js → query-parser-ECxP0nDw.js} +511 -16
  162. package/dist/query-parser-ECxP0nDw.js.map +1 -0
  163. package/dist/{request-timeout-DgH7j8qO.js → request-timeout-BiRelY-U.js} +17 -10
  164. package/dist/request-timeout-BiRelY-U.js.map +1 -0
  165. package/dist/resumable-upload-threshold-CKv-Ry0l.js +24 -0
  166. package/dist/resumable-upload-threshold-CKv-Ry0l.js.map +1 -0
  167. package/dist/schema-edit/apply-schema-change.d.ts +10 -0
  168. package/dist/schema-edit/local-source.d.ts +29 -0
  169. package/dist/schema-edit/remote-source.d.ts +13 -3
  170. package/dist/schema-edit/source-editor.d.ts +28 -0
  171. package/dist/{schema-editor-routes-oIyuWl3L.js → schema-editor-routes-DRXBAbZy.js} +55 -11
  172. package/dist/schema-editor-routes-DRXBAbZy.js.map +1 -0
  173. package/dist/services/outbound-post.d.ts +50 -0
  174. package/dist/services/outbound-url-guard.d.ts +34 -5
  175. package/dist/services/routed-realtime-service.d.ts +5 -0
  176. package/dist/services/webhook-service.d.ts +66 -14
  177. package/dist/singleton.d.ts +9 -5
  178. package/dist/soft-delete-params-CBryZXMq.js +668 -0
  179. package/dist/soft-delete-params-CBryZXMq.js.map +1 -0
  180. package/dist/sql-export-routes-D8ZaRvoR.js +240 -0
  181. package/dist/sql-export-routes-D8ZaRvoR.js.map +1 -0
  182. package/dist/{src-CatHFUym.js → src-D5Y3N-S4.js} +2 -1
  183. package/dist/{src-CatHFUym.js.map → src-D5Y3N-S4.js.map} +1 -1
  184. package/dist/storage/GCSStorageController.d.ts +46 -2
  185. package/dist/storage/LocalStorageController.d.ts +67 -2
  186. package/dist/storage/S3StorageController.d.ts +37 -3
  187. package/dist/storage/image-transform.d.ts +15 -0
  188. package/dist/storage/maintenance-routes.d.ts +23 -0
  189. package/dist/storage/maintenance.d.ts +126 -0
  190. package/dist/storage/rendition-cache.d.ts +9 -11
  191. package/dist/storage/request-principals.d.ts +30 -0
  192. package/dist/storage/routes.d.ts +20 -0
  193. package/dist/storage/source-variables.d.ts +10 -0
  194. package/dist/storage/streams.d.ts +42 -0
  195. package/dist/storage/tus-handler.d.ts +46 -2
  196. package/dist/storage/types.d.ts +82 -7
  197. package/dist/storage/upload-validation.d.ts +13 -0
  198. package/dist/storage-resumable-VO-cMpse-C_YX71pO.js +125 -0
  199. package/dist/storage-resumable-VO-cMpse-C_YX71pO.js.map +1 -0
  200. package/dist/strings.es-BeZWAodn.js +256 -0
  201. package/dist/strings.es-BeZWAodn.js.map +1 -0
  202. package/dist/upload-validation-CVobI5xO.js +172 -0
  203. package/dist/upload-validation-CVobI5xO.js.map +1 -0
  204. package/dist/utils/byte-size.d.ts +10 -0
  205. package/dist/utils/compression.d.ts +6 -0
  206. package/dist/utils/load-failure.d.ts +14 -0
  207. package/dist/utils/logger.d.ts +9 -0
  208. package/package.json +5 -5
  209. package/dist/GCSStorageController-BSiP1c-f.js +0 -256
  210. package/dist/GCSStorageController-BSiP1c-f.js.map +0 -1
  211. package/dist/S3StorageController-CAwFRgjV.js +0 -276
  212. package/dist/S3StorageController-CAwFRgjV.js.map +0 -1
  213. package/dist/auth-DMLngxn_.js.map +0 -1
  214. package/dist/backup-CN0s50D2.js.map +0 -1
  215. package/dist/contract-routes-fz8i4pxs.js.map +0 -1
  216. package/dist/cron-loader-CwaANlOG.js +0 -118
  217. package/dist/cron-loader-CwaANlOG.js.map +0 -1
  218. package/dist/cron-routes-Bc-SB0Se.js.map +0 -1
  219. package/dist/cron-scheduler-CYQgco86.js.map +0 -1
  220. package/dist/cron-store-D2Q9-Aco.js +0 -300
  221. package/dist/cron-store-D2Q9-Aco.js.map +0 -1
  222. package/dist/dynamic-import-X40pTZUQ.js +0 -23
  223. package/dist/dynamic-import-X40pTZUQ.js.map +0 -1
  224. package/dist/errors-D6_y86c5.js.map +0 -1
  225. package/dist/function-loader-D7o5Epjj.js.map +0 -1
  226. package/dist/function-routes-CaNG4waN.js.map +0 -1
  227. package/dist/jobs-DqYNfquG.js.map +0 -1
  228. package/dist/jwt-R6bSPMjk.js.map +0 -1
  229. package/dist/logger-D-S-hO5e.js.map +0 -1
  230. package/dist/openapi-generator-DAq_XVDu.js.map +0 -1
  231. package/dist/proxy-qRlqeUmO.js.map +0 -1
  232. package/dist/query-parser-BgiKJKvc.js.map +0 -1
  233. package/dist/request-timeout-DgH7j8qO.js.map +0 -1
  234. package/dist/schema-editor-routes-oIyuWl3L.js.map +0 -1
  235. package/dist/soft-delete-params-BWPilMPF.js +0 -59
  236. package/dist/soft-delete-params-BWPilMPF.js.map +0 -1
  237. package/dist/src-I3aG1PcY.js +0 -6870
  238. package/dist/src-I3aG1PcY.js.map +0 -1
  239. package/dist/types-BfKcm9do.js +0 -39
  240. 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-Cqp86KnA.js";
7
+ import { c as listingPrefix, s as folderKey } from "./keys-COzQ2aE8.js";
8
+ import { o as webStreamFrom, t as validateUploadedFile } from "./upload-validation-CVobI5xO.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-Btx-6bJ5.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"S3StorageController-Btx-6bJ5.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 === \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AAO,eAAe,QAAQ,MAAM,YAAY,KAAA;CAItD,OAAO;EAAE;EAAM,QAHA,OAAO,SAAS,YAAY,SAAS,QAAQ,oBAAoB,QAAQ,OAAO,KAAK,mBAAmB,WACjH,KAAK,iBACL,KAAA;CACgB;AAC1B;;;;;;;;;AAUA,SAAS,aAAa,OAAyB;CAC3C,MAAM,EAAE,MAAM,WAAW,aAAa,KAAK;CAC3C,IAAI,SAAS,gBAAgB,OAAO;CACpC,OAAO,SAAS,eAAe,SAAS,cAAc,WAAW;AACrE;;AAGA,IAAM,0CAA0B,IAAI,IAAI;CAAC;CAAgB;CAAgB;CAAsB;AAAuB,CAAC;;;;;;;;AASvH,SAAS,gBAAgB,OAAgB,QAAyB;CAC9D,MAAM,EAAE,SAAS,aAAa,KAAK;CACnC,IAAI,CAAC,QAAQ,CAAC,wBAAwB,IAAI,IAAI,GAAG,OAAO;CACxD,OAAO,IAAI,SACP,KACA,yBACA,SAAS,iBACH,uBAAuB,OAAO,+HAC9B,0EAA0E,OAAO,KAAK,KAAK,6DACjG;EAAE;EAAQ,QAAQ;CAAK,CAC3B;AACJ;AAEA,SAAS,wBAAwB,OAAyB;CACtD,MAAM,EAAE,MAAM,WAAW,aAAa,KAAK;CAC3C,OAAO,SAAS,kBAAkB,WAAW;AACjD;;AAGA,SAAS,eAAe,OAAoD;CACxE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,OAAO,iBAAiB;AAClF"}
@@ -32,6 +32,29 @@ export declare function schemaDriftRemedy(): {
32
32
  * nobody has does.
33
33
  */
34
34
  export declare function isDataException(error: unknown): boolean;
35
+ /**
36
+ * Did the request fail because the database could not be reached at all — not
37
+ * because it refused the statement, and not because some other service is down?
38
+ *
39
+ * Read off the error the database driver raised, wherever it sits in the cause
40
+ * chain:
41
+ *
42
+ * - a SQLSTATE that means the connection was refused or dropped (class `08`,
43
+ * `57P01`–`57P03`). The database's own word, so it settles the question
44
+ * either way: a SQLSTATE of any other class is the database answering;
45
+ * - node-postgres's own sentence for a socket that closed under a query;
46
+ * - a socket failure (`ECONNREFUSED`, `ENOTFOUND`, …), but only where it can
47
+ * only be the database's: thrown as it is, which is how node-postgres hands
48
+ * back a pool connection it could not open, or as the cause of a failed
49
+ * Drizzle query (the wrapper that carries the statement). Under any other
50
+ * wrapper it belongs to another client: `fetch failed` is a `fetch()` to
51
+ * some other host, and an S3 call that cannot connect carries the AWS SDK's
52
+ * `$metadata`. Answering those "the database is unreachable" would send an
53
+ * operator to a database that is fine.
54
+ */
55
+ export declare function isDatabaseUnreachable(error: unknown): boolean;
56
+ /** What a caller is told when the database cannot be reached. Retryable, and not about them. */
57
+ export declare const DATABASE_UNAVAILABLE_MESSAGE: string;
35
58
  /**
36
59
  * Standardized API error class.
37
60
  * Throw this from any route handler — the errorHandler middleware
@@ -81,6 +104,15 @@ export declare class ApiError extends Error {
81
104
  static conflict(message: string, code?: string, details?: unknown): ApiError;
82
105
  static internal(message: string, code?: string): ApiError;
83
106
  static serviceUnavailable(message: string, code?: string): ApiError;
107
+ /**
108
+ * `503 DATABASE_UNAVAILABLE`: the database could not be reached. What
109
+ * every door answers then — the data API, sign-in, the admin routes and
110
+ * the realtime socket — so a client sees one retryable answer, sent with
111
+ * `Retry-After`, rather than a permission failure or a crash.
112
+ *
113
+ * @see isDatabaseUnreachable
114
+ */
115
+ static databaseUnavailable(message?: string): ApiError;
84
116
  }
85
117
  /**
86
118
  * Canonical error response shape:
@@ -29,7 +29,7 @@
29
29
  * — `applySchemaChange` re-checks rather than trusting the plan it is handed.
30
30
  */
31
31
  import { Hono } from "hono";
32
- import { type CollectionPatch, type CollectionConfig, type DatabaseAdmin, type SchemaCommitPaths } from "@rebasepro/types";
32
+ import { type AuthAdapter, type CollectionPatch, type CollectionConfig, type DatabaseAdmin, type SchemaCommitPaths } from "@rebasepro/types";
33
33
  import { HonoEnv } from "./types.js";
34
34
  import { type SchemaEditRepository } from "../schema-edit/apply-schema-change.js";
35
35
  import { type SchemaEditPolicy } from "../schema-edit/schema-edit-permissions.js";
@@ -110,7 +110,27 @@ export interface LiveSchemaRoutesConfig {
110
110
  * commit, a commit needs an author, and a credential is not an author.
111
111
  */
112
112
  policy?: SchemaEditPolicy;
113
+ /**
114
+ * The account behind a uid, for the commit's author line.
115
+ *
116
+ * The request's user is what its access token carries, and the built-in
117
+ * token carries a uid and roles — no name, no address — so without this a
118
+ * commit is authored by the uid. Absent, or answering nothing, the commit
119
+ * falls back to what the request carries.
120
+ */
121
+ resolveAuthorIdentity?: (uid: string) => Promise<AccountIdentity | null>;
122
+ }
123
+ /** What a commit's author line is made of. */
124
+ export interface AccountIdentity {
125
+ displayName?: string | null;
126
+ email?: string | null;
113
127
  }
128
+ /**
129
+ * The account behind a uid, read through the auth in use: its user-management
130
+ * lookup when it has one — a plain read — else `resolveUser`. `null` when the
131
+ * auth has neither, or knows no such account.
132
+ */
133
+ export declare function readAccountIdentity(adapter: Pick<AuthAdapter, "userManagement" | "resolveUser"> | undefined, uid: string): Promise<AccountIdentity | null>;
114
134
  /**
115
135
  * What the panel posts about one collection.
116
136
  *
@@ -143,11 +163,15 @@ export interface ProposedChange {
143
163
  * `undefined` when the request carries no user — a service key, say — which
144
164
  * lets the repository fall back to its own git config rather than inventing a
145
165
  * name for somebody.
166
+ *
167
+ * The name and address the request carries win; what it lacks is read from
168
+ * the account through `resolveAccount`. A lookup that fails costs the commit
169
+ * its name, never the commit: the author falls back to the uid.
146
170
  */
147
- export declare function commitAuthor(user: unknown): {
171
+ export declare function commitAuthor(user: unknown, resolveAccount?: (uid: string) => Promise<AccountIdentity | null>): Promise<{
148
172
  name: string;
149
173
  email: string;
150
- } | undefined;
174
+ } | undefined>;
151
175
  /**
152
176
  * The change as a patch against the collection as it is.
153
177
  *