better-supabase 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +34 -31
  2. package/dist/base64-CQeB1eSf.js +42 -0
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/index.js +4 -14
  5. package/dist/{compiler-CZ9nIuqy.d.ts → compiler-2zqGzxVZ.d.ts} +2 -2
  6. package/dist/config/index.d.ts +4 -3
  7. package/dist/config/index.js +5 -3
  8. package/dist/config-Be4GwsqI.js +129 -0
  9. package/dist/{index-DOsjFvMf.d.ts → config-C1CYcm6o.d.ts} +49 -49
  10. package/dist/{config-ClDXmVtY.js → config-DOsGYSiT.js} +14 -137
  11. package/dist/{define-BXMYD9AY.js → define-DF341GDj.js} +71 -51
  12. package/dist/{define-e3zI4_4g.d.ts → define-DUbydmJa.d.ts} +10 -9
  13. package/dist/edge/index.d.ts +4 -4
  14. package/dist/edge/index.js +4 -4
  15. package/dist/{entitlements-Dng-ctuT.d.ts → entitlements-DvJXoI02.d.ts} +1 -1
  16. package/dist/env/index.js +203 -1
  17. package/dist/events/index.d.ts +1 -1
  18. package/dist/events/index.js +139 -1
  19. package/dist/{events-DOt3nSO-.d.ts → events-Do8jXh4D.d.ts} +3 -3
  20. package/dist/{executor-BYXQ9AGn.d.ts → executor-B26lgbHD.d.ts} +2 -2
  21. package/dist/{executor-DeppvirK.js → executor-C57jx2pn.js} +7 -2
  22. package/dist/{executor-CGdNQ27g.d.ts → executor-DynmIWhq.d.ts} +2 -2
  23. package/dist/hono/index.d.ts +5 -5
  24. package/dist/hono/index.js +4 -4
  25. package/dist/{index-CBDufH1M.d.ts → index-BNsABq7P.d.ts} +8 -8
  26. package/dist/{index-Bw1bwtC0.d.ts → index-CADlNHK-.d.ts} +27 -14
  27. package/dist/{index-DuP14VHo.d.ts → index-CTTMS6_1.d.ts} +19 -8
  28. package/dist/index-Cf-D2jk1.d.ts +50 -0
  29. package/dist/{index-K-3WM2Hp.d.ts → index-CriFFJ_p.d.ts} +4 -4
  30. package/dist/{index-Ciu5Xlml.d.ts → index-GV77NpRP.d.ts} +5 -4
  31. package/dist/{index-D4v7sncu.d.ts → index-UJ-LUxtI.d.ts} +3 -3
  32. package/dist/{index-CG69s15v.d.ts → index-kpgopLNv.d.ts} +4 -3
  33. package/dist/{index-DbxFr7XG.d.ts → index-qriRM9cZ.d.ts} +7 -2
  34. package/dist/index.d.ts +12 -12
  35. package/dist/index.js +16 -7
  36. package/dist/jobs/index.d.ts +25 -24
  37. package/dist/jobs/index.js +16 -10
  38. package/dist/{json-schema-BpYqkCKf.js → json-schema--aOXAGfU.js} +7 -2
  39. package/dist/lint/index.js +1 -1
  40. package/dist/list/index.d.ts +2 -2
  41. package/dist/list/index.js +128 -93
  42. package/dist/{live-DJyZMD6w.d.ts → live-QE3UPbGm.d.ts} +16 -6
  43. package/dist/mcp/index.d.ts +24 -17
  44. package/dist/mcp/index.js +41 -12
  45. package/dist/{mfa-CpLfJSde.js → mfa-BxoR1RkN.js} +74 -19
  46. package/dist/{mfa-TVia554c.d.ts → mfa-x3V3vGh-.d.ts} +1 -1
  47. package/dist/next/index.d.ts +39 -26
  48. package/dist/next/index.js +28 -23
  49. package/dist/openapi/index.d.ts +1 -1
  50. package/dist/openapi/index.js +57 -34
  51. package/dist/orpc/index.d.ts +6 -6
  52. package/dist/orpc/index.js +3 -3
  53. package/dist/otel/index.d.ts +2 -2
  54. package/dist/otel/index.js +4 -2
  55. package/dist/{permdock-sql-CghlHPuH.js → permdock-sql-Bta_G0v-.js} +11 -6
  56. package/dist/permdock-sql-DImJULY-.d.ts +17 -0
  57. package/dist/{plugin-C4TR9J0Z.d.ts → plugin-DVRB8qNE.d.ts} +5 -4
  58. package/dist/plugins/actor/index.d.ts +1 -1
  59. package/dist/plugins/rules/index.d.ts +2 -2
  60. package/dist/plugins/rules/index.js +4 -4
  61. package/dist/plugins/soft-delete/index.d.ts +3 -3
  62. package/dist/plugins/soft-delete/index.js +2 -2
  63. package/dist/plugins/tenant/index.d.ts +2 -2
  64. package/dist/plugins/timestamps/index.d.ts +1 -1
  65. package/dist/plugins/timestamps/index.js +1 -1
  66. package/dist/plugins/validation/index.d.ts +2 -2
  67. package/dist/pool-B9qsLyFR.d.ts +71 -0
  68. package/dist/postgres/index.d.ts +10 -5
  69. package/dist/postgres/index.js +36 -16
  70. package/dist/{postgrest-cAEQ_IQN.d.ts → postgrest-DmBlevh-.d.ts} +1 -1
  71. package/dist/{problem-BTkTtRV9.js → problem-CGt1ADix.js} +10 -4
  72. package/dist/{problem-DlgB0lYl.d.ts → problem-Z2RTQjZD.d.ts} +6 -4
  73. package/dist/query/index.d.ts +2 -2
  74. package/dist/query/index.js +1 -1
  75. package/dist/{query-ChvDbsDE.js → query-BdKLTPlj.js} +2 -2
  76. package/dist/react/index.d.ts +7 -7
  77. package/dist/react/index.js +2 -2
  78. package/dist/react/server.d.ts +3 -3
  79. package/dist/react/server.js +1 -1
  80. package/dist/react/session.d.ts +21 -2
  81. package/dist/react/session.js +19 -1
  82. package/dist/{react-C83BdBGt.js → react-DNBYNazu.js} +20 -16
  83. package/dist/{read-set-4lI3W_gZ.js → read-set-D0qBcboM.js} +3 -3
  84. package/dist/realtime/index.d.ts +4 -3
  85. package/dist/realtime/index.js +7 -6
  86. package/dist/{resolve-CjHILk2w.d.ts → resolve-BRciX2jK.d.ts} +6 -5
  87. package/dist/{resource-CgZa3YG_.d.ts → resource-CwVgiI5q.d.ts} +16 -7
  88. package/dist/{resource-BHEWmQJK.js → resource-D30rp0GN.js} +38 -16
  89. package/dist/{respond-DMcbQwfN.js → respond-C44EZAJo.js} +35 -19
  90. package/dist/{respond-Dne1ARSa.d.ts → respond-DAkPIdTH.d.ts} +15 -9
  91. package/dist/{result-CTkCZ6JA.d.ts → result-c2OYgCV2.d.ts} +13 -8
  92. package/dist/server/index.d.ts +35 -10
  93. package/dist/server/index.js +38 -9
  94. package/dist/{simplify-bwJpLnaS.js → simplify-LakqK1vH.js} +10 -16
  95. package/dist/sql/index.d.ts +139 -0
  96. package/dist/sql/index.js +1983 -0
  97. package/dist/{sql-DTjA1LPj.js → sql-BIgk12ew.js} +72 -16
  98. package/dist/ssr/index.d.ts +4 -4
  99. package/dist/ssr/index.js +2 -2
  100. package/dist/{standard-CyhRzctb.d.ts → standard-eudBiRk1.d.ts} +1 -1
  101. package/dist/{stats-C5W-rBfR.js → stats-D78UQ8Yu.js} +8 -7
  102. package/dist/storage/index.d.ts +4 -3
  103. package/dist/storage/index.js +530 -1
  104. package/dist/{tables-rZxRxNPW.js → tables-Dhha3BXM.js} +5 -5
  105. package/dist/temporal-BwshQk0W.js +27 -0
  106. package/dist/temporal-required-CMxeSVPo.js +19 -0
  107. package/dist/testing/index.d.ts +13 -11
  108. package/dist/testing/index.js +128 -29
  109. package/dist/{types-C83v5SQz.d.ts → types-DONv9SHN.d.ts} +14 -11
  110. package/dist/{version-Cqq1m3UY.js → version-BfpG2gks.js} +1 -1
  111. package/dist/{view-D1s0wa0T.d.ts → view-3Po_PVlr.d.ts} +34 -4
  112. package/dist/{view-aOYizTeE.js → view-wZ-9qIUz.js} +11 -2
  113. package/dist/webhooks/index.d.ts +18 -16
  114. package/dist/webhooks/index.js +1 -1
  115. package/dist/{webhooks-DMipjhSP.js → webhooks-CAIFQSTM.js} +11 -9
  116. package/package.json +24 -28
  117. package/schemas/config-v1.json +31 -1
  118. package/schemas/doctor-report-v1.json +17 -1
  119. package/schemas/snapshot-v2.json +35 -0
  120. package/skills/better-supabase/SKILL.md +23 -11
  121. package/skills/better-supabase/references/plugins.md +21 -18
  122. package/skills/better-supabase/references/troubleshooting.md +15 -15
  123. package/skills/better-supabase-api/SKILL.md +7 -7
  124. package/skills/better-supabase-api/references/adapters.md +30 -25
  125. package/skills/better-supabase-testing/SKILL.md +11 -8
  126. package/bin/better-supabase.js +0 -4
  127. package/dist/casing-da0uRTqt.js +0 -14
  128. package/dist/cli/bin.d.ts +0 -1
  129. package/dist/cli/bin.js +0 -15
  130. package/dist/cli/index.d.ts +0 -226
  131. package/dist/cli/index.js +0 -3
  132. package/dist/cli-DrSgDOQC.js +0 -6646
  133. package/dist/env-BEToab0I.js +0 -204
  134. package/dist/events-BuzTgn2D.js +0 -135
  135. package/dist/pool-R2m_DkXi.d.ts +0 -37
  136. package/dist/seed-CzecODcJ.js +0 -101
  137. package/dist/session-C3LxnQ0e.d.ts +0 -22
  138. package/dist/session-CqEwzVup.js +0 -20
  139. package/dist/storage-DuGn38fr.js +0 -527
