@freehour/supabase-core 1.2.1 → 1.4.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,264 +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
- * .selectColumns(['id', 'name'])
218
- * .then(({data}) => console.log(data)); // [{ id: 1, name: 'John' }, ...]
219
- */
220
- query: {
221
- enable: (s) => Object.assign(s, {
222
- /**
223
- * Selects columns from the relation.
224
- *
225
- * @param columns The array of column names to select, or '*' to select all columns.
226
- * @param options The options for the selection, such as count.
227
- * @returns The PostgREST filter builder with selection applied and filter extension enabled.
228
- */
229
- select: (t, e) => w.filter.enable(
230
- s.select(
231
- A(t).join(","),
232
- e
233
- )
234
- ),
235
- /**
236
- * Counts the number of rows in the relation.
237
- * Does not select any columns, only counts the rows.
238
- *
239
- * @param method The counting method to use, defaults to 'exact'.
240
- * @returns The PostgREST filter builder with counting applied and filter extension enabled.
241
- */
242
- count: (t = "exact") => w.filter.enable(
243
- s.select("*", { count: t, head: !0 })
244
- ),
245
- /**
246
- * Deletes rows from the relation.
247
- * Returns a filter builder for further filtering before deletion.
248
- *
249
- * @returns The PostgREST filter builder with delete applied and filter extension enabled.
250
- */
251
- delete: () => w.filter.enable(
252
- s.delete()
253
- )
254
- })
255
- },
256
- /**
257
- * Filter extension for PostgREST queries.
258
- * Supports applying filters, pagination and collecting results.
259
- * This extension can be used with any PostgREST filter builder.
260
- *
261
- * @example
262
- * const selection = supabase.schema('public').from('my_table').select('*', { count: 'exact' });
263
- * const {data, error} = await postgrestExtensions.filter.enable(selection)
264
- * .apply({ key: 'name', op: 'eq', value: 'John' })
265
- * .paginate(1, 10)
266
- * .collect();
267
- */
268
- filter: {
269
- enable: (s, t = {}) => Object.assign(s, {
270
- /**
271
- * Applies a filter to the query.
272
- * A filter is defined as an array of AST filter nodes including conditions and logical operators.
273
- * @param filter The filter to apply.
274
- */
275
- apply: (e) => w.filter.enable(
276
- (() => {
277
- function r(a, n) {
278
- if (n.type === "logical") {
279
- const i = D(n.args, (c) => c, ",");
280
- return n.op === "or" ? a.or(i) : n.op === "not.or" ? a.or(i, { referencedTable: "not" }) : r(a, {
281
- type: "logical",
282
- op: n.op === "and" ? "not.or" : "or",
283
- args: n.args.map(N)
284
- });
285
- }
286
- return a.filter(n.key, n.op, n.value);
287
- }
288
- return e.reduce(r, s);
289
- })(),
290
- t
291
- ),
292
- /**
293
- * Limits the range of results to a specific page given a page index and limit.
294
- * @param page The page index (0-based).
295
- * @param limit The number of items per page.
296
- * @param count Optional count of total items, if known.
297
- * If provided, it will be used to check if the pagination range is valid and resolve to an empty range if not.
298
- */
299
- paginate: (e, r, a) => w.filter.enable(
300
- (() => {
301
- l(e >= 0, "Page index must be ≥ 0"), l(r >= 0, "Page limit must be ≥ 0");
302
- const n = e * r, i = n + r - 1;
303
- if (a !== void 0) {
304
- if (n >= a)
305
- return s.limit(0);
306
- if (i >= a)
307
- return s.range(n, a - 1);
308
- }
309
- return s.range(n, i);
310
- })(),
311
- {
312
- ...t,
313
- pagination: {
314
- page: e,
315
- limit: r,
316
- count: a
317
- }
318
- }
319
- ),
320
- /**
321
- * Collects the results of a pagination query.
322
- * **Note:** For collect to work, paginate() must be called before collect() and the selection must include a `count`.
323
- * @returns The paginated list of queried items.
324
- */
325
- collect: () => s.throwOnError().then((e) => {
326
- 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;
327
- 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()"), {
328
- items: r,
329
- totalItems: o,
330
- page: n,
331
- totalPages: Math.ceil(o / i),
332
- limit: i
333
- };
334
- })
335
- })
336
- }
337
- };
338
- class F {
117
+ class v {
339
118
  database;
340
119
  /**
341
120
  * The name of the schema containing the view.
@@ -353,7 +132,7 @@ class F {
353
132
  this.database = t, this.schema = e, this.relation = r;
354
133
  }
355
134
  recordNotFoundError(t) {
356
- 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}`, {
357
136
  schema: this.schema,
358
137
  relation: this.relation,
359
138
  id: t
@@ -366,8 +145,7 @@ class F {
366
145
  * const { data, error } = await dataService.query.select('*');
367
146
  */
368
147
  get query() {
369
- const t = this.database.schema(this.schema).from(this.relation);
370
- return w.query.enable(t);
148
+ return this.database.schema(this.schema).from(this.relation);
371
149
  }
372
150
  /**
373
151
  * Performs a fuzzy search on the specified column of the relation.
@@ -378,17 +156,17 @@ class F {
378
156
  column: t,
379
157
  searchTerm: e = "",
380
158
  minSimilarity: r = 0,
381
- limit: a = 64
159
+ limit: n = 64
382
160
  }) {
383
- const { data: n } = await this.database.schema("core").rpc("fuzzy_search", {
161
+ const { data: i } = await this.database.schema("core").rpc("fuzzy_search", {
384
162
  relation: this.relation,
385
163
  schema_name: this.schema,
386
164
  column_name: t,
387
165
  search_term: e,
388
166
  min_similarity: r,
389
- limit_results: a
167
+ limit_results: n
390
168
  }).throwOnError();
391
- return n;
169
+ return i;
392
170
  }
393
171
  /**
394
172
  * List all rows in the relation.
@@ -467,11 +245,11 @@ class F {
467
245
  onConflict: e,
468
246
  ...r
469
247
  } = {}) {
470
- const { data: a } = await this.query.upsert(t, {
471
- onConflict: e?.join(","),
248
+ const { data: n } = await this.query.upsert(t, {
249
+ onConflict: e !== void 0 ? F(e).join(",") : void 0,
472
250
  ...r
473
251
  }).select().single().throwOnError();
474
- return a;
252
+ return n;
475
253
  }
476
254
  /**
477
255
  * Updates an existing row in the relation by its ID.
@@ -486,7 +264,7 @@ class F {
486
264
  return r;
487
265
  }
488
266
  }
489
- class C extends F {
267
+ class B extends v {
490
268
  constructor({
491
269
  database: t,
492
270
  schema: e,
@@ -499,7 +277,7 @@ class C extends F {
499
277
  });
500
278
  }
501
279
  }
502
- class U extends F {
280
+ class C extends v {
503
281
  constructor({
504
282
  database: t,
505
283
  schema: e,
@@ -512,43 +290,265 @@ class U extends F {
512
290
  });
513
291
  }
514
292
  }
515
- function Y(s) {
293
+ function X(s) {
516
294
  if (s.error)
517
295
  throw s.error;
518
296
  return l(s.count !== null, "Response does not contain a count. Make sure to set the `count` option in the request."), s;
519
297
  }
520
- 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 {
521
520
  supabase;
522
521
  constructor({ supabase: t }) {
523
522
  this.supabase = t;
524
523
  }
525
524
  schema(t) {
526
- return this.supabase.schema(t);
525
+ const e = this.supabase.schema(t);
526
+ return new Q(e);
527
527
  }
528
528
  relation(t, e) {
529
- return new F({
529
+ return new v({
530
530
  database: this,
531
531
  schema: t,
532
532
  relation: e
533
533
  });
534
534
  }
535
535
  table(t, e) {
536
- return new C({
536
+ return new B({
537
537
  database: this,
538
538
  schema: t,
539
539
  table: e
540
540
  });
541
541
  }
542
542
  view(t, e) {
543
- return new U({
543
+ return new C({
544
544
  database: this,
545
545
  schema: t,
546
546
  view: e
547
547
  });
548
548
  }
549
549
  }
550
- const K = B;
551
- class tt {
550
+ const st = R;
551
+ class nt {
552
552
  preprocesses = [];
553
553
  storage;
554
554
  constructor({
@@ -566,17 +566,17 @@ class tt {
566
566
  */
567
567
  async getOutdatedEmbeddings(t) {
568
568
  const e = [];
569
- let r = !0, a;
569
+ let r = !0, n;
570
570
  for (; r; ) {
571
- const { objects: n, ...i } = await this.storage.getFiles(t, { cursor: a }), c = await Promise.all(
572
- n.map(async (o) => {
573
- const h = new Date(o.updated_at), d = await this.storage.getFileStorageLocation({ fileId: o.id }), u = await this.getEmbeddings(d);
574
- 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);
575
575
  })
576
576
  );
577
577
  e.push(
578
- ...n.filter((o, h) => c[h]).map(({ id: o }) => ({ fileId: o }))
579
- ), { hasNext: r, nextCursor: a } = i;
578
+ ...i.filter((o, d) => c[d]).map(({ id: o }) => ({ fileId: o }))
579
+ ), { hasNext: r, nextCursor: n } = a;
580
580
  }
581
581
  return e;
582
582
  }
