@freehour/supabase-core 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { assert as l } from "@freehour/assert";
2
- import m from "zod";
3
- import { PostgrestError as P } from "@supabase/supabase-js";
4
- import { Mime as S } from "@freehour/mime";
5
- class k extends Error {
2
+ import f from "zod";
3
+ import { PostgrestError as j } from "@supabase/supabase-js";
4
+ import * as $ from "@supabase/postgrest-js";
5
+ import { Mime as _ } from "@freehour/mime";
6
+ class E extends Error {
6
7
  constructor(t, e = {}) {
7
8
  super(t, e), this.name = this.constructor.name, Error.captureStackTrace(this, this.constructor);
8
9
  }
9
10
  }
10
- class E extends k {
11
+ class x extends E {
11
12
  /**
12
13
  * The ID of the file that was not found.
13
14
  */
@@ -23,12 +24,12 @@ class E extends k {
23
24
  constructor(t, {
24
25
  fileId: e,
25
26
  bucket: r,
26
- path: a
27
+ path: n
27
28
  } = {}) {
28
- super(t), this.fileId = e, this.bucket = r, this.path = a;
29
+ super(t), this.fileId = e, this.bucket = r, this.path = n;
29
30
  }
30
31
  }
31
- class x extends k {
32
+ class S extends E {
32
33
  /**
33
34
  * The encountered expression that could not be parsed.
34
35
  */
@@ -40,12 +41,12 @@ class x extends k {
40
41
  constructor(t, {
41
42
  expression: e,
42
43
  format: r,
43
- ...a
44
+ ...n
44
45
  } = {}) {
45
- super(t, a), this.expression = e, this.format = r;
46
+ super(t, n), this.expression = e, this.format = r;
46
47
  }
47
48
  }
48
- class _ extends k {
49
+ class N extends E {
49
50
  /**
50
51
  * The schema where the record was expected to be found.
51
52
  */
@@ -61,12 +62,12 @@ class _ extends k {
61
62
  constructor(t, {
62
63
  schema: e,
63
64
  relation: r,
64
- id: a
65
+ id: n
65
66
  } = {}) {
66
- super(t), this.schema = e, this.relation = r, this.id = a;
67
+ super(t), this.schema = e, this.relation = r, this.id = n;
67
68
  }
68
69
  }
69
- class I extends Error {
70
+ class P extends Error {
70
71
  /**
71
72
  * The MIME type that is unsupported.
72
73
  */
@@ -78,270 +79,42 @@ class I extends Error {
78
79
  constructor(t, {
79
80
  value: e,
80
81
  supported: r,
81
- ...a
82
+ ...n
82
83
  } = {}) {
83
- super(t, a), this.value = e, this.supported = r;
84
+ super(t, n), this.value = e, this.supported = r;
84
85
  }
85
86
  }
86
- const $ = m.object({
87
- code: m.string(),
88
- details: m.string().nullable(),
89
- hint: m.string().nullable(),
90
- name: m.string().optional(),
91
- message: m.string().optional()
87
+ const D = f.object({
88
+ code: f.string(),
89
+ details: f.string().nullable(),
90
+ hint: f.string().nullable(),
91
+ name: f.string().optional(),
92
+ message: f.string().optional()
92
93
  });
93
- function H(s) {
94
- return s instanceof P || $.safeParse(s).success;
94
+ function J(s) {
95
+ return s instanceof j || D.safeParse(s).success;
95
96
  }
96
- const v = ["eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "match", "imatch", "in", "is", "isdistinct", "fts", "plfts", "phfts", "wfts", "cs", "cd", "ov", "sl", "sr", "nxr", "nxl", "adj"], J = ["and", "or"], Q = ",", O = "~", X = (s) => (t = {}) => {
97
- const e = (a) => t[a] ?? a, r = Object.keys(s.shape);
98
- return m.string().transform((a, n) => {
99
- try {
100
- return L(a, r, e);
101
- } catch (i) {
102
- return n.addIssue({
103
- code: "custom",
104
- input: a,
105
- message: i instanceof Error ? i.message : void 0,
106
- params: i instanceof x ? {
107
- expression: i.expression,
108
- format: i.format
109
- } : void 0
110
- }), [];
111
- }
112
- });
113
- };
114
- function j(s) {
115
- return s.startsWith("not.") ? s.slice(4) : `not.${s}`;
116
- }
117
- function N(s) {
118
- return {
119
- ...s,
120
- op: j(s.op)
121
- };
122
- }
123
- function q(s, t = (e) => e) {
124
- if (s.type === "logical") {
125
- const e = s.args.map((r) => q(r, t));
126
- return `${s.op}(${e})`;
127
- }
128
- return `${t(s.key)}.${s.op}.${s.value}`;
129
- }
130
- function D(s, t = (r) => r, e = O) {
131
- return s.map((r) => q(r, t)).join(e);
132
- }
133
- function y(s, t = [], e = (r) => r) {
134
- function r(u) {
135
- const p = [];
136
- let b = 0, f = "";
137
- for (const g of u)
138
- g === "(" ? (b++, f += g) : g === ")" ? (b--, f += g) : g === "," && b === 0 ? (p.push(f.trim()), f = "") : f += g;
139
- return f && p.push(f.trim()), p;
140
- }
141
- if (s.endsWith(")")) {
142
- if (s.startsWith("and("))
143
- return {
144
- type: "logical",
145
- op: "and",
146
- args: r(s.slice(4, -1)).map((u) => y(u, t, e))
147
- };
148
- if (s.startsWith("or("))
149
- return {
150
- type: "logical",
151
- op: "or",
152
- args: r(s.slice(3, -1)).map((u) => y(u, t, e))
153
- };
154
- if (s.startsWith("not.and("))
155
- return {
156
- type: "logical",
157
- op: "not.and",
158
- args: r(s.slice(8, -1)).map((u) => y(u, t, e))
159
- };
160
- if (s.startsWith("not.or("))
161
- return {
162
- type: "logical",
163
- op: "not.or",
164
- args: r(s.slice(7, -1)).map((u) => y(u, t, e))
165
- };
166
- }
167
- const n = `^(${t.length === 0 ? "[a-zA-Z_][a-zA-Z0-9_]*" : t.join("|")})\\.((?:not\\.)?(?:${v.join("|")}))\\.(.+)$`, c = new RegExp(n).exec(s);
168
- if (!c)
169
- throw new x(`Invalid filter expression '${s}'`, {
170
- expression: s,
171
- format: {
172
- syntax: "key.(not.)op.value",
173
- keys: t.length === 0 ? "*" : t,
174
- operators: v
175
- }
176
- });
177
- const [, o, h, d] = c;
178
- return {
179
- type: "condition",
180
- key: e(o),
181
- op: h,
182
- value: l.defined(d)
183
- };
184
- }
185
- function L(s, t = [], e = (a) => a, r = O) {
186
- return s.length === 0 ? [] : s.split(r).map((a) => y(a, t, e));
187
- }
188
- function M(s, t = "/") {
97
+ function L(s, t = "/") {
189
98
  const e = s.lastIndexOf(t);
190
99
  return e === -1 ? ["", s] : [s.substring(0, e), s.substring(e + 1)];
191
100
  }
192
- function A(s) {
101
+ function F(s) {
193
102
  return Array.isArray(s) ? s : [s];
194
103
  }
195
- function z(s, t) {
104
+ function M(s, t) {
196
105
  return s.reduce((e, r) => {
197
- const a = t(r);
198
- return (e[a] ??= []).push(r), e;
106
+ const n = t(r);
107
+ return (e[n] ??= []).push(r), e;
199
108
  }, {});
200
109
  }
201
- function T(s, t) {
110
+ function A(s, t) {
202
111
  const e = s.findIndex(t);
203
112
  return e !== -1 && s.splice(e, 1), s;
204
113
  }
205
- function W(s) {
114
+ function z(s) {
206
115
  return Object.entries(s);
207
116
  }
208
- const w = {
209
- /**
210
- * Query extension for PostgREST queries.
211
- * Supports typesafe column selection and counting.
212
- * This extension can be used with any PostgREST query builder.
213
- *
214
- * @example
215
- * const table = supabase.schema('public').from('my_table');
216
- * const {data, error} = await postgrestExtensions.query.enable(table)
217
- * .select(['id', 'name'])
218
- * .then(({data}) => console.log(data)); // [{ id: 1, name: 'John' }, ...]
219
- */
220
- query: {
221
- enable: (s) => Object.assign(
222
- s,
223
- {
224
- /**
225
- * Selects columns from the relation.
226
- *
227
- * @param columns The array of column names to select, or '*' to select all columns.
228
- * @param options The options for the selection, such as count.
229
- * @returns The PostgREST filter builder with selection applied and filter extension enabled.
230
- */
231
- select: (t, e) => w.filter.enable(
232
- s.select(
233
- A(t).join(","),
234
- e
235
- )
236
- ),
237
- /**
238
- * Counts the number of rows in the relation.
239
- * Does not select any columns, only counts the rows.
240
- *
241
- * @param method The counting method to use, defaults to 'exact'.
242
- * @returns The PostgREST filter builder with counting applied and filter extension enabled.
243
- */
244
- count: (t = "exact") => w.filter.enable(
245
- s.select("*", { count: t, head: !0 })
246
- ),
247
- /**
248
- * Deletes rows from the relation.
249
- * Returns a filter builder for further filtering before deletion.
250
- *
251
- * @returns The PostgREST filter builder with delete applied and filter extension enabled.
252
- */
253
- delete: () => w.filter.enable(
254
- s.delete()
255
- )
256
- }
257
- )
258
- },
259
- /**
260
- * Filter extension for PostgREST queries.
261
- * Supports applying filters, pagination and collecting results.
262
- * This extension can be used with any PostgREST filter builder.
263
- *
264
- * @example
265
- * const selection = supabase.schema('public').from('my_table').select('*', { count: 'exact' });
266
- * const {data, error} = await postgrestExtensions.filter.enable(selection)
267
- * .filter({ key: 'name', op: 'eq', value: 'John' })
268
- * .paginate(1, 10)
269
- * .collect();
270
- */
271
- filter: {
272
- enable: (s, t = {}) => Object.assign(
273
- s,
274
- {
275
- /**
276
- * Applies a filter to the query.
277
- * A filter is defined as an AST of filter nodes including conditions and logical operators.
278
- * @param node The filter to apply.
279
- */
280
- filter: (e) => w.filter.enable(
281
- (() => {
282
- function r(a, n) {
283
- if (n.type === "logical") {
284
- const i = D(n.args, (c) => c, ",");
285
- return n.op === "or" ? a.or(i) : n.op === "not.or" ? a.or(i, { referencedTable: "not" }) : r(a, {
286
- type: "logical",
287
- op: n.op === "and" ? "not.or" : "or",
288
- args: n.args.map(N)
289
- });
290
- }
291
- return a.filter(n.key, n.op, n.value);
292
- }
293
- return r(s, e);
294
- })(),
295
- t
296
- ),
297
- /**
298
- * Limits the range of results to a specific page given a page index and limit.
299
- * @param page The page index (0-based).
300
- * @param limit The number of items per page.
301
- * @param count Optional count of total items, if known.
302
- * If provided, it will be used to check if the pagination range is valid and resolve to an empty range if not.
303
- */
304
- paginate: (e, r, a) => w.filter.enable(
305
- (() => {
306
- l(e >= 0, "Page index must be ≥ 0"), l(r >= 0, "Page limit must be ≥ 0");
307
- const n = e * r, i = n + r - 1;
308
- if (a !== void 0) {
309
- if (n >= a)
310
- return s.limit(0);
311
- if (i >= a)
312
- return s.range(n, a - 1);
313
- }
314
- return s.range(n, i);
315
- })(),
316
- {
317
- ...t,
318
- pagination: {
319
- page: e,
320
- limit: r,
321
- count: a
322
- }
323
- }
324
- ),
325
- /**
326
- * Collects the results of a pagination query.
327
- * **Note:** For collect to work, paginate() must be called before collect() and the selection must include a `count`.
328
- * @returns The paginated list of queried items.
329
- */
330
- collect: () => s.throwOnError().then((e) => {
331
- const { data: r, count: a } = e, { page: n, limit: i, ...c } = l.defined(t.pagination, "Pagination context is required for collect(). Make sure to call paginate() before collect()"), o = a ?? c.count;
332
- return l(i > 0, "Page limit must be > 0"), l(Array.isArray(r), "Data must be an array for pagination, make sure to select multiple rows in query"), l(o !== void 0, "Row count is required for pagination, make sure to count in query or pass `count` in paginate()"), {
333
- items: r,
334
- totalItems: o,
335
- page: n,
336
- totalPages: Math.ceil(o / i),
337
- limit: i
338
- };
339
- })
340
- }
341
- )
342
- }
343
- };
344
- class F {
117
+ class v {
345
118
  database;
346
119
  /**
347
120
  * The name of the schema containing the view.
@@ -359,7 +132,7 @@ class F {
359
132
  this.database = t, this.schema = e, this.relation = r;
360
133
  }
361
134
  recordNotFoundError(t) {
362
- return new _(`Record with id ${t} not found in ${this.schema}.${this.relation}`, {
135
+ return new N(`Record with id ${t} not found in ${this.schema}.${this.relation}`, {
363
136
  schema: this.schema,
364
137
  relation: this.relation,
365
138
  id: t
@@ -372,8 +145,7 @@ class F {
372
145
  * const { data, error } = await dataService.query.select('*');
373
146
  */
374
147
  get query() {
375
- const t = this.database.schema(this.schema).from(this.relation);
376
- return w.query.enable(t);
148
+ return this.database.schema(this.schema).from(this.relation);
377
149
  }
378
150
  /**
379
151
  * Performs a fuzzy search on the specified column of the relation.
@@ -384,17 +156,17 @@ class F {
384
156
  column: t,
385
157
  searchTerm: e = "",
386
158
  minSimilarity: r = 0,
387
- limit: a = 64
159
+ limit: n = 64
388
160
  }) {
389
- const { data: n } = await this.database.schema("core").rpc("fuzzy_search", {
161
+ const { data: i } = await this.database.schema("core").rpc("fuzzy_search", {
390
162
  relation: this.relation,
391
163
  schema_name: this.schema,
392
164
  column_name: t,
393
165
  search_term: e,
394
166
  min_similarity: r,
395
- limit_results: a
167
+ limit_results: n
396
168
  }).throwOnError();
397
- return n;
169
+ return i;
398
170
  }
399
171
  /**
400
172
  * List all rows in the relation.
@@ -473,11 +245,11 @@ class F {
473
245
  onConflict: e,
474
246
  ...r
475
247
  } = {}) {
476
- const { data: a } = await this.query.upsert(t, {
477
- onConflict: e?.join(","),
248
+ const { data: n } = await this.query.upsert(t, {
249
+ onConflict: e !== void 0 ? F(e).join(",") : void 0,
478
250
  ...r
479
251
  }).select().single().throwOnError();
480
- return a;
252
+ return n;
481
253
  }
482
254
  /**
483
255
  * Updates an existing row in the relation by its ID.
@@ -492,7 +264,7 @@ class F {
492
264
  return r;
493
265
  }
494
266
  }
495
- class C extends F {
267
+ class B extends v {
496
268
  constructor({
497
269
  database: t,
498
270
  schema: e,
@@ -505,7 +277,7 @@ class C extends F {
505
277
  });
506
278
  }
507
279
  }
508
- class U extends F {
280
+ class C extends v {
509
281
  constructor({
510
282
  database: t,
511
283
  schema: e,
@@ -518,43 +290,265 @@ class U extends F {
518
290
  });
519
291
  }
520
292
  }
521
- function Y(s) {
293
+ function X(s) {
522
294
  if (s.error)
523
295
  throw s.error;
524
296
  return l(s.count !== null, "Response does not contain a count. Make sure to set the `count` option in the request."), s;
525
297
  }
526
- class B {
298
+ const O = ["eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "match", "imatch", "in", "is", "isdistinct", "fts", "plfts", "phfts", "wfts", "cs", "cd", "ov", "sl", "sr", "nxr", "nxl", "adj"], Y = ["and", "or"], K = ",", q = "~", tt = (s) => (t = {}) => {
299
+ const e = (n) => t[n] ?? n, r = Object.keys(s.shape);
300
+ return f.string().transform((n, i) => {
301
+ try {
302
+ return W(n, r, e);
303
+ } catch (a) {
304
+ return i.addIssue({
305
+ code: "custom",
306
+ input: n,
307
+ message: a instanceof Error ? a.message : void 0,
308
+ params: a instanceof S ? {
309
+ expression: a.expression,
310
+ format: a.format
311
+ } : void 0
312
+ }), [];
313
+ }
314
+ });
315
+ };
316
+ function T(s) {
317
+ return s.startsWith("not.") ? s.slice(4) : `not.${s}`;
318
+ }
319
+ function et(s) {
320
+ return {
321
+ ...s,
322
+ op: T(s.op)
323
+ };
324
+ }
325
+ function I(s, t = (e) => e) {
326
+ if (s.type === "logical") {
327
+ const e = s.args.map((r) => I(r, t));
328
+ return `${s.op}(${e})`;
329
+ }
330
+ return `${t(s.key)}.${s.op}.${s.value}`;
331
+ }
332
+ function rt(s, t = (r) => r, e = q) {
333
+ return s.map((r) => I(r, t)).join(e);
334
+ }
335
+ function k(s, t = [], e = (r) => r) {
336
+ function r(u) {
337
+ const g = [];
338
+ let b = 0, w = "", y = !1;
339
+ for (const p of u)
340
+ p === '"' ? (y = !y, w += p) : p === "(" && !y ? (b++, w += p) : p === ")" && !y ? (b--, w += p) : p === "," && b === 0 && !y ? (g.push(w.trim()), w = "") : w += p;
341
+ return g;
342
+ }
343
+ if (s.endsWith(")")) {
344
+ if (s.startsWith("and("))
345
+ return {
346
+ type: "logical",
347
+ op: "and",
348
+ args: r(s.slice(4, -1)).map((u) => k(u, t, e))
349
+ };
350
+ if (s.startsWith("or("))
351
+ return {
352
+ type: "logical",
353
+ op: "or",
354
+ args: r(s.slice(3, -1)).map((u) => k(u, t, e))
355
+ };
356
+ if (s.startsWith("not.and("))
357
+ return {
358
+ type: "logical",
359
+ op: "not.and",
360
+ args: r(s.slice(8, -1)).map((u) => k(u, t, e))
361
+ };
362
+ if (s.startsWith("not.or("))
363
+ return {
364
+ type: "logical",
365
+ op: "not.or",
366
+ args: r(s.slice(7, -1)).map((u) => k(u, t, e))
367
+ };
368
+ }
369
+ const i = `^(${t.length === 0 ? "[a-zA-Z_][a-zA-Z0-9_]*" : t.join("|")})\\.((?:not\\.)?(?:${O.join("|")}))\\.(.+)$`, c = new RegExp(i).exec(s);
370
+ if (!c)
371
+ throw new S(`Invalid filter expression '${s}'`, {
372
+ expression: s,
373
+ format: {
374
+ syntax: "key.(not.)op.value",
375
+ keys: t.length === 0 ? "*" : t,
376
+ operators: O
377
+ }
378
+ });
379
+ const [, o, d, m] = c;
380
+ return {
381
+ type: "condition",
382
+ key: e(o),
383
+ op: d,
384
+ value: l.defined(m)
385
+ };
386
+ }
387
+ function W(s, t = [], e = (n) => n, r = q) {
388
+ return s.length === 0 ? [] : s.split(r).map((n) => k(n, t, e));
389
+ }
390
+ class h extends $.PostgrestFilterBuilder {
391
+ pagination;
392
+ constructor(t) {
393
+ super(t);
394
+ }
395
+ select(t = "*") {
396
+ const e = super.select(
397
+ F(t).join(",")
398
+ );
399
+ return new h(e);
400
+ }
401
+ /**
402
+ * Applies a filter to the query.
403
+ * A filter is defined as an AST of filter nodes including conditions and logical operators.
404
+ * @param filter The filter to apply.
405
+ */
406
+ where(t) {
407
+ if (t.type === "logical") {
408
+ const e = t.args.map((r) => I(r)).join(",");
409
+ this.url.searchParams.append(t.op, `(${e})`);
410
+ } else
411
+ this.url.searchParams.append(t.key, `${t.op}.${t.value}`);
412
+ return this;
413
+ }
414
+ /**
415
+ * Limits the range of results to a specific page given a page index and limit.
416
+ * @param page The page index (0-based).
417
+ * @param limit The number of items per page.
418
+ * @param count Optional count of total items, if known.
419
+ * If provided, it will be used to check if the pagination range is valid and resolve to an empty range if not.
420
+ */
421
+ paginate(t, e, r) {
422
+ l(t >= 0, "Page index must be ≥ 0"), l(e >= 0, "Page limit must be ≥ 0");
423
+ const n = t * e, i = n + e - 1;
424
+ if (r !== void 0) {
425
+ if (n >= r)
426
+ return this.limit(0);
427
+ if (i >= r)
428
+ return this.range(n, r - 1);
429
+ }
430
+ return this.pagination = {
431
+ ...this.pagination,
432
+ page: t,
433
+ limit: e,
434
+ count: r
435
+ }, this.range(n, i);
436
+ }
437
+ /**
438
+ * Collects the results of a pagination query.
439
+ * **Note:** For collect to work, paginate() must be called before collect() and the selection must include a `count`.
440
+ * @returns The paginated list of queried items.
441
+ */
442
+ collect() {
443
+ return this.then(({ data: t, count: e, error: r, ...n }) => {
444
+ if (r)
445
+ return { data: t, count: e, error: r, ...n };
446
+ const { page: i, limit: a, ...c } = l.defined(this.pagination, "Pagination is required for collect(). Make sure to call paginate() before collect()"), o = e ?? c.count;
447
+ return l(a > 0, "Page limit must be > 0"), l(Array.isArray(t), "Data must be an array for pagination, make sure to select multiple rows in query"), l(o !== void 0, "Row count is required for pagination, make sure to count in query or pass `count` in paginate()"), {
448
+ data: {
449
+ items: t,
450
+ totalItems: o,
451
+ page: i,
452
+ totalPages: Math.ceil(o / a),
453
+ limit: a
454
+ },
455
+ error: r,
456
+ count: e,
457
+ ...n
458
+ };
459
+ });
460
+ }
461
+ }
462
+ class U extends $.PostgrestQueryBuilder {
463
+ constructor(t) {
464
+ super(t.url, t);
465
+ }
466
+ select(t = "*", e) {
467
+ const r = super.select(
468
+ F(t).join(","),
469
+ e
470
+ );
471
+ return new h(r);
472
+ }
473
+ /**
474
+ * Counts the number of rows in the relation.
475
+ * Does not select any columns, only counts the rows.
476
+ *
477
+ * @param method The counting method to use, defaults to 'exact'.
478
+ * @returns The PostgREST filter builder with counting applied and filter extension enabled.
479
+ */
480
+ count(t = "exact") {
481
+ const e = this.select("*", { count: t, head: !0 });
482
+ return new h(e);
483
+ }
484
+ insert(t, e) {
485
+ const r = super.insert(t, e);
486
+ return new h(r);
487
+ }
488
+ upsert(t, { onConflict: e, ...r } = {}) {
489
+ const n = super.upsert(t, {
490
+ onConflict: F(e).join(","),
491
+ ...r
492
+ });
493
+ return new h(n);
494
+ }
495
+ // @ts-expect-error the signatures are compatible but typescript can't verify it
496
+ update(t, e) {
497
+ const r = super.update(t, e);
498
+ return new h(r);
499
+ }
500
+ delete() {
501
+ const t = super.delete();
502
+ return new h(t);
503
+ }
504
+ }
505
+ class Q {
506
+ client;
507
+ constructor(t) {
508
+ this.client = t;
509
+ }
510
+ from(t) {
511
+ const e = this.client.from(t);
512
+ return new U(e);
513
+ }
514
+ rpc(t, e, r) {
515
+ const n = this.client.rpc(t, e, r);
516
+ return new h(n);
517
+ }
518
+ }
519
+ class R {
527
520
  supabase;
528
521
  constructor({ supabase: t }) {
529
522
  this.supabase = t;
530
523
  }
531
524
  schema(t) {
532
- return this.supabase.schema(t);
525
+ const e = this.supabase.schema(t);
526
+ return new Q(e);
533
527
  }
534
528
  relation(t, e) {
535
- return new F({
529
+ return new v({
536
530
  database: this,
537
531
  schema: t,
538
532
  relation: e
539
533
  });
540
534
  }
541
535
  table(t, e) {
542
- return new C({
536
+ return new B({
543
537
  database: this,
544
538
  schema: t,
545
539
  table: e
546
540
  });
547
541
  }
548
542
  view(t, e) {
549
- return new U({
543
+ return new C({
550
544
  database: this,
551
545
  schema: t,
552
546
  view: e
553
547
  });
554
548
  }
555
549
  }
556
- const K = B;
557
- class tt {
550
+ const st = R;
551
+ class nt {
558
552
  preprocesses = [];
559
553
  storage;
560
554
  constructor({
@@ -572,17 +566,17 @@ class tt {
572
566
  */
573
567
  async getOutdatedEmbeddings(t) {
574
568
  const e = [];
575
- let r = !0, a;
569
+ let r = !0, n;
576
570
  for (; r; ) {
577
- const { objects: n, ...i } = await this.storage.getFiles(t, { cursor: a }), c = await Promise.all(
578
- n.map(async (o) => {
579
- const h = new Date(o.updated_at), d = await this.storage.getFileStorageLocation({ fileId: o.id }), u = await this.getEmbeddings(d);
580
- return u.length === 0 || u.some((p) => p.createdAt < h);
571
+ const { objects: i, ...a } = await this.storage.getFiles(t, { cursor: n }), c = await Promise.all(
572
+ i.map(async (o) => {
573
+ const d = new Date(o.updated_at), m = await this.storage.getFileStorageLocation({ fileId: o.id }), u = await this.getEmbeddings(m);
574
+ return u.length === 0 || u.some((g) => g.createdAt < d);
581
575
  })
582
576
  );
583
577
  e.push(
584
- ...n.filter((o, h) => c[h]).map(({ id: o }) => ({ fileId: o }))
585
- ), { hasNext: r, nextCursor: a } = i;
578
+ ...i.filter((o, d) => c[d]).map(({ id: o }) => ({ fileId: o }))
579
+ ), { hasNext: r, nextCursor: n } = a;
586
580
  }
587
581
  return e;
588
582
  }
@@ -595,50 +589,50 @@ class tt {
595
589
  return this.preprocesses.push(t), this;
596
590
  }
597
591
  removePreprocessingStep(t) {
598
- return T(this.preprocesses, (e) => e.name === t), this;
592
+ return A(this.preprocesses, (e) => e.name === t), this;
599
593
  }
600
594
  async get(t) {
601
595
  const e = await this.storage.getFileStorageLocation(t);
602
596
  return this.getEmbeddings(e);
603
597
  }
604
598
  async ingest(t, e) {
605
- const { file: r, ...a } = await this.storage.downloadFile(t), n = S.parse(r.type);
606
- if (n.type !== "text")
607
- throw new I(`Unsupported file type: ${n}. Only text files can be embedded.`);
608
- await this.deleteEmbeddings(a);
609
- const i = {
599
+ const { file: r, ...n } = await this.storage.downloadFile(t), i = _.parse(r.type);
600
+ if (i.type !== "text")
601
+ throw new P(`Unsupported file type: ${i}. Only text files can be embedded.`);
602
+ await this.deleteEmbeddings(n);
603
+ const a = {
610
604
  name: r.name,
611
605
  type: r.type,
612
606
  size: r.size,
613
- ...a,
614
- ...typeof e == "function" ? e(r, a) : e
615
- }, c = this.preprocess(await r.text(), i);
616
- return this.createEmbeddings(a, c, i);
607
+ ...n,
608
+ ...typeof e == "function" ? e(r, n) : e
609
+ }, c = this.preprocess(await r.text(), a);
610
+ return this.createEmbeddings(n, c, a);
617
611
  }
618
612
  async synchronize(t, e) {
619
613
  const r = await this.getOutdatedEmbeddings(t);
620
614
  return (await Promise.all(
621
615
  r.map(
622
- async (n) => this.ingest(n, e).then(() => ({
623
- file: n,
616
+ async (i) => this.ingest(i, e).then(() => ({
617
+ file: i,
624
618
  success: !0,
625
619
  error: null
626
- })).catch((i) => i instanceof I ? null : {
627
- file: n,
628
- error: i,
620
+ })).catch((a) => a instanceof P ? null : {
621
+ file: i,
622
+ error: a,
629
623
  success: !1
630
624
  })
631
625
  )
632
- )).filter((n) => n !== null);
626
+ )).filter((i) => i !== null);
633
627
  }
634
628
  }
635
- const et = {
629
+ const it = {
636
630
  removeImagesFromMarkdown: {
637
631
  name: "removeImagesFromMarkdown",
638
632
  run(s, t) {
639
633
  if (t.type === "text/markdown") {
640
634
  const e = /!\[([^\]]*)\]\([^)]*\)/g;
641
- return s.replace(e, (r, a) => `![${a}]()`);
635
+ return s.replace(e, (r, n) => `![${n}]()`);
642
636
  }
643
637
  return s;
644
638
  }
@@ -648,13 +642,13 @@ const et = {
648
642
  run(s, t) {
649
643
  if (t.type === "text/markdown") {
650
644
  const e = /\[([^\]]*)\]\([^)]*\)/g;
651
- return s.replace(e, (r, a) => `[${a}]()`);
645
+ return s.replace(e, (r, n) => `[${n}]()`);
652
646
  }
653
647
  return s;
654
648
  }
655
649
  }
656
650
  };
657
- class rt {
651
+ class at {
658
652
  client;
659
653
  database;
660
654
  constructor({
@@ -667,38 +661,38 @@ class rt {
667
661
  return this.database.table("storage", "objects");
668
662
  }
669
663
  async getFileObject(t, e) {
670
- const { data: r, error: a } = await this.client.from(t).info(e);
671
- if (a)
672
- throw a;
664
+ const { data: r, error: n } = await this.client.from(t).info(e);
665
+ if (n)
666
+ throw n;
673
667
  return r;
674
668
  }
675
669
  async getFiles(t, e) {
676
- const { data: r, error: a } = await this.client.from(t).listV2(e);
677
- if (a)
678
- throw a;
670
+ const { data: r, error: n } = await this.client.from(t).listV2(e);
671
+ if (n)
672
+ throw n;
679
673
  return r;
680
674
  }
681
675
  async getFileStorageLocation(t) {
682
676
  if ("fileId" in t) {
683
- const { fileId: n } = t, i = await this.files.get(n, ["bucket_id", "path_tokens"]);
684
- if (!i)
685
- throw new E(`File with ID ${n} not found`, { fileId: n });
677
+ const { fileId: i } = t, a = await this.files.get(i, ["bucket_id", "path_tokens"]);
678
+ if (!a)
679
+ throw new x(`File with ID ${i} not found`, { fileId: i });
686
680
  return {
687
- fileId: n,
688
- bucket: l.notNull(i.bucket_id, "bucket_id must not be null"),
689
- path: l.notNull(i.path_tokens, "path_tokens must not be null").join("/")
681
+ fileId: i,
682
+ bucket: l.notNull(a.bucket_id, "bucket_id must not be null"),
683
+ path: l.notNull(a.path_tokens, "path_tokens must not be null").join("/")
690
684
  };
691
685
  }
692
- const { bucket: e, path: r } = t, { id: a } = await this.getFileObject(e, r);
693
- return { fileId: a, bucket: e, path: r };
686
+ const { bucket: e, path: r } = t, { id: n } = await this.getFileObject(e, r);
687
+ return { fileId: n, bucket: e, path: r };
694
688
  }
695
689
  async getFileInfo(t) {
696
- const { fileId: e, bucket: r, path: a } = await this.getFileStorageLocation(t), { id: n, bucketId: i, metadata: c, ...o } = await this.getFileObject(r, a);
697
- return l(n === e, "file ID from storage client must match file ID from database"), l(i === r, "bucketId from storage client must match bucket from database"), {
690
+ const { fileId: e, bucket: r, path: n } = await this.getFileStorageLocation(t), { id: i, bucketId: a, metadata: c, ...o } = await this.getFileObject(r, n);
691
+ return l(i === e, "file ID from storage client must match file ID from database"), l(a === r, "bucketId from storage client must match bucket from database"), {
698
692
  ...o,
699
693
  fileId: e,
700
694
  bucket: r,
701
- path: a,
695
+ path: n,
702
696
  metadata: c,
703
697
  properties: c ? {
704
698
  type: c.mimetype,
@@ -707,104 +701,106 @@ class rt {
707
701
  };
708
702
  }
709
703
  async getPublicURL(t, e) {
710
- const { bucket: r, path: a } = await this.getFileStorageLocation(t), { data: { publicUrl: n } } = this.client.from(r).getPublicUrl(a, e);
711
- return n;
704
+ const { bucket: r, path: n } = await this.getFileStorageLocation(t), { data: { publicUrl: i } } = this.client.from(r).getPublicUrl(n, e);
705
+ return i;
712
706
  }
713
707
  async existsFile(t) {
714
- const { bucket: e, path: r } = await this.getFileStorageLocation(t), { data: a, error: n } = await this.client.from(e).exists(r);
715
- if (n)
716
- throw n;
717
- return a;
708
+ const { bucket: e, path: r } = await this.getFileStorageLocation(t), { data: n, error: i } = await this.client.from(e).exists(r);
709
+ if (i)
710
+ throw i;
711
+ return n;
718
712
  }
719
713
  async assertExistsFile(t) {
720
- const { bucket: e, path: r } = await this.getFileStorageLocation(t), { data: a, error: n } = await this.client.from(e).exists(r);
721
- if (n)
722
- throw n;
723
- if (!a)
724
- throw new E(`File not found in bucket '${e}' at path '${r}'`, { bucket: e, path: r });
714
+ const { bucket: e, path: r } = await this.getFileStorageLocation(t), { data: n, error: i } = await this.client.from(e).exists(r);
715
+ if (i)
716
+ throw i;
717
+ if (!n)
718
+ throw new x(`File not found in bucket '${e}' at path '${r}'`, { bucket: e, path: r });
725
719
  }
726
- async uploadFile(t, { bucket: e, path: r }, { overwriteExisting: a = !1 } = {}) {
727
- const { data: n, error: i } = await this.client.from(e).upload(
720
+ async uploadFile(t, { bucket: e, path: r }, { overwriteExisting: n = !1 } = {}) {
721
+ const { data: i, error: a } = await this.client.from(e).upload(
728
722
  `${r}/${t.name}`,
729
723
  t,
730
724
  {
731
- upsert: a
725
+ upsert: n
732
726
  }
733
727
  );
734
- if (i)
735
- throw i;
728
+ if (a)
729
+ throw a;
736
730
  return {
737
- fileId: n.id,
731
+ fileId: i.id,
738
732
  bucket: e,
739
- path: n.path
733
+ path: i.path
740
734
  };
741
735
  }
742
736
  async downloadFile(t) {
743
- const { fileId: e, bucket: r, path: a, properties: n } = await this.getFileInfo(t), { data: i, error: c } = await this.client.from(r).download(a);
737
+ const { fileId: e, bucket: r, path: n, properties: i } = await this.getFileInfo(t), { data: a, error: c } = await this.client.from(r).download(n);
744
738
  if (c)
745
739
  throw c;
746
- const [, o] = M(a);
740
+ const [, o] = L(n);
747
741
  return {
748
742
  fileId: e,
749
743
  bucket: r,
750
- path: a,
751
- file: new File([i], o, n)
744
+ path: n,
745
+ file: new File([a], o, i)
752
746
  };
753
747
  }
754
748
  async deleteFiles(t) {
755
- const e = t.filter((o) => "fileId" in o).map((o) => o.fileId), a = (await this.files.query.select(["bucket_id", "path_tokens"]).containedBy("id", e).throwOnError()).data.map(({ bucket_id: o, path_tokens: h }) => ({
749
+ const e = t.filter((o) => "fileId" in o).map((o) => o.fileId), n = (await this.files.query.select(["bucket_id", "path_tokens"]).containedBy("id", e).throwOnError()).data.map(({ bucket_id: o, path_tokens: d }) => ({
756
750
  bucket: l.notNull(o, "bucket_id must not be null"),
757
- path: l.notNull(h, "path_tokens must not be null").join("/")
758
- })), n = t.filter((o) => "path" in o).concat(a), i = W(
759
- z(n, (o) => o.bucket)
760
- ).map(([o, h]) => ({
751
+ path: l.notNull(d, "path_tokens must not be null").join("/")
752
+ })), i = t.filter((o) => "path" in o).concat(n), a = z(
753
+ M(i, (o) => o.bucket)
754
+ ).map(([o, d]) => ({
761
755
  bucket: o,
762
- paths: h.map((d) => d.path)
756
+ paths: d.map((m) => m.path)
763
757
  }));
764
- return (await Promise.all(i.map(
765
- async ({ bucket: o, paths: h }) => this.client.from(o).remove(h).then(({ data: d, error: u }) => {
758
+ return (await Promise.all(a.map(
759
+ async ({ bucket: o, paths: d }) => this.client.from(o).remove(d).then(({ data: m, error: u }) => {
766
760
  if (u)
767
761
  throw u;
768
- return d.map((p, b) => ({
769
- fileId: l.notNull(p.id, "file id must not be null"),
762
+ return m.map((g, b) => ({
763
+ fileId: l.notNull(g.id, "file id must not be null"),
770
764
  bucket: o,
771
- path: l.defined(h[b], "path must not be null")
765
+ path: l.defined(d[b], "path must not be null")
772
766
  }));
773
767
  })
774
768
  ))).flat();
775
769
  }
776
770
  }
777
771
  export {
778
- F as DataService,
779
- K as DatabaseService,
780
- tt as EmbeddingService,
781
- E as FileNotFoundError,
782
- X as Filter,
783
- O as FilterChainSeparator,
784
- v as FilterOp,
785
- J as LogicalOp,
786
- Q as LogicalOpSeparator,
787
- x as ParseError,
788
- $ as PostgrestErrorInterface,
789
- _ as RecordNotFoundError,
790
- rt as StorageService,
791
- C as TableDataService,
792
- k as TracedError,
793
- I as UnsupportedMimeError,
794
- U as ViewDataService,
795
- Y as assertCounted,
796
- A as coerceArray,
797
- D as encodeFilter,
798
- q as encodeFilterNode,
799
- W as entries,
800
- z as groupBy,
801
- H as isDatabaseApiError,
802
- N as negateFilterNode,
803
- j as negateOp,
804
- y as parseFilterExpression,
805
- L as parseFilterExpressionChain,
806
- w as postgrestExtensions,
807
- et as preprocessingSteps,
808
- T as removeElement,
809
- M as splitPath
772
+ v as DataService,
773
+ st as DatabaseService,
774
+ nt as EmbeddingService,
775
+ x as FileNotFoundError,
776
+ tt as Filter,
777
+ q as FilterChainSeparator,
778
+ O as FilterOp,
779
+ Y as LogicalOp,
780
+ K as LogicalOpSeparator,
781
+ S as ParseError,
782
+ Q as PostgrestClient,
783
+ D as PostgrestErrorInterface,
784
+ h as PostgrestFilterBuilder,
785
+ U as PostgrestQueryBuilder,
786
+ N as RecordNotFoundError,
787
+ at as StorageService,
788
+ B as TableDataService,
789
+ E as TracedError,
790
+ P as UnsupportedMimeError,
791
+ C as ViewDataService,
792
+ X as assertCounted,
793
+ F as coerceArray,
794
+ rt as encodeFilter,
795
+ I as encodeFilterNode,
796
+ z as entries,
797
+ M as groupBy,
798
+ J as isDatabaseApiError,
799
+ et as negateFilterNode,
800
+ T as negateOp,
801
+ k as parseFilterExpression,
802
+ W as parseFilterExpressionChain,
803
+ it as preprocessingSteps,
804
+ A as removeElement,
805
+ L as splitPath
810
806
  };