@@ -1,2 +1,531 @@
1
- import { i as parseSize, n as defineBucket, r as fromStorageError, t as TTL } from "../storage-DuGn38fr.js";
1
+ import { n as dbError, o as isDbError, t as DbException } from "../errors-Bl3rkOzo.js";
2
+ import { r as optionalTemporal } from "../temporal-BwshQk0W.js";
3
+ import { n as temporalMissing } from "../temporal-required-CMxeSVPo.js";
4
+ import { i as ok, n as err, o as toDbError, t as AsyncResult } from "../result-DWXatkd6.js";
5
+ import { i as tenantClaimPaths } from "../claims-CoTobNC-.js";
6
+ import { a as sqlIdent, i as slug, o as sqlString, r as parseTemplate, t as permdockCheck } from "../permdock-sql-Bta_G0v-.js";
7
+ //#region src/storage/bucket.ts
8
+ /** Storage operations that list objects; every other `select` is a read. */
9
+ const LIST_OPERATIONS = [
10
+ "object.list",
11
+ "object.list_v2",
12
+ "s3.object.list"
13
+ ];
14
+ const TTL = {
15
+ minute: 60,
16
+ hour: 3600,
17
+ day: 86400,
18
+ week: 604800
19
+ };
20
+ const SIZE_UNITS = {
21
+ b: 1,
22
+ kb: 1e3,
23
+ kib: 1024,
24
+ mb: 1e3 ** 2,
25
+ mib: 1024 ** 2,
26
+ gb: 1e3 ** 3,
27
+ gib: 1024 ** 3
28
+ };
29
+ function parseSize(value) {
30
+ if (typeof value === "number") return value;
31
+ const match = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i.exec(value);
32
+ const unit = SIZE_UNITS[(match?.[2] || "b").toLowerCase()];
33
+ if (!match || unit === void 0) throw new TypeError(`Invalid size "${value}"`);
34
+ return Math.round(Number(match[1]) * unit);
35
+ }
36
+ const SAFE_SEGMENT = /^[\w!\-.*'() &$@=;:+,?]+$/;
37
+ function validateSegment(_name, value) {
38
+ if (value === "." || value === "..") return "is a relative path";
39
+ if (!SAFE_SEGMENT.test(value)) return "contains characters Storage does not allow";
40
+ }
41
+ function claimSql(claim) {
42
+ const expressions = (typeof claim === "string" ? [claim] : claim).map((path) => {
43
+ const keys = path.split(".");
44
+ const last = keys.pop();
45
+ return `(select auth.jwt())${keys.map((key) => ` -> ${sqlString(key)}`).join("")} ->> ${sqlString(last)}`;
46
+ });
47
+ return expressions.length === 1 ? expressions[0] : `coalesce(${expressions.join(", ")})`;
48
+ }
49
+ function mimeAllowed(allowed, type) {
50
+ const base = type.split(";")[0].trim().toLowerCase();
51
+ return allowed.some((entry) => {
52
+ const pattern = entry.toLowerCase();
53
+ return pattern.endsWith("/*") ? base.startsWith(pattern.slice(0, -1)) : base === pattern;
54
+ });
55
+ }
56
+ function sizeLabel(bytes) {
57
+ for (const [unit, size] of [
58
+ ["GiB", 1024 ** 3],
59
+ ["MiB", 1024 ** 2],
60
+ ["KiB", 1024]
61
+ ]) if (bytes >= size && bytes % size === 0) return `${String(bytes / size)}${unit}`;
62
+ return `${String(bytes)}B`;
63
+ }
64
+ /** Maps a Storage error (`StorageApiError`, fetch failures) to a `DbError`. */
65
+ function fromStorageError(raw, table) {
66
+ if (isDbError(raw)) return raw;
67
+ if (raw instanceof DbException) return raw.error;
68
+ if (typeof raw !== "object" || raw === null) return toDbError(raw);
69
+ const failure = raw;
70
+ if (failure.name === "AbortError") return toDbError(raw);
71
+ const message = failure.message ?? "Storage request failed";
72
+ const code = failure.code ?? failure.statusCode;
73
+ const base = {
74
+ ...code ? { code } : {},
75
+ ...table ? { table } : {}
76
+ };
77
+ const statusCode = Number(failure.statusCode);
78
+ const status = Number.isFinite(statusCode) && statusCode >= 400 ? statusCode : failure.status ?? 0;
79
+ if (/row-level security|unauthorized to|AccessDenied/i.test(`${message} ${code ?? ""}`)) return dbError("forbidden", message, base);
80
+ if (/already exists|duplicate/i.test(`${message} ${code ?? ""}`)) return dbError("conflict", message, base);
81
+ if (failure.name === "StorageUnknownError" && status === 0) return dbError("network", message, base);
82
+ switch (status) {
83
+ case 400: return dbError("invalid_request", message, base);
84
+ case 401: return dbError("unauthorized", message, base);
85
+ case 403: return dbError("forbidden", message, base);
86
+ case 404: return dbError("not_found", message, base);
87
+ case 409: return dbError("conflict", message, base);
88
+ case 413:
89
+ case 415: return dbError("invalid_input", message, {
90
+ ...base,
91
+ status
92
+ });
93
+ case 408:
94
+ case 429: return dbError("network", message, {
95
+ ...base,
96
+ status
97
+ });
98
+ default: return status >= 500 ? dbError("network", message, base) : dbError("unexpected", message, base);
99
+ }
100
+ }
101
+ /**
102
+ * A typed Storage bucket: path builders from a template, limits, generated
103
+ * SQL policies and `config.toml`, and helpers for the multi-step work apps
104
+ * repeat (replace, signed uploads, orphan cleanup).
105
+ *
106
+ * ```ts
107
+ * export const logos = defineBucket({
108
+ * id: 'customer-logos',
109
+ * path: '{orgId}/{customerId}/logo/{version}.webp',
110
+ * policy: 'tenant',
111
+ * fileSizeLimit: '5MiB',
112
+ * allowedMimeTypes: ['image/webp'],
113
+ * });
114
+ * ```
115
+ */
116
+ function defineBucket(config) {
117
+ const template = parseTemplate(config.path, "/", validateSegment);
118
+ const policy = config.policy ?? "none";
119
+ const fileSizeLimit = config.fileSizeLimit === void 0 ? void 0 : parseSize(config.fileSizeLimit);
120
+ const allowedMimeTypes = config.allowedMimeTypes;
121
+ function segmentFor(param, kind) {
122
+ const index = template.segmentOf(param);
123
+ if (index === void 0) throw new TypeError(`defineBucket: a ${kind} policy needs {${param}} as a whole path segment in "${config.path}"`);
124
+ return index;
125
+ }
126
+ const mode = typeof policy === "string" ? policy : "permdock";
127
+ const accessCheck = (() => {
128
+ switch (mode) {
129
+ case "tenant": {
130
+ const index = segmentFor(config.tenant?.param ?? "orgId", "tenant");
131
+ const expression = config.tenant?.sql ?? claimSql(config.tenant?.claim ?? tenantClaimPaths());
132
+ return `split_part(name, '/', ${String(index)}) = (${expression})`;
133
+ }
134
+ case "owner": {
135
+ const index = segmentFor(config.owner?.param ?? "userId", "owner");
136
+ return `split_part(name, '/', ${String(index)}) = (select auth.uid())::text`;
137
+ }
138
+ case "public":
139
+ case "none":
140
+ case "permdock": return;
141
+ default: throw new TypeError(`defineBucket: unknown policy "${String(mode)}"`);
142
+ }
143
+ })();
144
+ const permdock = (() => {
145
+ if (typeof policy === "string") return void 0;
146
+ const where = `defineBucket(${config.id})`;
147
+ const id = policy.scope === "global" ? void 0 : `split_part(name, '/', ${String(policy.segment ?? segmentFor(config.tenant?.param ?? "orgId", "PermDock"))})`;
148
+ const check = (key) => permdockCheck(where, policy, key, id, config.catalog);
149
+ const keys = policy.permdock;
150
+ return {
151
+ read: check(keys.read),
152
+ ...keys.list === void 0 ? {} : { list: check(keys.list) },
153
+ write: check(keys.write),
154
+ delete: check(keys.delete ?? keys.write)
155
+ };
156
+ })();
157
+ const resolve = (target) => {
158
+ if (typeof target !== "string") return template.build(target);
159
+ if (!template.match(target)) throw new DbException(dbError("invalid_input", `Path "${target}" does not match "${config.path}"`));
160
+ return target;
161
+ };
162
+ const check = (file) => {
163
+ if (fileSizeLimit !== void 0 && file.size !== void 0 && file.size > fileSizeLimit) return dbError("invalid_input", `File is larger than ${sizeLabel(fileSizeLimit)}`, { status: 413 });
164
+ if (allowedMimeTypes && file.type && !mimeAllowed(allowedMimeTypes, file.type)) return dbError("invalid_input", `File type ${file.type} is not allowed`, { status: 415 });
165
+ };
166
+ const bucket = {
167
+ id: config.id,
168
+ template: config.path,
169
+ params: template.params,
170
+ owner: policy === "owner" ? config.owner?.param ?? "userId" : template.params.includes("userId") ? "userId" : void 0,
171
+ public: config.public ?? false,
172
+ policy,
173
+ fileSizeLimit,
174
+ allowedMimeTypes,
175
+ path: (values) => template.build(values),
176
+ match: (path) => template.match(path),
177
+ prefix: (values = {}) => template.prefix(values, template.segments - 1),
178
+ check,
179
+ sql() {
180
+ const id = sqlString(config.id);
181
+ const name = slug(config.id);
182
+ const lines = [
183
+ `-- better-supabase: bucket ${config.id} (${config.path})`,
184
+ "insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)",
185
+ `values (${id}, ${id}, ${String(bucket.public)}, ${fileSizeLimit === void 0 ? "null" : String(fileSizeLimit)}, ${allowedMimeTypes ? `array[${allowedMimeTypes.map(sqlString).join(", ")}]` : "null"})`,
186
+ "on conflict (id) do update set public = excluded.public, file_size_limit = excluded.file_size_limit,",
187
+ " allowed_mime_types = excluded.allowed_mime_types;"
188
+ ];
189
+ const policies = [];
190
+ const inBucket = `bucket_id = ${id}`;
191
+ const pathMatch = `name ~ ${sqlString(template.sqlPattern)}`;
192
+ if (accessCheck) {
193
+ const using = `${inBucket} and ${accessCheck}`;
194
+ const write = `${using} and ${pathMatch}`;
195
+ policies.push([
196
+ "select",
197
+ "select",
198
+ "authenticated",
199
+ using,
200
+ void 0
201
+ ], [
202
+ "insert",
203
+ "insert",
204
+ "authenticated",
205
+ void 0,
206
+ write
207
+ ], [
208
+ "update",
209
+ "update",
210
+ "authenticated",
211
+ using,
212
+ write
213
+ ], [
214
+ "delete",
215
+ "delete",
216
+ "authenticated",
217
+ using,
218
+ void 0
219
+ ]);
220
+ } else if (policy === "public") policies.push([
221
+ "select",
222
+ "select",
223
+ "anon, authenticated",
224
+ inBucket,
225
+ void 0
226
+ ]);
227
+ else if (permdock) {
228
+ const listing = `storage.allow_any_operation(array[${LIST_OPERATIONS.map(sqlString).join(", ")}])`;
229
+ if (permdock.list) policies.push([
230
+ "select",
231
+ "select",
232
+ "authenticated",
233
+ `${inBucket} and not ${listing} and ${permdock.read}`,
234
+ void 0
235
+ ], [
236
+ "list",
237
+ "select",
238
+ "authenticated",
239
+ `${inBucket} and ${listing} and ${permdock.list}`,
240
+ void 0
241
+ ]);
242
+ else policies.push([
243
+ "select",
244
+ "select",
245
+ "authenticated",
246
+ `${inBucket} and ${permdock.read}`,
247
+ void 0
248
+ ]);
249
+ const write = `${inBucket} and ${permdock.write}`;
250
+ policies.push([
251
+ "insert",
252
+ "insert",
253
+ "authenticated",
254
+ void 0,
255
+ `${write} and ${pathMatch}`
256
+ ], [
257
+ "update",
258
+ "update",
259
+ "authenticated",
260
+ write,
261
+ `${write} and ${pathMatch}`
262
+ ], [
263
+ "delete",
264
+ "delete",
265
+ "authenticated",
266
+ `${inBucket} and ${permdock.delete}`,
267
+ void 0
268
+ ]);
269
+ }
270
+ for (const [suffix, command, roles, using, withCheck] of policies) {
271
+ const policyName = sqlIdent(`bs_${name}_${suffix}`);
272
+ lines.push("", `drop policy if exists ${policyName} on storage.objects;`, `create policy ${policyName} on storage.objects for ${command} to ${roles}${using ? `\n using (${using})` : ""}${withCheck ? `\n with check (${withCheck})` : ""};`);
273
+ }
274
+ if (permdock && !permdock.list) lines.push("", `drop policy if exists ${sqlIdent(`bs_${name}_list`)} on storage.objects;`);
275
+ return `${lines.join("\n")}\n`;
276
+ },
277
+ toml() {
278
+ const lines = [`[storage.buckets.${config.id}]`, `public = ${String(bucket.public)}`];
279
+ if (config.fileSizeLimit !== void 0) lines.push(`file_size_limit = "${typeof config.fileSizeLimit === "number" ? sizeLabel(config.fileSizeLimit) : config.fileSizeLimit}"`);
280
+ if (allowedMimeTypes) lines.push(`allowed_mime_types = [${allowedMimeTypes.map((type) => JSON.stringify(type)).join(", ")}]`);
281
+ return `${lines.join("\n")}\n`;
282
+ },
283
+ drift(actual) {
284
+ if (!actual) return [{
285
+ field: "missing",
286
+ expected: config.id,
287
+ actual: void 0,
288
+ message: `Bucket "${config.id}" does not exist`
289
+ }];
290
+ const issues = [];
291
+ if (actual.public !== bucket.public) issues.push({
292
+ field: "public",
293
+ expected: bucket.public,
294
+ actual: actual.public,
295
+ message: `Bucket "${config.id}" public is ${String(actual.public)}`
296
+ });
297
+ if ((actual.fileSizeLimit ?? void 0) !== fileSizeLimit) issues.push({
298
+ field: "fileSizeLimit",
299
+ expected: fileSizeLimit,
300
+ actual: actual.fileSizeLimit,
301
+ message: `Bucket "${config.id}" file size limit differs`
302
+ });
303
+ const sorted = (list) => list ? [...list].sort().join(",") : "";
304
+ if (sorted(actual.allowedMimeTypes) !== sorted(allowedMimeTypes)) issues.push({
305
+ field: "allowedMimeTypes",
306
+ expected: allowedMimeTypes,
307
+ actual: actual.allowedMimeTypes,
308
+ message: `Bucket "${config.id}" allowed MIME types differ`
309
+ });
310
+ return issues;
311
+ },
312
+ connect: (client) => connectBucket(bucket, client, resolve)
313
+ };
314
+ return bucket;
315
+ }
316
+ function bodyInfo(body, contentType) {
317
+ const info = {};
318
+ if (typeof Blob !== "undefined" && body instanceof Blob) {
319
+ info.size = body.size;
320
+ if (body.type) info.type = body.type;
321
+ } else if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) info.size = body.byteLength;
322
+ if (contentType) info.type = contentType;
323
+ return info;
324
+ }
325
+ function ttlSeconds(ttl) {
326
+ return typeof ttl === "number" ? ttl : TTL[ttl ?? "hour"];
327
+ }
328
+ function isErrorResult(value) {
329
+ return typeof value === "object" && value !== null && value.ok === false && "error" in value;
330
+ }
331
+ function connectBucket(bucket, client, resolve) {
332
+ const api = () => client.storage.from(bucket.id);
333
+ const run = (fn) => AsyncResult.from(async () => {
334
+ try {
335
+ const { data, error } = await fn();
336
+ return error || data === null ? err(fromStorageError(error, bucket.id)) : ok(data);
337
+ } catch (cause) {
338
+ return err(fromStorageError(cause, bucket.id));
339
+ }
340
+ });
341
+ const fileOptions = (options, contentType) => ({
342
+ ...contentType ? { contentType } : {},
343
+ ...options?.cacheControl ? { cacheControl: options.cacheControl } : {},
344
+ ...options?.metadata ? { metadata: { ...options.metadata } } : {},
345
+ upsert: options?.upsert ?? false
346
+ });
347
+ const download = (value) => value === void 0 ? {} : { download: value };
348
+ const upload = (target, body, options) => AsyncResult.from(async () => {
349
+ options?.signal?.throwIfAborted();
350
+ const path = resolve(target);
351
+ const contentType = options?.contentType;
352
+ const problem = bucket.check(bodyInfo(body, contentType));
353
+ if (problem) return err(problem);
354
+ return run(() => api().upload(path, body, fileOptions(options, contentType))).map(() => ({ path }));
355
+ });
356
+ const remove = (targets) => AsyncResult.from(async () => {
357
+ const paths = targets.map(resolve);
358
+ if (paths.length === 0) return ok([]);
359
+ return run(() => api().remove(paths)).map(() => paths);
360
+ });
361
+ const walk = async (folder, signal, out) => {
362
+ const limit = 1e3;
363
+ for (let offset = 0;; offset += limit) {
364
+ signal?.throwIfAborted();
365
+ const { data, error } = await api().list(folder, {
366
+ limit,
367
+ offset,
368
+ sortBy: {
369
+ column: "name",
370
+ order: "asc"
371
+ }
372
+ }, signal ? { signal } : {});
373
+ if (error) throw new DbException(fromStorageError(error, bucket.id));
374
+ for (const item of data) {
375
+ const path = folder ? `${folder}/${item.name}` : item.name;
376
+ if (item.id === null) await walk(path, signal, out);
377
+ else {
378
+ const metadata = item.metadata ?? {};
379
+ out.push({
380
+ path,
381
+ ...typeof metadata.size === "number" ? { size: metadata.size } : {},
382
+ ...metadata.mimetype ? { contentType: metadata.mimetype } : {},
383
+ createdAt: item.created_at,
384
+ updatedAt: item.updated_at
385
+ });
386
+ }
387
+ }
388
+ if (data.length < limit) return;
389
+ }
390
+ };
391
+ const list = (within, options) => AsyncResult.from(async () => {
392
+ const out = [];
393
+ await walk(bucket.prefix(within ?? {}), options?.signal, out);
394
+ return ok(out);
395
+ }).mapError((error) => ({
396
+ ...error,
397
+ table: bucket.id
398
+ }));
399
+ const signedUrl = (target, options) => AsyncResult.from(async () => {
400
+ const path = resolve(target);
401
+ return run(() => api().createSignedUrl(path, ttlSeconds(options?.ttl), {
402
+ ...download(options?.download),
403
+ ...options?.transform ? { transform: { ...options.transform } } : {}
404
+ })).map((data) => data.signedUrl);
405
+ });
406
+ return {
407
+ bucket,
408
+ upload,
409
+ download: (target, options) => AsyncResult.from(async () => {
410
+ const path = resolve(target);
411
+ return run(() => api().download(path, {}, options?.signal ? { signal: options.signal } : {}));
412
+ }),
413
+ exists: (target) => AsyncResult.from(async () => {
414
+ const path = resolve(target);
415
+ const found = await api().exists(path);
416
+ if (!found.data) return ok(false);
417
+ return found.error ? err(fromStorageError(found.error, bucket.id)) : ok(true);
418
+ }),
419
+ remove,
420
+ list,
421
+ signedUrl,
422
+ signedUrls: (targets, options) => AsyncResult.from(async () => {
423
+ const paths = targets.map(resolve);
424
+ if (paths.length === 0) return ok([]);
425
+ return run(() => api().createSignedUrls(paths, ttlSeconds(options?.ttl), download(options?.download))).andThen((data) => {
426
+ const failed = data.find((entry) => entry.error != null || !entry.signedUrl);
427
+ if (failed) return Promise.resolve(err(dbError("not_found", failed.error ?? `No URL for ${String(failed.path)}`, { table: bucket.id })));
428
+ return Promise.resolve(ok(data.map((entry) => entry.signedUrl)));
429
+ });
430
+ }),
431
+ publicUrl(target, options) {
432
+ const path = resolve(target);
433
+ return api().getPublicUrl(path, {
434
+ ...download(options?.download),
435
+ ...options?.transform ? { transform: { ...options.transform } } : {}
436
+ }).data.publicUrl;
437
+ },
438
+ renderUrl(target, transform, options) {
439
+ if (!bucket.public) return signedUrl(target, {
440
+ ...options,
441
+ transform
442
+ });
443
+ return AsyncResult.from(() => Promise.resolve(ok(api().getPublicUrl(resolve(target), {
444
+ ...download(options?.download),
445
+ transform: { ...transform }
446
+ }).data.publicUrl)));
447
+ },
448
+ replace: (target, body, options = {}) => AsyncResult.from(async () => {
449
+ const path = resolve(target);
450
+ const previous = options.previous ?? null;
451
+ const same = previous === path;
452
+ const uploaded = await upload(path, body, {
453
+ ...options,
454
+ upsert: same || (options.upsert ?? false)
455
+ });
456
+ if (!uploaded.ok) return uploaded;
457
+ const undo = async (error) => {
458
+ if (!same) await remove([path]);
459
+ return err(error);
460
+ };
461
+ try {
462
+ options.signal?.throwIfAborted();
463
+ const outcome = await options.commit?.(path);
464
+ if (isErrorResult(outcome)) return await undo(outcome.error);
465
+ } catch (cause) {
466
+ return undo(fromStorageError(cause, bucket.id));
467
+ }
468
+ if (!previous || same) return ok({
469
+ path,
470
+ removed: null
471
+ });
472
+ const removed = await run(() => api().remove([previous]));
473
+ return ok(removed.ok ? {
474
+ path,
475
+ removed: previous
476
+ } : {
477
+ path,
478
+ removed: null,
479
+ cleanup: removed.error
480
+ });
481
+ }),
482
+ reserve: (target, options) => AsyncResult.from(async () => {
483
+ const path = resolve(target);
484
+ return run(() => api().createSignedUploadUrl(path, options?.upsert ? { upsert: true } : void 0)).map((data) => ({
485
+ path: data.path,
486
+ token: data.token,
487
+ signedUrl: data.signedUrl
488
+ }));
489
+ }),
490
+ uploadReserved: (reservation, body, options) => AsyncResult.from(async () => {
491
+ options?.signal?.throwIfAborted();
492
+ const path = resolve(reservation.path);
493
+ const problem = bucket.check(bodyInfo(body, options?.contentType));
494
+ if (problem) return err(problem);
495
+ return run(() => api().uploadToSignedUrl(path, reservation.token, body, fileOptions(options, options?.contentType))).map(() => ({ path }));
496
+ }),
497
+ sweep: (options) => AsyncResult.from(async () => {
498
+ const namespace = optionalTemporal();
499
+ if (namespace === void 0) return err(temporalMissing());
500
+ const now = options.now?.() ?? namespace.Now.instant();
501
+ const cutoff = options.olderThan instanceof namespace.Instant ? options.olderThan.epochMilliseconds : now.epochMilliseconds - options.olderThan.total("milliseconds");
502
+ const found = await list(options.within, options.signal ? { signal: options.signal } : void 0);
503
+ if (!found.ok) return found;
504
+ const candidates = found.data.filter((object) => bucket.match(object.path) !== null).filter((object) => {
505
+ const created = Date.parse(object.createdAt ?? object.updatedAt ?? "");
506
+ return Number.isFinite(created) && created < cutoff;
507
+ }).map((object) => object.path);
508
+ const size = options.batchSize ?? 100;
509
+ const orphans = [];
510
+ const removed = [];
511
+ for (let index = 0; index < candidates.length; index += size) {
512
+ options.signal?.throwIfAborted();
513
+ const batch = candidates.slice(index, index + size);
514
+ const keep = new Set(await options.referenced(batch));
515
+ const unreferenced = batch.filter((path) => !keep.has(path));
516
+ orphans.push(...unreferenced);
517
+ if (options.dryRun || unreferenced.length === 0) continue;
518
+ const result = await run(() => api().remove(unreferenced));
519
+ if (!result.ok) return result;
520
+ removed.push(...unreferenced);
521
+ }
522
+ return ok({
523
+ scanned: found.data.length,
524
+ orphans,
525
+ removed
526
+ });
527
+ })
528
+ };
529
+ }
530
+ //#endregion
2
531
  export { TTL, defineBucket, fromStorageError, parseSize };