@@ -589,50 +589,50 @@ class tt {
589
589
  return this.preprocesses.push(t), this;
590
590
  }
591
591
  removePreprocessingStep(t) {
592
- return T(this.preprocesses, (e) => e.name === t), this;
592
+ return A(this.preprocesses, (e) => e.name === t), this;
593
593
  }
594
594
  async get(t) {
595
595
  const e = await this.storage.getFileStorageLocation(t);
596
596
  return this.getEmbeddings(e);
597
597
  }
598
598
  async ingest(t, e) {
599
- const { file: r, ...a } = await this.storage.downloadFile(t), n = S.parse(r.type);
600
- if (n.type !== "text")
601
- throw new I(`Unsupported file type: ${n}. Only text files can be embedded.`);
602
- await this.deleteEmbeddings(a);
603
- 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 = {
604
604
  name: r.name,
605
605
  type: r.type,
606
606
  size: r.size,
607
- ...a,
608
- ...typeof e == "function" ? e(r, a) : e
609
- }, c = this.preprocess(await r.text(), i);
610
- 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);
611
611
  }
612
612
  async synchronize(t, e) {
613
613
  const r = await this.getOutdatedEmbeddings(t);
614
614
  return (await Promise.all(
615
615
  r.map(
616
- async (n) => this.ingest(n, e).then(() => ({
617
- file: n,
616
+ async (i) => this.ingest(i, e).then(() => ({
617
+ file: i,
618
618
  success: !0,
619
619
  error: null
620
- })).catch((i) => i instanceof I ? null : {
621
- file: n,
622
- error: i,
620
+ })).catch((a) => a instanceof P ? null : {
621
+ file: i,
622
+ error: a,
623
623
  success: !1
624
624
  })
625
625
  )
626
- )).filter((n) => n !== null);
626
+ )).filter((i) => i !== null);
627
627
  }