@@ -24,16 +24,16 @@ function visitCondition(condition, tables) {
24
24
  case "and":
25
25
  case "or":
26
26
  for (const item of condition.items) visitCondition(item, tables);
27
- return;
27
+ break;
28
28
  case "not":
29
29
  visitCondition(condition.item, tables);
30
- return;
31
- case "column": return;
30
+ break;
31
+ case "column": break;
32
32
  case "relation":
33
33
  tables.add(condition.target.key);
34
34
  visitCondition(condition.where, tables);
35
- return;
36
- default: return condition;
35
+ break;
36
+ default: throw new TypeError(`Unknown condition: ${String(condition)}`);
37
37
  }
38
38
  }
39
39
  /**
@@ -0,0 +1,27 @@
1
+ const TEMPORAL_MISSING = `Temporal is not available in this runtime. Import "temporal-polyfill/global" once at startup.`;
2
+ /** The runtime's `Temporal`, or `undefined` before the polyfill loads. */
3
+ function optionalTemporal() {
4
+ return globalThis.Temporal;
5
+ }
6
+ /**
7
+ * The current instant, the default `now` everywhere. Without Temporal it
8
+ * throws a `TypeError` that names the polyfill.
9
+ */
10
+ function nowInstant() {
11
+ const namespace = optionalTemporal();
12
+ if (namespace === void 0) throw new TypeError(TEMPORAL_MISSING);
13
+ return namespace.Now.instant();
14
+ }
15
+ /**
16
+ * The text Postgres reads back for a Temporal value: ISO 8601, with a
17
+ * `ZonedDateTime` sent as its instant because Postgres rejects the
18
+ * `[Region/City]` annotation. `undefined` for anything else.
19
+ */
20
+ function temporalText(value) {
21
+ const namespace = optionalTemporal();
22
+ if (namespace === void 0) return void 0;
23
+ if (value instanceof namespace.ZonedDateTime) return value.toInstant().toString();
24
+ if (value instanceof namespace.Instant || value instanceof namespace.PlainDateTime || value instanceof namespace.PlainDate || value instanceof namespace.PlainTime) return value.toString();
25
+ }
26
+ //#endregion
27
+ export { temporalText as i, nowInstant as n, optionalTemporal as r, TEMPORAL_MISSING as t };
@@ -0,0 +1,19 @@
1
+ import { n as dbError, t as DbException } from "./errors-Bl3rkOzo.js";
2
+ import { r as optionalTemporal, t as TEMPORAL_MISSING } from "./temporal-BwshQk0W.js";
3
+ //#region src/core/temporal-required.ts
4
+ /** The error for a runtime without Temporal, naming the polyfill to load. */
5
+ function temporalMissing() {
6
+ return dbError("unexpected", TEMPORAL_MISSING);
7
+ }
8
+ /**
9
+ * The runtime's `Temporal`. Node 26, Chromium, Firefox and Deno ship it.
10
+ * Elsewhere it throws a `DbException`, which repositories return as an
11
+ * `unexpected` error that names the polyfill.
12
+ */
13
+ function temporal() {
14
+ const namespace = optionalTemporal();
15
+ if (namespace === void 0) throw new DbException(temporalMissing());
16
+ return namespace;
17
+ }
18
+ //#endregion
19
+ export { temporalMissing as n, temporal as t };
@@ -1,13 +1,15 @@
1
- import { d as Generator, f as GeneratorInput, y as ResolvedConfig } from "../index-DOsjFvMf.js";
2
- import { A as SchemaMeta, N as TableKey, R as Update, _ as Insert, n as AnyModels, t as AnyFunctions } from "../types-C83v5SQz.js";
3
- import { r as Executor } from "../executor-CGdNQ27g.js";
4
- import { P as DbStats, l as CacheAdapter, t as BetterSupabase, y as Db } from "../define-e3zI4_4g.js";
5
- import { h as RequestContext, n as AnyPlugin } from "../plugin-C4TR9J0Z.js";
6
- import { t as SqlClient } from "../executor-BYXQ9AGn.js";
7
- import { t as Postgres } from "../pool-R2m_DkXi.js";
8
- import { n as AuthResolver } from "../resolve-CjHILk2w.js";
9
- import { r as EventSink, t as CloudEvent } from "../index-Ciu5Xlml.js";
1
+ import { A as SchemaMeta, N as TableKey, R as Update, g as Insert, n as AnyModels, t as AnyFunctions } from "../types-DONv9SHN.js";
2
+ import { r as Executor } from "../executor-DynmIWhq.js";
3
+ import { P as DbStats, l as CacheAdapter, t as BetterSupabase, y as Db } from "../define-DUbydmJa.js";
4
+ import { h as RequestContext, n as AnyPlugin } from "../plugin-DVRB8qNE.js";
5
+ import { b as ResolvedConfig, d as Generator, f as GeneratorInput } from "../config-C1CYcm6o.js";
6
+ import "../index-Cf-D2jk1.js";
7
+ import { t as SqlClient } from "../executor-B26lgbHD.js";
8
+ import { r as Postgres } from "../pool-B9qsLyFR.js";
9
+ import { n as AuthResolver } from "../resolve-BRciX2jK.js";
10
+ import { r as EventSink, t as CloudEvent } from "../index-GV77NpRP.js";
10
11
  import { SupabaseClient } from "@supabase/supabase-js";
12
+ import { webcrypto } from "node:crypto";
11
13
  //#region src/testing/jwt.d.ts
12
14
  interface TestJwtClaims {
13
15
  readonly sub: string;
@@ -31,12 +33,12 @@ export declare function localAuth(secret: string): AuthResolver;
31
33
  interface TestSigner {
32
34
  /** Public JWKS; pass as `jwks` to `resolveAuth` / `createServer({ auth: { jwks } })`. */
33
35
  readonly jwks: {
34
- readonly keys: readonly JsonWebKey[];
36
+ readonly keys: readonly webcrypto.JsonWebKey[];
35
37
  };
36
38
  sign(claims: TestJwtClaims): Promise<string>;
37
39
  }
38
40
  /** A private ES256 JWK, as `better-supabase keys` writes to `supabase/signing_keys.json`. */
39
- interface SigningJwk extends JsonWebKey {
41
+ interface SigningJwk extends webcrypto.JsonWebKey {
40
42
  readonly kid: string;
41
43
  }
42
44
  /**