628
628
  }
629
- const et = {
629
+ const it = {
630
630
  removeImagesFromMarkdown: {
631
631
  name: "removeImagesFromMarkdown",
632
632
  run(s, t) {
633
633
  if (t.type === "text/markdown") {
634
634
  const e = /!\[([^\]]*)\]\([^)]*\)/g;
635
- return s.replace(e, (r, a) => `![${a}]()`);
635
+ return s.replace(e, (r, n) => `![${n}]()`);
636
636
  }
637
637
  return s;
638
638
  }
@@ -642,13 +642,13 @@ const et = {
642
642
  run(s, t) {
643
643
  if (t.type === "text/markdown") {
644
644
  const e = /\[([^\]]*)\]\([^)]*\)/g;
645
- return s.replace(e, (r, a) => `[${a}]()`);
645
+ return s.replace(e, (r, n) => `[${n}]()`);
646
646
  }
647
647
  return s;
648
648
  }
649
649
  }
650
650
  };
651
- class rt {
651
+ class at {
652
652
  client;
653
653
  database;
654
654
  constructor({
@@ -661,38 +661,38 @@ class rt {
661
661
  return this.database.table("storage", "objects");
662
662
  }
663
663
  async getFileObject(t, e) {
664
- const { data: r, error: a } = await this.client.from(t).info(e);
665
- if (a)
666
- throw a;
664
+ const { data: r, error: n } = await this.client.from(t).info(e);
665
+ if (n)
666
+ throw n;
667
667
  return r;
668
668
  }
669
669
  async getFiles(t, e) {
670
- const { data: r, error: a } = await this.client.from(t).listV2(e);
671
- if (a)
672
- throw a;
670
+ const { data: r, error: n } = await this.client.from(t).listV2(e);
671
+ if (n)
672
+ throw n;
673
673
  return r;
674
674
  }
675
675
  async getFileStorageLocation(t) {
676
676
  if ("fileId" in t) {
677
- const { fileId: n } = t, i = await this.files.get(n, ["bucket_id", "path_tokens"]);
678
- if (!i)
679
- 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 });
680
680
  return {
681
- fileId: n,
682
- bucket: l.notNull(i.bucket_id, "bucket_id must not be null"),
683
- 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("/")
684
684
  };
685
685
  }
686
- const { bucket: e, path: r } = t, { id: a } = await this.getFileObject(e, r);
687
- 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 };
688
688
  }
689
689
  async getFileInfo(t) {
690
- const { fileId: e, bucket: r, path: a } = await this.getFileStorageLocation(t), { id: n, bucketId: i, metadata: c, ...o } = await this.getFileObject(r, a);
691
- 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"), {
692
692
  ...o,
693
693
  fileId: e,
694
694
  bucket: r,
695
- path: a,
695
+ path: n,
696
696
  metadata: c,
697
697
  properties: c ? {
698
698
  type: c.mimetype,
@@ -701,104 +701,106 @@ class rt {
701
701
  };
702
702
  }
703
703
  async getPublicURL(t, e) {
704
- const { bucket: r, path: a } = await this.getFileStorageLocation(t), { data: { publicUrl: n } } = this.client.from(r).getPublicUrl(a, e);
705
- 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;
706
706
  }
707
707
  async existsFile(t) {
708
- const { bucket: e, path: r } = await this.getFileStorageLocation(t), { data: a, error: n } = await this.client.from(e).exists(r);
709
- if (n)
710
- throw n;
711
- 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;
712
712
  }
713
713
  async assertExistsFile(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
- if (!a)
718
- 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 });
719
719
  }
720
- async uploadFile(t, { bucket: e, path: r }, { overwriteExisting: a = !1 } = {}) {
721
- 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(
722
722
  `${r}/${t.name}`,
723
723
  t,
724
724
  {
725
- upsert: a
725
+ upsert: n
726
726
  }
727
727
  );
728
- if (i)
729
- throw i;
728
+ if (a)
729
+ throw a;
730
730
  return {
731
- fileId: n.id,
731
+ fileId: i.id,
732
732
  bucket: e,
733
- path: n.path
733
+ path: i.path
734
734
  };
735
735
  }
736
736
  async downloadFile(t) {
737
- 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);
738
738
  if (c)
739
739
  throw c;
740
- const [, o] = M(a);
740
+ const [, o] = L(n);
741
741
  return {
742
742
  fileId: e,
743
743
  bucket: r,
744
- path: a,
745
- file: new File([i], o, n)
744
+ path: n,
745
+ file: new File([a], o, i)
746
746
  };
747
747
  }
748
748
  async deleteFiles(t) {
749
- 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 }) => ({
750
750
  bucket: l.notNull(o, "bucket_id must not be null"),
751
- path: l.notNull(h, "path_tokens must not be null").join("/")
752
- })), n = t.filter((o) => "path" in o).concat(a), i = W(
753
- z(n, (o) => o.bucket)
754
- ).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]) => ({
755
755
  bucket: o,
756
- paths: h.map((d) => d.path)
756
+ paths: d.map((m) => m.path)
757
757
  }));
758
- return (await Promise.all(i.map(
759
- 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 }) => {
760
760
  if (u)
761
761
  throw u;
762
- return d.map((p, b) => ({
763
- 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"),
764
764
  bucket: o,
765
- path: l.defined(h[b], "path must not be null")
765
+ path: l.defined(d[b], "path must not be null")
766
766
  }));
767
767
  })
768
768
  ))).flat();
769
769
  }
770
770
  }
771
771
  export {
772
- F as DataService,
773
- K as DatabaseService,
774
- tt as EmbeddingService,
775
- E as FileNotFoundError,
776
- X as Filter,
777
- O as FilterChainSeparator,
778
- v as FilterOp,
779
- J as LogicalOp,
780
- Q as LogicalOpSeparator,
781
- x as ParseError,
782
- $ as PostgrestErrorInterface,
783
- _ as RecordNotFoundError,
784
- rt as StorageService,
785
- C as TableDataService,
786
- k as TracedError,
787
- I as UnsupportedMimeError,
788
- U as ViewDataService,
789
- Y as assertCounted,
790
- A as coerceArray,
791
- D as encodeFilter,
792
- q as encodeFilterNode,
793
- W as entries,
794
- z as groupBy,
795
- H as isDatabaseApiError,
796
- N as negateFilterNode,
797
- j as negateOp,
798
- y as parseFilterExpression,
799
- L as parseFilterExpressionChain,
800
- w as postgrestExtensions,
801
- et as preprocessingSteps,
802
- T as removeElement,
803
- 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
804
806
  };