@pol-studios/db 1.0.9 → 1.0.11

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 (113) hide show
  1. package/dist/DataLayerContext-CL6alnkb.d.ts +755 -0
  2. package/dist/UserMetadataContext-B8gVWGMl.d.ts +35 -0
  3. package/dist/UserMetadataContext-DntmpK41.d.ts +33 -0
  4. package/dist/auth/context.d.ts +3 -2
  5. package/dist/auth/context.js +22 -12786
  6. package/dist/auth/context.js.map +1 -1
  7. package/dist/auth/guards.js +12 -7640
  8. package/dist/auth/guards.js.map +1 -1
  9. package/dist/auth/hooks.d.ts +3 -3
  10. package/dist/auth/hooks.js +26 -10591
  11. package/dist/auth/hooks.js.map +1 -1
  12. package/dist/auth/index.d.ts +3 -2
  13. package/dist/auth/index.js +45 -13008
  14. package/dist/auth/index.js.map +1 -1
  15. package/dist/{canvas-UVNDA54X.node → canvas-C4TBBDUL.node} +0 -0
  16. package/dist/canvas-ZQNCL7JL.js +1541 -0
  17. package/dist/canvas-ZQNCL7JL.js.map +1 -0
  18. package/dist/chunk-3PJTNH2L.js +2778 -0
  19. package/dist/chunk-3PJTNH2L.js.map +1 -0
  20. package/dist/chunk-5EFDS7SR.js +205 -0
  21. package/dist/chunk-5EFDS7SR.js.map +1 -0
  22. package/dist/chunk-7SCJNYTE.js +1459 -0
  23. package/dist/chunk-7SCJNYTE.js.map +1 -0
  24. package/dist/chunk-DJ6VLEAL.js +247 -0
  25. package/dist/chunk-DJ6VLEAL.js.map +1 -0
  26. package/dist/chunk-GC3TBUWE.js +14 -0
  27. package/dist/chunk-GC3TBUWE.js.map +1 -0
  28. package/dist/chunk-H3LNH2NT.js +611 -0
  29. package/dist/chunk-H3LNH2NT.js.map +1 -0
  30. package/dist/chunk-H6365JPC.js +1858 -0
  31. package/dist/chunk-H6365JPC.js.map +1 -0
  32. package/dist/chunk-HAWJTZCK.js +86 -0
  33. package/dist/chunk-HAWJTZCK.js.map +1 -0
  34. package/dist/chunk-J4ZVCXZ4.js +1 -0
  35. package/dist/chunk-J4ZVCXZ4.js.map +1 -0
  36. package/dist/chunk-JAATANS3.js +429 -0
  37. package/dist/chunk-JAATANS3.js.map +1 -0
  38. package/dist/chunk-LNJ3WF7V.js +470 -0
  39. package/dist/chunk-LNJ3WF7V.js.map +1 -0
  40. package/dist/chunk-N26IEHZT.js +79 -0
  41. package/dist/chunk-N26IEHZT.js.map +1 -0
  42. package/dist/chunk-NSIAAYW3.js +1 -0
  43. package/dist/chunk-NSIAAYW3.js.map +1 -0
  44. package/dist/chunk-NZON56CB.js +3864 -0
  45. package/dist/chunk-NZON56CB.js.map +1 -0
  46. package/dist/chunk-OQ7U6EQ3.js +7550 -0
  47. package/dist/chunk-OQ7U6EQ3.js.map +1 -0
  48. package/dist/chunk-P4UZ7IXC.js +42 -0
  49. package/dist/chunk-P4UZ7IXC.js.map +1 -0
  50. package/dist/chunk-SM73S2DY.js +11 -0
  51. package/dist/chunk-SM73S2DY.js.map +1 -0
  52. package/dist/chunk-TKWR5AAY.js +415 -0
  53. package/dist/chunk-TKWR5AAY.js.map +1 -0
  54. package/dist/chunk-U5UNPBKB.js +501 -0
  55. package/dist/chunk-U5UNPBKB.js.map +1 -0
  56. package/dist/chunk-WGDJ4IXR.js +921 -0
  57. package/dist/chunk-WGDJ4IXR.js.map +1 -0
  58. package/dist/chunk-WVF7RUW5.js +186 -0
  59. package/dist/chunk-WVF7RUW5.js.map +1 -0
  60. package/dist/chunk-X3HZLNBV.js +2129 -0
  61. package/dist/chunk-X3HZLNBV.js.map +1 -0
  62. package/dist/chunk-XU3SBFAG.js +5205 -0
  63. package/dist/chunk-XU3SBFAG.js.map +1 -0
  64. package/dist/chunk-ZVBHWU7O.js +1412 -0
  65. package/dist/chunk-ZVBHWU7O.js.map +1 -0
  66. package/dist/client/index.d.ts +1 -1
  67. package/dist/client/index.js +54 -163
  68. package/dist/client/index.js.map +1 -1
  69. package/dist/core/index.d.ts +19 -0
  70. package/dist/{index-BFu5_dS8.d.ts → database.types-ChFCG-4M.d.ts} +1 -177
  71. package/dist/dist-NDNRSNOG.js +521 -0
  72. package/dist/dist-NDNRSNOG.js.map +1 -0
  73. package/dist/gen/index.js +188 -1280
  74. package/dist/gen/index.js.map +1 -1
  75. package/dist/hooks/index.d.ts +10 -3
  76. package/dist/hooks/index.js +20 -8695
  77. package/dist/hooks/index.js.map +1 -1
  78. package/dist/index-CQLyNG6A.d.ts +433 -0
  79. package/dist/index.d.ts +12 -8
  80. package/dist/index.js +447 -47848
  81. package/dist/index.js.map +1 -1
  82. package/dist/index.native.d.ts +373 -33
  83. package/dist/index.native.js +432 -25048
  84. package/dist/index.native.js.map +1 -1
  85. package/dist/index.web.d.ts +10 -7
  86. package/dist/index.web.js +585 -43773
  87. package/dist/index.web.js.map +1 -1
  88. package/dist/mutation/index.d.ts +2 -2
  89. package/dist/mutation/index.js +331 -4777
  90. package/dist/mutation/index.js.map +1 -1
  91. package/dist/parser/index.js +45 -3697
  92. package/dist/parser/index.js.map +1 -1
  93. package/dist/pdf-PHXP7RHD.js +20336 -0
  94. package/dist/pdf-PHXP7RHD.js.map +1 -0
  95. package/dist/powersync-bridge/index.d.ts +284 -0
  96. package/dist/powersync-bridge/index.js +22 -0
  97. package/dist/powersync-bridge/index.js.map +1 -0
  98. package/dist/query/index.js +31 -13175
  99. package/dist/query/index.js.map +1 -1
  100. package/dist/realtime/index.js +279 -12541
  101. package/dist/realtime/index.js.map +1 -1
  102. package/dist/{UserMetadataContext-BYYqA6LI.d.ts → setupAuthContext-Kv-THH-h.d.ts} +1 -29
  103. package/dist/types/index.d.ts +5 -1
  104. package/dist/types/index.js +14 -0
  105. package/dist/{useBatchUpsert-CSQVX7w8.d.ts → useBatchUpsert-9OYjibLh.d.ts} +1 -1
  106. package/dist/{useDbCount-RGCuHmHp.d.ts → useDbCount-BG356T9i.d.ts} +3 -719
  107. package/dist/{useReceiptAI-Bn0czE7C.d.ts → useReceiptAI-6HkRpRml.d.ts} +1 -1
  108. package/dist/{useResolveFeedback-CpZPP8Pw.d.ts → useResolveFeedback-BWmatBlE.d.ts} +26 -45
  109. package/dist/{useSupabase-pPhUZHcl.d.ts → useSupabase-DvWVuHHE.d.ts} +2 -1
  110. package/dist/with-auth/index.d.ts +704 -0
  111. package/dist/with-auth/index.js +1221 -0
  112. package/dist/with-auth/index.js.map +1 -0
  113. package/package.json +25 -10
@@ -0,0 +1,3864 @@
1
+ import {
2
+ normalizeFilter,
3
+ useDbAdvanceFilterQuery
4
+ } from "./chunk-H3LNH2NT.js";
5
+ import {
6
+ OperationLog
7
+ } from "./chunk-7SCJNYTE.js";
8
+ import {
9
+ useDbQuery
10
+ } from "./chunk-WGDJ4IXR.js";
11
+ import {
12
+ useDbUpsert
13
+ } from "./chunk-ZVBHWU7O.js";
14
+ import {
15
+ getSupabaseUrl
16
+ } from "./chunk-GC3TBUWE.js";
17
+ import {
18
+ PostgrestParser
19
+ } from "./chunk-TKWR5AAY.js";
20
+ import {
21
+ chunkArray,
22
+ diff,
23
+ getObjectChanges,
24
+ isNullOrWhitespace,
25
+ isUsable,
26
+ newUuid,
27
+ omit,
28
+ require_moment
29
+ } from "./chunk-OQ7U6EQ3.js";
30
+ import {
31
+ buildNormalizedQuery,
32
+ encode,
33
+ normalizeResponse,
34
+ useDeleteItem,
35
+ useDeleteManyMutation,
36
+ useInsertMutation,
37
+ useQueriesForTableLoader,
38
+ useQuery,
39
+ useUpsertItem
40
+ } from "./chunk-H6365JPC.js";
41
+ import {
42
+ UserSessionId,
43
+ useSupabase
44
+ } from "./chunk-5EFDS7SR.js";
45
+ import {
46
+ __require,
47
+ __toESM
48
+ } from "./chunk-P4UZ7IXC.js";
49
+
50
+ // src/useDbDelete.ts
51
+ import { c as _c } from "react/compiler-runtime";
52
+ import { useMutation } from "@tanstack/react-query";
53
+ function useDbDelete(relation, t0) {
54
+ const $ = _c(14);
55
+ let t1;
56
+ if ($[0] !== t0) {
57
+ t1 = t0 === void 0 ? ["id"] : t0;
58
+ $[0] = t0;
59
+ $[1] = t1;
60
+ } else {
61
+ t1 = $[1];
62
+ }
63
+ const primaryKeys = t1;
64
+ const tableName = typeof relation === "object" ? relation.table : relation;
65
+ const schemaName = typeof relation === "object" ? relation.schema : "public";
66
+ const supabase = useSupabase();
67
+ let t2;
68
+ if ($[2] !== primaryKeys) {
69
+ t2 = primaryKeys.map(_temp);
70
+ $[2] = primaryKeys;
71
+ $[3] = t2;
72
+ } else {
73
+ t2 = $[3];
74
+ }
75
+ const t3 = t2;
76
+ let t4;
77
+ if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
78
+ t4 = {
79
+ primaryKeys: t3,
80
+ table: tableName,
81
+ schema: schemaName
82
+ };
83
+ $[4] = schemaName;
84
+ $[5] = t3;
85
+ $[6] = tableName;
86
+ $[7] = t4;
87
+ } else {
88
+ t4 = $[7];
89
+ }
90
+ const deleteItem = useDeleteItem(t4);
91
+ let t5;
92
+ if ($[8] !== deleteItem || $[9] !== primaryKeys || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
93
+ t5 = {
94
+ mutationFn: async (item) => {
95
+ if (Array.isArray(item)) {
96
+ throw new Error("Item cannot be an array.");
97
+ }
98
+ const deleteQuery = supabase.schema(schemaName).from(tableName).delete();
99
+ primaryKeys.forEach((key) => {
100
+ const keyStr = String(key);
101
+ const value = item[keyStr];
102
+ if (isUsable(value)) {
103
+ deleteQuery.eq(keyStr, value);
104
+ }
105
+ });
106
+ const response = await deleteQuery.select().single();
107
+ if (response.error) {
108
+ throw response.error;
109
+ }
110
+ if (response.data) {
111
+ deleteItem(response.data);
112
+ } else {
113
+ deleteItem(item);
114
+ }
115
+ return response.data;
116
+ }
117
+ };
118
+ $[8] = deleteItem;
119
+ $[9] = primaryKeys;
120
+ $[10] = schemaName;
121
+ $[11] = supabase;
122
+ $[12] = tableName;
123
+ $[13] = t5;
124
+ } else {
125
+ t5 = $[13];
126
+ }
127
+ const deleteMutation = useMutation(t5);
128
+ return deleteMutation;
129
+ }
130
+ function _temp(k) {
131
+ return String(k);
132
+ }
133
+
134
+ // src/useDbInfiniteQuery.ts
135
+ import { useInfiniteQuery } from "@tanstack/react-query";
136
+ import { useMemo, useRef } from "react";
137
+ function useDbInfiniteQuery(query, countPerLoad, config) {
138
+ const initialQueryKey = encode(query, false).join("-");
139
+ const lastKnownQuery = useRef(initialQueryKey);
140
+ const currentPageNumber = useRef(1);
141
+ if (lastKnownQuery.current != initialQueryKey) {
142
+ lastKnownQuery.current = initialQueryKey;
143
+ currentPageNumber.current = 1;
144
+ }
145
+ const isFetching = useRef(false);
146
+ const queryKey = useMemo(() => encode(query, false), [initialQueryKey, config?.crossOrganization]);
147
+ const getQuery = useInfiniteQuery({
148
+ ...config,
149
+ queryKey,
150
+ queryFn: async ({
151
+ pageParam,
152
+ signal
153
+ }) => {
154
+ let adjustableQuery = query;
155
+ const pageNumber = pageParam;
156
+ if (config?.onQuery && config?.enableOnQuery) {
157
+ config?.onQuery({
158
+ query: adjustableQuery,
159
+ pageParam: pageNumber
160
+ });
161
+ } else {
162
+ adjustableQuery = adjustableQuery.range((pageNumber - 1) * countPerLoad, pageNumber * countPerLoad - 1);
163
+ }
164
+ adjustableQuery = adjustableQuery.abortSignal(signal);
165
+ updatedCache.current = false;
166
+ const response = await adjustableQuery;
167
+ currentPageNumber.current = pageNumber;
168
+ if (response.error) {
169
+ throw response.error;
170
+ } else {
171
+ return response;
172
+ }
173
+ },
174
+ initialPageParam: 1,
175
+ getNextPageParam: (response_0, allResponses, lastParam) => {
176
+ const pageParam_0 = lastParam;
177
+ const resp = response_0;
178
+ if (allResponses.length * countPerLoad >= (resp?.count ?? 0)) {
179
+ return void 0;
180
+ }
181
+ return pageParam_0 + 1;
182
+ }
183
+ });
184
+ const updatedCache = useRef(true);
185
+ return useMemo(() => {
186
+ const pages = getQuery.data?.pages;
187
+ return {
188
+ ...getQuery,
189
+ count: pages?.[pages.length - 1]?.count,
190
+ data: pages?.flatMap((x) => x.data ?? [])
191
+ };
192
+ }, [getQuery.data, currentPageNumber.current]);
193
+ }
194
+
195
+ // src/useDbInsert.ts
196
+ import { c as _c2 } from "react/compiler-runtime";
197
+ import { useMutation as useMutation2 } from "@tanstack/react-query";
198
+ function useDbInsert(relation, t0, query, mutationOption) {
199
+ const $ = _c2(11);
200
+ let t1;
201
+ if ($[0] !== t0) {
202
+ t1 = t0 === void 0 ? ["id"] : t0;
203
+ $[0] = t0;
204
+ $[1] = t1;
205
+ } else {
206
+ t1 = $[1];
207
+ }
208
+ const primaryKeys = t1;
209
+ const supabase = useSupabase();
210
+ const tableName = typeof relation === "object" ? relation.table : relation;
211
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
212
+ let t2;
213
+ if ($[2] !== primaryKeys) {
214
+ t2 = primaryKeys.map(_temp3);
215
+ $[2] = primaryKeys;
216
+ $[3] = t2;
217
+ } else {
218
+ t2 = $[3];
219
+ }
220
+ const primaryKeysAsStrings = t2;
221
+ const t3 = supabase;
222
+ let t4;
223
+ if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
224
+ t4 = t3.schema(schemaName).from(tableName);
225
+ $[4] = schemaName;
226
+ $[5] = t3;
227
+ $[6] = tableName;
228
+ $[7] = t4;
229
+ } else {
230
+ t4 = $[7];
231
+ }
232
+ const mutation = useInsertMutation(t4, primaryKeysAsStrings, query, mutationOption);
233
+ let t5;
234
+ if ($[8] !== mutation || $[9] !== primaryKeys) {
235
+ t5 = {
236
+ mutationFn: async (item) => {
237
+ const primaryKeysNull = primaryKeys.filter((x) => x in item === false || isUsable(item[x]) === false).map(_temp2);
238
+ const response = await mutation.mutateAsync([omit(item, primaryKeysNull)]);
239
+ mutation.reset();
240
+ return response?.[0];
241
+ }
242
+ };
243
+ $[8] = mutation;
244
+ $[9] = primaryKeys;
245
+ $[10] = t5;
246
+ } else {
247
+ t5 = $[10];
248
+ }
249
+ const updateMutation = useMutation2(t5);
250
+ return updateMutation;
251
+ }
252
+ function _temp2(k_0) {
253
+ return String(k_0);
254
+ }
255
+ function _temp3(k) {
256
+ return String(k);
257
+ }
258
+
259
+ // src/useDbMultiDelete.ts
260
+ import { c as _c3 } from "react/compiler-runtime";
261
+ import { useMutation as useMutation3 } from "@tanstack/react-query";
262
+ function useDbMultiDelete(relation, t0) {
263
+ const $ = _c3(10);
264
+ let t1;
265
+ if ($[0] !== t0) {
266
+ t1 = t0 === void 0 ? ["id"] : t0;
267
+ $[0] = t0;
268
+ $[1] = t1;
269
+ } else {
270
+ t1 = $[1];
271
+ }
272
+ const primaryKeys = t1;
273
+ const tableName = typeof relation === "object" ? relation.table : relation;
274
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
275
+ const supabase = useSupabase();
276
+ let t2;
277
+ if ($[2] !== primaryKeys) {
278
+ t2 = primaryKeys.map(_temp4);
279
+ $[2] = primaryKeys;
280
+ $[3] = t2;
281
+ } else {
282
+ t2 = $[3];
283
+ }
284
+ const primaryKeysAsStrings = t2;
285
+ const t3 = supabase;
286
+ let t4;
287
+ if ($[4] !== schemaName || $[5] !== t3 || $[6] !== tableName) {
288
+ t4 = t3.schema(schemaName).from(tableName);
289
+ $[4] = schemaName;
290
+ $[5] = t3;
291
+ $[6] = tableName;
292
+ $[7] = t4;
293
+ } else {
294
+ t4 = $[7];
295
+ }
296
+ const deleteManyMutation = useDeleteManyMutation(t4, primaryKeysAsStrings);
297
+ let t5;
298
+ if ($[8] !== deleteManyMutation) {
299
+ t5 = {
300
+ mutationFn: async (item) => {
301
+ if (Array.isArray(item)) {
302
+ const response = await deleteManyMutation.mutateAsync(item);
303
+ return response;
304
+ } else {
305
+ throw new Error("Item must be an array.");
306
+ }
307
+ }
308
+ };
309
+ $[8] = deleteManyMutation;
310
+ $[9] = t5;
311
+ } else {
312
+ t5 = $[9];
313
+ }
314
+ const deleteMutation = useMutation3(t5);
315
+ return deleteMutation;
316
+ }
317
+ function _temp4(k) {
318
+ return String(k);
319
+ }
320
+
321
+ // src/useDbMultiUpsert.ts
322
+ import { c as _c4 } from "react/compiler-runtime";
323
+ import { useMutation as useMutation4 } from "@tanstack/react-query";
324
+ function useDbMultiUpsert(relation, t0, t1) {
325
+ const $ = _c4(17);
326
+ let t2;
327
+ if ($[0] !== t0) {
328
+ t2 = t0 === void 0 ? ["id"] : t0;
329
+ $[0] = t0;
330
+ $[1] = t2;
331
+ } else {
332
+ t2 = $[1];
333
+ }
334
+ const primaryKeys = t2;
335
+ const query = t1 === void 0 ? "*" : t1;
336
+ const supabase = useSupabase();
337
+ const tableName = typeof relation === "object" ? relation.table : relation;
338
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
339
+ const t3 = relation;
340
+ let t4;
341
+ if ($[2] !== primaryKeys || $[3] !== t3) {
342
+ t4 = {
343
+ primaryKeys,
344
+ table: t3,
345
+ schema: "public"
346
+ };
347
+ $[2] = primaryKeys;
348
+ $[3] = t3;
349
+ $[4] = t4;
350
+ } else {
351
+ t4 = $[4];
352
+ }
353
+ const upsertItem = useUpsertItem(t4);
354
+ let t5;
355
+ if ($[5] !== primaryKeys) {
356
+ t5 = primaryKeys.map(_temp5);
357
+ $[5] = primaryKeys;
358
+ $[6] = t5;
359
+ } else {
360
+ t5 = $[6];
361
+ }
362
+ const primaryKeysAsStrings = t5;
363
+ let t6;
364
+ if ($[7] !== primaryKeys || $[8] !== primaryKeysAsStrings || $[9] !== query || $[10] !== schemaName || $[11] !== supabase || $[12] !== tableName) {
365
+ t6 = async function upsertItemAction2(item) {
366
+ let task;
367
+ if (Object.keys(item).length !== primaryKeys.length && primaryKeys.every((key_0) => key_0 in item && isUsable(item[key_0]))) {
368
+ const updateObject = omit(item, primaryKeysAsStrings);
369
+ task = supabase.schema(schemaName).from(tableName).update(updateObject);
370
+ primaryKeys.forEach((key) => {
371
+ task = task.eq(String(key), item[key]);
372
+ });
373
+ } else {
374
+ task = supabase.schema(schemaName).from(tableName).insert(omit(item, primaryKeysAsStrings));
375
+ }
376
+ const response = await task.select(query);
377
+ if (response.error) {
378
+ throw response.error;
379
+ }
380
+ return response.data[0];
381
+ };
382
+ $[7] = primaryKeys;
383
+ $[8] = primaryKeysAsStrings;
384
+ $[9] = query;
385
+ $[10] = schemaName;
386
+ $[11] = supabase;
387
+ $[12] = tableName;
388
+ $[13] = t6;
389
+ } else {
390
+ t6 = $[13];
391
+ }
392
+ const upsertItemAction = t6;
393
+ let t7;
394
+ if ($[14] !== upsertItem || $[15] !== upsertItemAction) {
395
+ t7 = {
396
+ mutationFn: async (item_0) => {
397
+ if (Array.isArray(item_0)) {
398
+ const data = await Promise.all(item_0.map((x) => upsertItemAction(x)));
399
+ data.filter(_temp22).forEach((x_1) => upsertItem(x_1));
400
+ return data;
401
+ }
402
+ throw new Error("Item must be an array.");
403
+ }
404
+ };
405
+ $[14] = upsertItem;
406
+ $[15] = upsertItemAction;
407
+ $[16] = t7;
408
+ } else {
409
+ t7 = $[16];
410
+ }
411
+ const updateMutation = useMutation4(t7);
412
+ return updateMutation;
413
+ }
414
+ function _temp22(x_0) {
415
+ return isUsable(x_0);
416
+ }
417
+ function _temp5(k) {
418
+ return String(k);
419
+ }
420
+
421
+ // src/useDbPartialAdvanceQuery.ts
422
+ import { c as _c5 } from "react/compiler-runtime";
423
+ import { useLayoutEffect, useState } from "react";
424
+ import { useSessionStorageState } from "@pol-studios/hooks/storage";
425
+ function useDbPartialAdvanceQuery(query, itemCountPerPage, config) {
426
+ const $ = _c5(54);
427
+ const initialQuery = encode(query, false);
428
+ const [id, setId] = useState(window.location.pathname);
429
+ const [currentPage, setCurrentPage] = useSessionStorageState(`${id}-currentPage`, 1);
430
+ const page = currentPage ?? 1;
431
+ const t0 = query;
432
+ let t1;
433
+ if ($[0] !== itemCountPerPage || $[1] !== page || $[2] !== t0) {
434
+ t1 = t0.range((page - 1) * itemCountPerPage, page * itemCountPerPage - 1);
435
+ $[0] = itemCountPerPage;
436
+ $[1] = page;
437
+ $[2] = t0;
438
+ $[3] = t1;
439
+ } else {
440
+ t1 = $[3];
441
+ }
442
+ const rangedQuery = t1;
443
+ const t2 = config?.filterKey;
444
+ const t3 = currentPage ?? 1;
445
+ let t4;
446
+ if ($[4] !== t3) {
447
+ t4 = t3.toString();
448
+ $[4] = t3;
449
+ $[5] = t4;
450
+ } else {
451
+ t4 = $[5];
452
+ }
453
+ let t5;
454
+ if ($[6] !== config || $[7] !== t2 || $[8] !== t4) {
455
+ t5 = {
456
+ ...config,
457
+ filterKey: t2,
458
+ count: "exact",
459
+ key: t4
460
+ };
461
+ $[6] = config;
462
+ $[7] = t2;
463
+ $[8] = t4;
464
+ $[9] = t5;
465
+ } else {
466
+ t5 = $[9];
467
+ }
468
+ const [baseQuery, filter, setFilters] = useDbAdvanceFilterQuery(rangedQuery, t5);
469
+ let t6;
470
+ if ($[10] !== filter) {
471
+ t6 = JSON.stringify(omit(filter, ["pagination"]));
472
+ $[10] = filter;
473
+ $[11] = t6;
474
+ } else {
475
+ t6 = $[11];
476
+ }
477
+ const filterKey = t6;
478
+ const select = initialQuery[4].split("&").find(_temp6);
479
+ let t7;
480
+ if ($[12] !== filterKey || $[13] !== id || $[14] !== initialQuery[3] || $[15] !== initialQuery[5] || $[16] !== initialQuery[6] || $[17] !== initialQuery[7] || $[18] !== initialQuery[8] || $[19] !== select || $[20] !== setId) {
481
+ t7 = () => {
482
+ const newId = [initialQuery[3], select, initialQuery[5], initialQuery[6], initialQuery[7], initialQuery[8], filterKey].join("-");
483
+ console.log({
484
+ newId,
485
+ id
486
+ });
487
+ setId(newId);
488
+ };
489
+ $[12] = filterKey;
490
+ $[13] = id;
491
+ $[14] = initialQuery[3];
492
+ $[15] = initialQuery[5];
493
+ $[16] = initialQuery[6];
494
+ $[17] = initialQuery[7];
495
+ $[18] = initialQuery[8];
496
+ $[19] = select;
497
+ $[20] = setId;
498
+ $[21] = t7;
499
+ } else {
500
+ t7 = $[21];
501
+ }
502
+ let t8;
503
+ if ($[22] !== filterKey || $[23] !== initialQuery[3] || $[24] !== initialQuery[5] || $[25] !== initialQuery[6] || $[26] !== initialQuery[7] || $[27] !== initialQuery[8] || $[28] !== select) {
504
+ t8 = [initialQuery[3], select, initialQuery[5], initialQuery[6], initialQuery[7], initialQuery[8], filterKey];
505
+ $[22] = filterKey;
506
+ $[23] = initialQuery[3];
507
+ $[24] = initialQuery[5];
508
+ $[25] = initialQuery[6];
509
+ $[26] = initialQuery[7];
510
+ $[27] = initialQuery[8];
511
+ $[28] = select;
512
+ $[29] = t8;
513
+ } else {
514
+ t8 = $[29];
515
+ }
516
+ useLayoutEffect(t7, t8);
517
+ let t9;
518
+ if ($[30] !== setCurrentPage) {
519
+ t9 = () => {
520
+ setCurrentPage(_temp23);
521
+ };
522
+ $[30] = setCurrentPage;
523
+ $[31] = t9;
524
+ } else {
525
+ t9 = $[31];
526
+ }
527
+ const safeFetchNextPage = t9;
528
+ let t10;
529
+ if ($[32] !== setCurrentPage) {
530
+ t10 = () => {
531
+ setCurrentPage(_temp32);
532
+ };
533
+ $[32] = setCurrentPage;
534
+ $[33] = t10;
535
+ } else {
536
+ t10 = $[33];
537
+ }
538
+ const fetchPreviousPage = t10;
539
+ const pageCount = Math.max(Math.ceil((baseQuery.count ?? 0) / itemCountPerPage), 1);
540
+ const t11 = currentPage ?? 1;
541
+ let t12;
542
+ if ($[34] !== baseQuery.count || $[35] !== baseQuery.data || $[36] !== currentPage || $[37] !== itemCountPerPage) {
543
+ t12 = baseQuery.data ? toPagedResponse(baseQuery.data, currentPage ?? 1, baseQuery.count ?? baseQuery.data.length, itemCountPerPage) : null;
544
+ $[34] = baseQuery.count;
545
+ $[35] = baseQuery.data;
546
+ $[36] = currentPage;
547
+ $[37] = itemCountPerPage;
548
+ $[38] = t12;
549
+ } else {
550
+ t12 = $[38];
551
+ }
552
+ const t13 = (currentPage ?? 1) < pageCount;
553
+ const t14 = (currentPage ?? 1) > 1;
554
+ const t15 = baseQuery.count ?? baseQuery.data?.length;
555
+ let t16;
556
+ if ($[39] !== baseQuery || $[40] !== fetchPreviousPage || $[41] !== pageCount || $[42] !== safeFetchNextPage || $[43] !== setCurrentPage || $[44] !== t11 || $[45] !== t12 || $[46] !== t13 || $[47] !== t14 || $[48] !== t15) {
557
+ t16 = {
558
+ ...baseQuery,
559
+ clarification: baseQuery.clarification,
560
+ fetchPreviousPage,
561
+ fetchNextPage: safeFetchNextPage,
562
+ currentPage: t11,
563
+ setCurrentPage,
564
+ data: t12,
565
+ pageCount,
566
+ hasNextPage: t13,
567
+ hasPreviousPage: t14,
568
+ count: t15
569
+ };
570
+ $[39] = baseQuery;
571
+ $[40] = fetchPreviousPage;
572
+ $[41] = pageCount;
573
+ $[42] = safeFetchNextPage;
574
+ $[43] = setCurrentPage;
575
+ $[44] = t11;
576
+ $[45] = t12;
577
+ $[46] = t13;
578
+ $[47] = t14;
579
+ $[48] = t15;
580
+ $[49] = t16;
581
+ } else {
582
+ t16 = $[49];
583
+ }
584
+ const request = t16;
585
+ let t17;
586
+ if ($[50] !== filter || $[51] !== request || $[52] !== setFilters) {
587
+ t17 = [request, filter, setFilters];
588
+ $[50] = filter;
589
+ $[51] = request;
590
+ $[52] = setFilters;
591
+ $[53] = t17;
592
+ } else {
593
+ t17 = $[53];
594
+ }
595
+ return t17;
596
+ }
597
+ function _temp32(currentPage_1) {
598
+ return (currentPage_1 ?? 1) - 1;
599
+ }
600
+ function _temp23(currentPage_0) {
601
+ return (currentPage_0 ?? 1) + 1;
602
+ }
603
+ function _temp6(x) {
604
+ return x.startsWith("select=");
605
+ }
606
+ function toPagedResponse(results, currentPage, totalCount, itemPerPage) {
607
+ const newPage = {
608
+ Items: results,
609
+ CurrentPage: currentPage,
610
+ ItemCount: totalCount,
611
+ MaxCountPerPage: itemPerPage,
612
+ PageCount: Math.max(Math.ceil(totalCount / itemPerPage), 1)
613
+ };
614
+ return newPage;
615
+ }
616
+
617
+ // src/useDbPartialQuery.ts
618
+ import { c as _c6 } from "react/compiler-runtime";
619
+ import { useSessionStorageState as useSessionStorageState2 } from "@pol-studios/hooks/storage";
620
+ function useDbPartialQuery(query, itemCountPerPage, config) {
621
+ const $ = _c6(28);
622
+ let t0;
623
+ if ($[0] !== query) {
624
+ t0 = encode(query, false);
625
+ $[0] = query;
626
+ $[1] = t0;
627
+ } else {
628
+ t0 = $[1];
629
+ }
630
+ const initialQuery = t0;
631
+ let t1;
632
+ if ($[2] !== initialQuery[7] || $[3] !== initialQuery[8]) {
633
+ t1 = [initialQuery[7], initialQuery[8]];
634
+ $[2] = initialQuery[7];
635
+ $[3] = initialQuery[8];
636
+ $[4] = t1;
637
+ } else {
638
+ t1 = $[4];
639
+ }
640
+ const id = t1.join("-");
641
+ const [currentPage, setCurrentPage] = useSessionStorageState2(id, 1);
642
+ const page = currentPage ?? 1;
643
+ const t2 = query;
644
+ let t3;
645
+ if ($[5] !== itemCountPerPage || $[6] !== page || $[7] !== t2) {
646
+ t3 = t2.range((page - 1) * itemCountPerPage, page * itemCountPerPage - 1);
647
+ $[5] = itemCountPerPage;
648
+ $[6] = page;
649
+ $[7] = t2;
650
+ $[8] = t3;
651
+ } else {
652
+ t3 = $[8];
653
+ }
654
+ const rangedQuery = t3;
655
+ const baseQuery = useDbQuery(rangedQuery, config);
656
+ let t4;
657
+ if ($[9] !== setCurrentPage) {
658
+ t4 = () => {
659
+ setCurrentPage(_temp7);
660
+ };
661
+ $[9] = setCurrentPage;
662
+ $[10] = t4;
663
+ } else {
664
+ t4 = $[10];
665
+ }
666
+ const safeFetchNextPage = t4;
667
+ let t5;
668
+ if ($[11] !== setCurrentPage) {
669
+ t5 = () => {
670
+ setCurrentPage(_temp24);
671
+ };
672
+ $[11] = setCurrentPage;
673
+ $[12] = t5;
674
+ } else {
675
+ t5 = $[12];
676
+ }
677
+ const fetchPreviousPage = t5;
678
+ const pageCount = Math.max(Math.ceil((baseQuery.count ?? 0) / itemCountPerPage), 1);
679
+ const t6 = currentPage ?? 1;
680
+ let t7;
681
+ if ($[13] !== baseQuery.count || $[14] !== baseQuery.data || $[15] !== currentPage || $[16] !== itemCountPerPage) {
682
+ t7 = baseQuery.data ? toPagedResponse2(baseQuery.data, currentPage ?? 1, baseQuery.count ?? baseQuery.data.length, itemCountPerPage) : null;
683
+ $[13] = baseQuery.count;
684
+ $[14] = baseQuery.data;
685
+ $[15] = currentPage;
686
+ $[16] = itemCountPerPage;
687
+ $[17] = t7;
688
+ } else {
689
+ t7 = $[17];
690
+ }
691
+ const t8 = (currentPage ?? 1) < pageCount;
692
+ const t9 = (currentPage ?? 1) > 1;
693
+ let t10;
694
+ if ($[18] !== baseQuery || $[19] !== fetchPreviousPage || $[20] !== pageCount || $[21] !== safeFetchNextPage || $[22] !== setCurrentPage || $[23] !== t6 || $[24] !== t7 || $[25] !== t8 || $[26] !== t9) {
695
+ t10 = {
696
+ ...baseQuery,
697
+ fetchPreviousPage,
698
+ fetchNextPage: safeFetchNextPage,
699
+ currentPage: t6,
700
+ setCurrentPage,
701
+ data: t7,
702
+ pageCount,
703
+ hasNextPage: t8,
704
+ hasPreviousPage: t9
705
+ };
706
+ $[18] = baseQuery;
707
+ $[19] = fetchPreviousPage;
708
+ $[20] = pageCount;
709
+ $[21] = safeFetchNextPage;
710
+ $[22] = setCurrentPage;
711
+ $[23] = t6;
712
+ $[24] = t7;
713
+ $[25] = t8;
714
+ $[26] = t9;
715
+ $[27] = t10;
716
+ } else {
717
+ t10 = $[27];
718
+ }
719
+ return t10;
720
+ }
721
+ function _temp24(currentPage_1) {
722
+ return currentPage_1 - 1;
723
+ }
724
+ function _temp7(currentPage_0) {
725
+ return currentPage_0 + 1;
726
+ }
727
+ function toPagedResponse2(results, currentPage, totalCount, itemPerPage) {
728
+ const newPage = {
729
+ Items: results,
730
+ CurrentPage: currentPage,
731
+ ItemCount: totalCount,
732
+ MaxCountPerPage: itemPerPage,
733
+ PageCount: Math.max(Math.ceil(totalCount / itemPerPage), 1)
734
+ };
735
+ return newPage;
736
+ }
737
+
738
+ // src/useDbRealtime.ts
739
+ import { c as _c7 } from "react/compiler-runtime";
740
+ import { useEffect, useState as useState2, useRef as useRef2 } from "react";
741
+ import { REALTIME_POSTGRES_CHANGES_LISTEN_EVENT } from "@supabase/supabase-js";
742
+ import { useDelayedValue } from "@pol-studios/hooks/state";
743
+ function useDbRealtime(key, query, table, primaryKeys, options) {
744
+ const $ = _c7(37);
745
+ const supabase = useSupabase();
746
+ const tableNameValue = typeof table === "string" ? table : table.table;
747
+ const schemaValue = typeof table === "string" ? "public" : table.schema;
748
+ const queriesForTable = useQueriesForTableLoader(tableNameValue);
749
+ let t0;
750
+ if ($[0] !== primaryKeys || $[1] !== schemaValue || $[2] !== tableNameValue) {
751
+ t0 = {
752
+ primaryKeys,
753
+ table: tableNameValue,
754
+ schema: schemaValue
755
+ };
756
+ $[0] = primaryKeys;
757
+ $[1] = schemaValue;
758
+ $[2] = tableNameValue;
759
+ $[3] = t0;
760
+ } else {
761
+ t0 = $[3];
762
+ }
763
+ const deleteItem = useDeleteItem(t0);
764
+ let t1;
765
+ if ($[4] !== primaryKeys || $[5] !== schemaValue || $[6] !== tableNameValue) {
766
+ t1 = {
767
+ primaryKeys,
768
+ table: tableNameValue,
769
+ schema: schemaValue
770
+ };
771
+ $[4] = primaryKeys;
772
+ $[5] = schemaValue;
773
+ $[6] = tableNameValue;
774
+ $[7] = t1;
775
+ } else {
776
+ t1 = $[7];
777
+ }
778
+ const upsertItem = useUpsertItem(t1);
779
+ const [realtimeState, setRealtimeState] = useState2("CLOSED");
780
+ const [retryTick, setRetryTick] = useState2(0);
781
+ const channelRef = useRef2(null);
782
+ const lastRetryTimeRef = useRef2(0);
783
+ const retryCountRef = useRef2(0);
784
+ const enabled = options?.enabled ?? true;
785
+ const filter = options?.filter;
786
+ const onChange = options?.onChange;
787
+ const debouncedKey = useDelayedValue(key, 50);
788
+ let t2;
789
+ if ($[8] !== deleteItem || $[9] !== enabled || $[10] !== filter || $[11] !== onChange || $[12] !== primaryKeys || $[13] !== queriesForTable || $[14] !== query || $[15] !== retryTick || $[16] !== schemaValue || $[17] !== supabase || $[18] !== tableNameValue || $[19] !== upsertItem) {
790
+ t2 = () => {
791
+ if (!enabled) {
792
+ if (channelRef.current) {
793
+ channelRef.current.unsubscribe();
794
+ supabase.removeChannel(channelRef.current);
795
+ channelRef.current = null;
796
+ }
797
+ setRealtimeState("CLOSED");
798
+ return;
799
+ }
800
+ const now = Date.now();
801
+ const timeSinceLastRetry = now - lastRetryTimeRef.current;
802
+ if (timeSinceLastRetry < 2e3 && retryTick > 0) {
803
+ return;
804
+ }
805
+ if (channelRef.current) {
806
+ channelRef.current.unsubscribe();
807
+ supabase.removeChannel(channelRef.current);
808
+ channelRef.current = null;
809
+ }
810
+ lastRetryTimeRef.current = now;
811
+ retryCountRef.current = retryCountRef.current + 1;
812
+ const channel = supabase.channel(newUuid()).on("postgres_changes", {
813
+ event: "*",
814
+ schema: schemaValue,
815
+ table: tableNameValue,
816
+ filter
817
+ }, async (payload) => {
818
+ let data = payload.new ?? payload.old;
819
+ if (payload.new && Object.keys(payload.new).length > 0) {
820
+ const selectQuery = buildNormalizedQuery({
821
+ queriesForTable,
822
+ query
823
+ });
824
+ if (payload.eventType !== REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE && selectQuery) {
825
+ if (selectQuery.groupedUserQueryPaths?.every((x) => x.path in data) === false) {
826
+ const qb = supabase.schema(payload.schema).from(payload.table).select(selectQuery.selectQuery);
827
+ for (const pk of primaryKeys) {
828
+ qb.eq(pk.toString(), data[pk]);
829
+ }
830
+ const res = await qb.single();
831
+ if (res.data) {
832
+ data = normalizeResponse(selectQuery.groupedPaths, res.data);
833
+ }
834
+ }
835
+ }
836
+ if ("changedBySessionId" in data) {
837
+ const sessionId = data.changedBySessionId;
838
+ if (sessionId !== UserSessionId) {
839
+ await upsertItem(data);
840
+ }
841
+ } else {
842
+ await upsertItem(data);
843
+ }
844
+ }
845
+ if (payload.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
846
+ await deleteItem(payload.old);
847
+ }
848
+ if (payload.errors?.length > 0) {
849
+ setRealtimeState("CHANNEL_ERROR");
850
+ }
851
+ if (onChange) {
852
+ onChange(payload);
853
+ }
854
+ }).on("postgres_changes", {
855
+ event: "DELETE",
856
+ schema: schemaValue,
857
+ table: tableNameValue
858
+ }, async (payload_0) => {
859
+ if (payload_0.eventType === REALTIME_POSTGRES_CHANGES_LISTEN_EVENT.DELETE) {
860
+ await deleteItem(payload_0.old);
861
+ }
862
+ }).subscribe((status) => {
863
+ setRealtimeState(status);
864
+ if (status === "SUBSCRIBED") {
865
+ retryCountRef.current = 0;
866
+ }
867
+ });
868
+ channelRef.current = channel;
869
+ return () => {
870
+ if (channelRef.current) {
871
+ channelRef.current.unsubscribe();
872
+ supabase.removeChannel(channelRef.current);
873
+ channelRef.current = null;
874
+ }
875
+ };
876
+ };
877
+ $[8] = deleteItem;
878
+ $[9] = enabled;
879
+ $[10] = filter;
880
+ $[11] = onChange;
881
+ $[12] = primaryKeys;
882
+ $[13] = queriesForTable;
883
+ $[14] = query;
884
+ $[15] = retryTick;
885
+ $[16] = schemaValue;
886
+ $[17] = supabase;
887
+ $[18] = tableNameValue;
888
+ $[19] = upsertItem;
889
+ $[20] = t2;
890
+ } else {
891
+ t2 = $[20];
892
+ }
893
+ let t3;
894
+ if ($[21] !== primaryKeys) {
895
+ t3 = primaryKeys.join(",");
896
+ $[21] = primaryKeys;
897
+ $[22] = t3;
898
+ } else {
899
+ t3 = $[22];
900
+ }
901
+ let t4;
902
+ if ($[23] !== debouncedKey || $[24] !== enabled || $[25] !== filter || $[26] !== query || $[27] !== retryTick || $[28] !== schemaValue || $[29] !== supabase || $[30] !== t3 || $[31] !== tableNameValue) {
903
+ t4 = [supabase, tableNameValue, schemaValue, enabled, filter, query, t3, retryTick, debouncedKey];
904
+ $[23] = debouncedKey;
905
+ $[24] = enabled;
906
+ $[25] = filter;
907
+ $[26] = query;
908
+ $[27] = retryTick;
909
+ $[28] = schemaValue;
910
+ $[29] = supabase;
911
+ $[30] = t3;
912
+ $[31] = tableNameValue;
913
+ $[32] = t4;
914
+ } else {
915
+ t4 = $[32];
916
+ }
917
+ useEffect(t2, t4);
918
+ let t5;
919
+ let t6;
920
+ if ($[33] !== enabled || $[34] !== realtimeState) {
921
+ t5 = () => {
922
+ if (!enabled || realtimeState === "SUBSCRIBED") {
923
+ retryCountRef.current = 0;
924
+ return;
925
+ }
926
+ const delay = Math.min(5e3 * Math.pow(2, retryCountRef.current), 6e4);
927
+ const id = setTimeout(() => {
928
+ setRetryTick(_temp8);
929
+ }, delay);
930
+ return () => clearTimeout(id);
931
+ };
932
+ t6 = [realtimeState, enabled];
933
+ $[33] = enabled;
934
+ $[34] = realtimeState;
935
+ $[35] = t5;
936
+ $[36] = t6;
937
+ } else {
938
+ t5 = $[35];
939
+ t6 = $[36];
940
+ }
941
+ useEffect(t5, t6);
942
+ return realtimeState;
943
+ }
944
+ function _temp8(t) {
945
+ return t + 1;
946
+ }
947
+
948
+ // src/useDbRealtimeQuery.tsx
949
+ import { c as _c8 } from "react/compiler-runtime";
950
+ function convertFilterToRealtimeQuery(filters) {
951
+ function convert(filter) {
952
+ if (!filter) return "";
953
+ if ("path" in filter) {
954
+ if (filter.path.includes(".")) return "";
955
+ let valueString = filter.value?.toString() ?? "null";
956
+ if (filter.operator === "in") {
957
+ valueString = '("' + valueString.slice(2, valueString.length - 2).split(",").join('","') + '")';
958
+ }
959
+ return `${filter.path}=${filter.negate ? "not." : ""}${filter.operator}.${valueString}`;
960
+ } else {
961
+ if (filter.or) {
962
+ return `(${filter.or.map((f) => convert(f)).join("|")})`;
963
+ } else if (filter.and) {
964
+ return `(${filter.and.map((f) => convert(f)).join("&")})`;
965
+ }
966
+ }
967
+ return "";
968
+ }
969
+ return convert(filters[0]);
970
+ }
971
+ function useDbRealtimeQuery(query, config, t0) {
972
+ const $ = _c8(27);
973
+ let t1;
974
+ if ($[0] !== t0) {
975
+ t1 = t0 === void 0 ? ["id"] : t0;
976
+ $[0] = t0;
977
+ $[1] = t1;
978
+ } else {
979
+ t1 = $[1];
980
+ }
981
+ const primaryKeys = t1;
982
+ const t2 = query;
983
+ let t3;
984
+ if ($[2] !== t2) {
985
+ t3 = new PostgrestParser(t2);
986
+ $[2] = t2;
987
+ $[3] = t3;
988
+ } else {
989
+ t3 = $[3];
990
+ }
991
+ const parser = t3;
992
+ const request = useQuery(query, config);
993
+ let filter;
994
+ let selectStatement;
995
+ let t4;
996
+ let t5;
997
+ if ($[4] !== parser.filters || $[5] !== parser.select || $[6] !== query || $[7] !== request.data) {
998
+ const queryKey = encode(query, false);
999
+ let t62;
1000
+ if ($[12] !== parser.filters || $[13] !== request.data) {
1001
+ const filterString = convertFilterToRealtimeQuery(parser.filters);
1002
+ filter = request.data && typeof request.data === "object" && "id" in request.data ? "id=eq." + request.data.id : filterString;
1003
+ if (filter.includes('in.(\\"\\")')) {
1004
+ filter = void 0;
1005
+ }
1006
+ t62 = isNullOrWhitespace(filter);
1007
+ $[12] = parser.filters;
1008
+ $[13] = request.data;
1009
+ $[14] = filter;
1010
+ $[15] = t62;
1011
+ } else {
1012
+ filter = $[14];
1013
+ t62 = $[15];
1014
+ }
1015
+ if (t62) {
1016
+ filter = void 0;
1017
+ }
1018
+ selectStatement = parser.select;
1019
+ t4 = useDbRealtime;
1020
+ t5 = queryKey.join("-");
1021
+ $[4] = parser.filters;
1022
+ $[5] = parser.select;
1023
+ $[6] = query;
1024
+ $[7] = request.data;
1025
+ $[8] = filter;
1026
+ $[9] = selectStatement;
1027
+ $[10] = t4;
1028
+ $[11] = t5;
1029
+ } else {
1030
+ filter = $[8];
1031
+ selectStatement = $[9];
1032
+ t4 = $[10];
1033
+ t5 = $[11];
1034
+ }
1035
+ let t6;
1036
+ if ($[16] !== parser.schema || $[17] !== parser.table) {
1037
+ t6 = {
1038
+ schema: parser.schema,
1039
+ table: parser.table
1040
+ };
1041
+ $[16] = parser.schema;
1042
+ $[17] = parser.table;
1043
+ $[18] = t6;
1044
+ } else {
1045
+ t6 = $[18];
1046
+ }
1047
+ const t7 = typeof config?.enabled === "boolean" ? config.enabled : true;
1048
+ let t8;
1049
+ if ($[19] !== filter || $[20] !== t7) {
1050
+ t8 = {
1051
+ filter,
1052
+ enabled: t7
1053
+ };
1054
+ $[19] = filter;
1055
+ $[20] = t7;
1056
+ $[21] = t8;
1057
+ } else {
1058
+ t8 = $[21];
1059
+ }
1060
+ const realtimeStatus = t4(t5, selectStatement, t6, primaryKeys, t8);
1061
+ const outputRealtimeStatus = request.isFetching ? "Loading..." : realtimeStatus;
1062
+ const t9 = request.data;
1063
+ const t10 = realtimeStatus == "SUBSCRIBED";
1064
+ let t11;
1065
+ if ($[22] !== outputRealtimeStatus || $[23] !== request || $[24] !== t10 || $[25] !== t9) {
1066
+ t11 = {
1067
+ ...request,
1068
+ data: t9,
1069
+ realtimeStatus: outputRealtimeStatus,
1070
+ isRealtimeConnected: t10,
1071
+ isRealtimeLoading: request.isFetching
1072
+ };
1073
+ $[22] = outputRealtimeStatus;
1074
+ $[23] = request;
1075
+ $[24] = t10;
1076
+ $[25] = t9;
1077
+ $[26] = t11;
1078
+ } else {
1079
+ t11 = $[26];
1080
+ }
1081
+ return t11;
1082
+ }
1083
+
1084
+ // src/useDbUpdate.ts
1085
+ import { c as _c9 } from "react/compiler-runtime";
1086
+ import { useMutation as useMutation5 } from "@tanstack/react-query";
1087
+ function useDbUpdate(relation, t0, query, mutationOption) {
1088
+ const $ = _c9(14);
1089
+ let t1;
1090
+ if ($[0] !== t0) {
1091
+ t1 = t0 === void 0 ? ["id"] : t0;
1092
+ $[0] = t0;
1093
+ $[1] = t1;
1094
+ } else {
1095
+ t1 = $[1];
1096
+ }
1097
+ const primaryKeys = t1;
1098
+ const supabase = useSupabase();
1099
+ const tableName = typeof relation === "object" ? relation.table : relation;
1100
+ const schemaName = typeof relation === "object" ? String(relation.schema) : "public";
1101
+ let t2;
1102
+ if ($[2] !== primaryKeys) {
1103
+ t2 = primaryKeys.map(_temp9);
1104
+ $[2] = primaryKeys;
1105
+ $[3] = t2;
1106
+ } else {
1107
+ t2 = $[3];
1108
+ }
1109
+ const primaryKeysAsStrings = t2;
1110
+ const t3 = primaryKeysAsStrings;
1111
+ const t4 = relation;
1112
+ let t5;
1113
+ if ($[4] !== t3 || $[5] !== t4) {
1114
+ t5 = {
1115
+ primaryKeys: t3,
1116
+ table: t4,
1117
+ schema: "public"
1118
+ };
1119
+ $[4] = t3;
1120
+ $[5] = t4;
1121
+ $[6] = t5;
1122
+ } else {
1123
+ t5 = $[6];
1124
+ }
1125
+ const upsertItem = useUpsertItem(t5);
1126
+ let t6;
1127
+ if ($[7] !== primaryKeys || $[8] !== primaryKeysAsStrings || $[9] !== schemaName || $[10] !== supabase || $[11] !== tableName || $[12] !== upsertItem) {
1128
+ t6 = {
1129
+ mutationFn: async (item) => {
1130
+ let response = null;
1131
+ if (primaryKeys.every((x_0) => x_0 in item && isUsable(item[x_0]))) {
1132
+ const query_0 = supabase.schema(schemaName).from(tableName).update(omit(item, primaryKeysAsStrings));
1133
+ primaryKeys.forEach((x) => {
1134
+ query_0.eq(String(x), item[x]);
1135
+ });
1136
+ const queryResponse = await query_0.select().single().throwOnError();
1137
+ if (queryResponse.data) {
1138
+ response = queryResponse.data;
1139
+ upsertItem(response);
1140
+ }
1141
+ }
1142
+ return response;
1143
+ }
1144
+ };
1145
+ $[7] = primaryKeys;
1146
+ $[8] = primaryKeysAsStrings;
1147
+ $[9] = schemaName;
1148
+ $[10] = supabase;
1149
+ $[11] = tableName;
1150
+ $[12] = upsertItem;
1151
+ $[13] = t6;
1152
+ } else {
1153
+ t6 = $[13];
1154
+ }
1155
+ const updateMutation = useMutation5(t6);
1156
+ return updateMutation;
1157
+ }
1158
+ function _temp9(k) {
1159
+ return String(k);
1160
+ }
1161
+
1162
+ // src/useMutationSuccess.ts
1163
+ import { c as _c10 } from "react/compiler-runtime";
1164
+ import { useEffect as useEffect2, useRef as useRef3 } from "react";
1165
+ function useMutationSuccess(mutation, t0) {
1166
+ const $ = _c10(10);
1167
+ let t1;
1168
+ if ($[0] !== t0) {
1169
+ t1 = t0 === void 0 ? {} : t0;
1170
+ $[0] = t0;
1171
+ $[1] = t1;
1172
+ } else {
1173
+ t1 = $[1];
1174
+ }
1175
+ const options = t1;
1176
+ const {
1177
+ successMessage,
1178
+ entityName,
1179
+ enabled: t2,
1180
+ onSuccess
1181
+ } = options;
1182
+ const enabled = t2 === void 0 ? true : t2;
1183
+ const previousSuccessRef = useRef3(false);
1184
+ const previousDataRef = useRef3(void 0);
1185
+ let t3;
1186
+ let t4;
1187
+ if ($[2] !== enabled || $[3] !== entityName || $[4] !== mutation.data || $[5] !== mutation.isSuccess || $[6] !== onSuccess || $[7] !== successMessage) {
1188
+ t3 = () => {
1189
+ if (!enabled) {
1190
+ return;
1191
+ }
1192
+ const isSuccess = mutation.isSuccess;
1193
+ const hasNewData = mutation.data !== previousDataRef.current;
1194
+ if (isSuccess && hasNewData && !previousSuccessRef.current) {
1195
+ const message = successMessage || getDefaultSuccessMessage(entityName);
1196
+ if (typeof window !== "undefined") {
1197
+ try {
1198
+ const {
1199
+ toast
1200
+ } = __require("@pol-studios/hooks");
1201
+ toast.toast({
1202
+ title: "Success",
1203
+ description: message
1204
+ });
1205
+ } catch {
1206
+ }
1207
+ } else {
1208
+ try {
1209
+ const {
1210
+ Toast
1211
+ } = __require("toastify-react-native");
1212
+ Toast.success(message);
1213
+ } catch {
1214
+ }
1215
+ }
1216
+ onSuccess?.();
1217
+ }
1218
+ previousSuccessRef.current = isSuccess;
1219
+ previousDataRef.current = mutation.data;
1220
+ };
1221
+ t4 = [mutation.isSuccess, mutation.data, enabled, successMessage, entityName, onSuccess];
1222
+ $[2] = enabled;
1223
+ $[3] = entityName;
1224
+ $[4] = mutation.data;
1225
+ $[5] = mutation.isSuccess;
1226
+ $[6] = onSuccess;
1227
+ $[7] = successMessage;
1228
+ $[8] = t3;
1229
+ $[9] = t4;
1230
+ } else {
1231
+ t3 = $[8];
1232
+ t4 = $[9];
1233
+ }
1234
+ useEffect2(t3, t4);
1235
+ return mutation;
1236
+ }
1237
+ function getDefaultSuccessMessage(entityName) {
1238
+ if (!entityName) {
1239
+ return "Saved successfully";
1240
+ }
1241
+ return `${entityName} saved successfully`;
1242
+ }
1243
+ function useMutationSuccessRN(mutation, t0) {
1244
+ const $ = _c10(2);
1245
+ let t1;
1246
+ if ($[0] !== t0) {
1247
+ t1 = t0 === void 0 ? {} : t0;
1248
+ $[0] = t0;
1249
+ $[1] = t1;
1250
+ } else {
1251
+ t1 = $[1];
1252
+ }
1253
+ const options = t1;
1254
+ return useMutationSuccess(mutation, options);
1255
+ }
1256
+
1257
+ // src/adapters/types.ts
1258
+ var ADAPTER_STRATEGIES = {
1259
+ POWERSYNC: "powersync",
1260
+ SUPABASE: "supabase",
1261
+ CACHED: "cached",
1262
+ HYBRID: "hybrid",
1263
+ AUTO: "auto"
1264
+ };
1265
+
1266
+ // src/adapters/auto-detector.ts
1267
+ var BackendStatus = /* @__PURE__ */ ((BackendStatus2) => {
1268
+ BackendStatus2["AVAILABLE"] = "available";
1269
+ BackendStatus2["INITIALIZING"] = "initializing";
1270
+ BackendStatus2["UNAVAILABLE"] = "unavailable";
1271
+ return BackendStatus2;
1272
+ })(BackendStatus || {});
1273
+ var AdapterAutoDetector = class {
1274
+ constructor(powerSyncDb, supabase, options = {}) {
1275
+ this.powerSyncDb = powerSyncDb;
1276
+ this.supabase = supabase;
1277
+ this.options = {
1278
+ preferPowerSync: options.preferPowerSync ?? true,
1279
+ statusCheckTimeout: options.statusCheckTimeout ?? 1e3,
1280
+ useOnlineUntilSynced: options.useOnlineUntilSynced ?? true
1281
+ };
1282
+ }
1283
+ options;
1284
+ listeners = /* @__PURE__ */ new Set();
1285
+ lastResult = null;
1286
+ syncStatus = null;
1287
+ /**
1288
+ * Update the sync status from PowerSync.
1289
+ * Called when sync status changes to re-evaluate backend recommendation.
1290
+ *
1291
+ * @param status - Current sync status or null if not available
1292
+ */
1293
+ updateSyncStatus(status) {
1294
+ const hadSynced = this.syncStatus?.hasSynced;
1295
+ const hasSyncedNow = status?.hasSynced;
1296
+ const changed = hadSynced !== hasSyncedNow;
1297
+ this.syncStatus = status;
1298
+ if (changed) {
1299
+ this.detect();
1300
+ }
1301
+ }
1302
+ /**
1303
+ * Get current sync status.
1304
+ * @returns Current sync status or null
1305
+ */
1306
+ getSyncStatus() {
1307
+ return this.syncStatus;
1308
+ }
1309
+ // ===========================================================================
1310
+ // Main Detection Methods
1311
+ // ===========================================================================
1312
+ /**
1313
+ * Detect backend availability and recommend best option.
1314
+ *
1315
+ * The detection logic follows this priority:
1316
+ * 1. If preferPowerSync is true and PowerSync is available, use PowerSync
1317
+ * 2. If PowerSync is initializing and online with Supabase available, use Supabase temporarily
1318
+ * 3. If online with Supabase available, use Supabase
1319
+ * 4. If offline but PowerSync available, use PowerSync (offline mode)
1320
+ * 5. If offline and PowerSync exists (even if initializing), use PowerSync local data
1321
+ * 6. Default to Supabase as fallback
1322
+ *
1323
+ * @returns Detection result with recommendation and reasoning
1324
+ */
1325
+ detect() {
1326
+ const powerSyncStatus = this.detectPowerSyncStatus();
1327
+ const supabaseStatus = this.detectSupabaseStatus();
1328
+ const isOnline = this.checkOnlineStatus();
1329
+ let recommendedBackend;
1330
+ let reason;
1331
+ if (this.options.preferPowerSync && powerSyncStatus === "available" /* AVAILABLE */) {
1332
+ recommendedBackend = "powersync";
1333
+ reason = "PowerSync is available and preferred for offline-first experience";
1334
+ } else if (powerSyncStatus === "initializing" /* INITIALIZING */ && isOnline && supabaseStatus === "available" /* AVAILABLE */) {
1335
+ recommendedBackend = "supabase";
1336
+ reason = "PowerSync initial sync in progress; using Supabase for fresh data";
1337
+ } else if (supabaseStatus === "available" /* AVAILABLE */ && isOnline) {
1338
+ recommendedBackend = "supabase";
1339
+ reason = "Using Supabase direct connection";
1340
+ } else if (powerSyncStatus === "available" /* AVAILABLE */) {
1341
+ recommendedBackend = "powersync";
1342
+ reason = "Offline mode using PowerSync local data";
1343
+ } else if (!isOnline && this.powerSyncDb) {
1344
+ recommendedBackend = "powersync";
1345
+ reason = "Offline mode - using PowerSync local data (initial sync may be incomplete)";
1346
+ } else {
1347
+ recommendedBackend = "supabase";
1348
+ reason = "No confirmed available backend; defaulting to Supabase";
1349
+ }
1350
+ const result = {
1351
+ powerSyncStatus,
1352
+ supabaseStatus,
1353
+ recommendedBackend,
1354
+ isOnline,
1355
+ reason
1356
+ };
1357
+ if (this.hasResultChanged(result)) {
1358
+ this.lastResult = result;
1359
+ this.notifyListeners(result);
1360
+ }
1361
+ return result;
1362
+ }
1363
+ /**
1364
+ * Check if PowerSync is available.
1365
+ *
1366
+ * PowerSync status depends on:
1367
+ * 1. Database instance exists
1368
+ * 2. If useOnlineUntilSynced is true, also checks if initial sync completed
1369
+ *
1370
+ * @returns PowerSync backend status
1371
+ */
1372
+ detectPowerSyncStatus() {
1373
+ if (!this.powerSyncDb) {
1374
+ return "unavailable" /* UNAVAILABLE */;
1375
+ }
1376
+ try {
1377
+ if (typeof this.powerSyncDb.getAll !== "function") {
1378
+ return "initializing" /* INITIALIZING */;
1379
+ }
1380
+ if (this.options.useOnlineUntilSynced && this.syncStatus) {
1381
+ if (!this.syncStatus.hasSynced) {
1382
+ return "initializing" /* INITIALIZING */;
1383
+ }
1384
+ }
1385
+ return "available" /* AVAILABLE */;
1386
+ } catch {
1387
+ return "initializing" /* INITIALIZING */;
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Check if Supabase is available.
1392
+ *
1393
+ * Supabase is considered available if we have a client instance.
1394
+ * The actual network connectivity is checked separately via checkOnlineStatus().
1395
+ *
1396
+ * @returns Supabase backend status
1397
+ */
1398
+ detectSupabaseStatus() {
1399
+ if (!this.supabase) {
1400
+ return "unavailable" /* UNAVAILABLE */;
1401
+ }
1402
+ try {
1403
+ if (typeof this.supabase.from === "function") {
1404
+ return "available" /* AVAILABLE */;
1405
+ }
1406
+ return "unavailable" /* UNAVAILABLE */;
1407
+ } catch {
1408
+ return "unavailable" /* UNAVAILABLE */;
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Check if device is online.
1413
+ *
1414
+ * Prefers the sync status's isOnline property if available (from React Native NetInfo).
1415
+ * Falls back to navigator.onLine in browser environments.
1416
+ * Returns true by default for other environments.
1417
+ *
1418
+ * @returns Whether the device has network connectivity
1419
+ */
1420
+ checkOnlineStatus() {
1421
+ if (this.syncStatus?.isOnline !== void 0) {
1422
+ return this.syncStatus.isOnline;
1423
+ }
1424
+ if (typeof window !== "undefined" && typeof navigator !== "undefined") {
1425
+ return navigator.onLine;
1426
+ }
1427
+ return true;
1428
+ }
1429
+ // ===========================================================================
1430
+ // Instance Management Methods
1431
+ // ===========================================================================
1432
+ /**
1433
+ * Update PowerSync instance (e.g., when it becomes available).
1434
+ *
1435
+ * @param db - New PowerSync database instance or null
1436
+ */
1437
+ setPowerSync(db) {
1438
+ this.powerSyncDb = db;
1439
+ }
1440
+ /**
1441
+ * Update Supabase instance.
1442
+ *
1443
+ * @param supabase - New Supabase client instance or null
1444
+ */
1445
+ setSupabase(supabase) {
1446
+ this.supabase = supabase;
1447
+ }
1448
+ /**
1449
+ * Get current PowerSync instance.
1450
+ *
1451
+ * @returns Current PowerSync database instance or null
1452
+ */
1453
+ getPowerSync() {
1454
+ return this.powerSyncDb;
1455
+ }
1456
+ /**
1457
+ * Get current Supabase instance.
1458
+ *
1459
+ * @returns Current Supabase client instance or null
1460
+ */
1461
+ getSupabase() {
1462
+ return this.supabase;
1463
+ }
1464
+ // ===========================================================================
1465
+ // Options Management
1466
+ // ===========================================================================
1467
+ /**
1468
+ * Update detector options.
1469
+ *
1470
+ * @param options - New options to merge with existing
1471
+ */
1472
+ setOptions(options) {
1473
+ this.options = {
1474
+ ...this.options,
1475
+ ...options
1476
+ };
1477
+ }
1478
+ /**
1479
+ * Get current detector options.
1480
+ *
1481
+ * @returns Current detector options
1482
+ */
1483
+ getOptions() {
1484
+ return {
1485
+ ...this.options
1486
+ };
1487
+ }
1488
+ // ===========================================================================
1489
+ // Listener Management
1490
+ // ===========================================================================
1491
+ /**
1492
+ * Add a listener for backend change events.
1493
+ *
1494
+ * @param listener - Callback to invoke when detection result changes
1495
+ * @returns Function to remove the listener
1496
+ */
1497
+ addListener(listener) {
1498
+ this.listeners.add(listener);
1499
+ return () => this.listeners.delete(listener);
1500
+ }
1501
+ /**
1502
+ * Remove a listener for backend change events.
1503
+ *
1504
+ * @param listener - Listener to remove
1505
+ */
1506
+ removeListener(listener) {
1507
+ this.listeners.delete(listener);
1508
+ }
1509
+ /**
1510
+ * Get the last detection result.
1511
+ *
1512
+ * @returns Last detection result or null if never detected
1513
+ */
1514
+ getLastResult() {
1515
+ return this.lastResult;
1516
+ }
1517
+ // ===========================================================================
1518
+ // Private Helper Methods
1519
+ // ===========================================================================
1520
+ /**
1521
+ * Check if the detection result has changed from the last result.
1522
+ */
1523
+ hasResultChanged(result) {
1524
+ if (!this.lastResult) {
1525
+ return true;
1526
+ }
1527
+ return this.lastResult.powerSyncStatus !== result.powerSyncStatus || this.lastResult.supabaseStatus !== result.supabaseStatus || this.lastResult.recommendedBackend !== result.recommendedBackend || this.lastResult.isOnline !== result.isOnline;
1528
+ }
1529
+ /**
1530
+ * Notify all listeners of a detection result change.
1531
+ */
1532
+ notifyListeners(result) {
1533
+ Array.from(this.listeners).forEach((listener) => {
1534
+ try {
1535
+ listener(result);
1536
+ } catch (error) {
1537
+ console.error("Error in backend change listener:", error);
1538
+ }
1539
+ });
1540
+ }
1541
+ };
1542
+ function createAdapterAutoDetector(powerSyncDb, supabase, options) {
1543
+ return new AdapterAutoDetector(powerSyncDb, supabase, options);
1544
+ }
1545
+
1546
+ // src/adapters/registry.ts
1547
+ var AdapterRegistry = class {
1548
+ /**
1549
+ * Create a new adapter registry
1550
+ *
1551
+ * @param config - Data layer configuration with table strategies
1552
+ */
1553
+ constructor(config) {
1554
+ this.config = config;
1555
+ }
1556
+ /**
1557
+ * Cache of created adapters by table name
1558
+ */
1559
+ adapters = /* @__PURE__ */ new Map();
1560
+ /**
1561
+ * PowerSync adapter instance (set during initialization)
1562
+ */
1563
+ powerSyncAdapter = null;
1564
+ /**
1565
+ * Supabase adapter instance (set during initialization)
1566
+ */
1567
+ supabaseAdapter = null;
1568
+ /**
1569
+ * Cached adapter instance (wraps Supabase with TanStack Query)
1570
+ */
1571
+ cachedAdapter = null;
1572
+ /**
1573
+ * Dependencies for creating adapters
1574
+ */
1575
+ deps = null;
1576
+ /**
1577
+ * Whether the registry has been initialized with adapters
1578
+ */
1579
+ _isInitialized = false;
1580
+ /**
1581
+ * Auto-detector instance for automatic backend selection
1582
+ */
1583
+ autoDetector = null;
1584
+ /**
1585
+ * Listeners for backend change events
1586
+ */
1587
+ backendChangeListeners = /* @__PURE__ */ new Set();
1588
+ /**
1589
+ * Last auto-detection result for debugging and status
1590
+ */
1591
+ lastDetectionResult = null;
1592
+ // ===========================================================================
1593
+ // Initialization
1594
+ // ===========================================================================
1595
+ /**
1596
+ * Check if the registry has been initialized
1597
+ */
1598
+ get isInitialized() {
1599
+ return this._isInitialized;
1600
+ }
1601
+ /**
1602
+ * Initialize the registry with dependencies.
1603
+ * Called by DataLayerProvider when PowerSync and Supabase are ready.
1604
+ *
1605
+ * @param deps - Dependencies needed to create adapters
1606
+ */
1607
+ initialize(deps) {
1608
+ this.deps = deps;
1609
+ this._isInitialized = true;
1610
+ }
1611
+ /**
1612
+ * Set the PowerSync adapter instance
1613
+ *
1614
+ * @param adapter - PowerSync adapter implementation
1615
+ */
1616
+ setPowerSyncAdapter(adapter) {
1617
+ this.powerSyncAdapter = adapter;
1618
+ }
1619
+ /**
1620
+ * Set the Supabase adapter instance
1621
+ *
1622
+ * @param adapter - Supabase adapter implementation
1623
+ */
1624
+ setSupabaseAdapter(adapter) {
1625
+ this.supabaseAdapter = adapter;
1626
+ }
1627
+ /**
1628
+ * Set the Cached adapter instance
1629
+ *
1630
+ * @param adapter - Cached adapter implementation
1631
+ */
1632
+ setCachedAdapter(adapter) {
1633
+ this.cachedAdapter = adapter;
1634
+ }
1635
+ /**
1636
+ * Initialize auto-detection with a detector instance
1637
+ *
1638
+ * @param detector - The auto-detector to use
1639
+ */
1640
+ initializeAutoDetection(detector) {
1641
+ this.autoDetector = detector;
1642
+ detector.addListener((result) => {
1643
+ this.lastDetectionResult = result;
1644
+ this.notifyBackendChange(result.recommendedBackend);
1645
+ });
1646
+ }
1647
+ // ===========================================================================
1648
+ // Adapter Access
1649
+ // ===========================================================================
1650
+ /**
1651
+ * Get the appropriate adapter for a table based on configuration.
1652
+ *
1653
+ * The adapter is selected based on the table's strategy in config.tables:
1654
+ * - "powersync": Returns PowerSyncAdapter
1655
+ * - "supabase": Returns SupabaseAdapter
1656
+ * - "cached": Returns CachedAdapter (wrapping Supabase)
1657
+ * - "hybrid": Returns HybridAdapter (combining PowerSync + Cached)
1658
+ * - "auto": Uses auto-detection to select the best backend
1659
+ *
1660
+ * For tables not in config, defaults to auto-detection if available,
1661
+ * otherwise falls back to SupabaseAdapter.
1662
+ *
1663
+ * @param table - The table name
1664
+ * @returns The appropriate adapter for the table
1665
+ * @throws Error if adapters are not initialized
1666
+ */
1667
+ getAdapter(table) {
1668
+ const strategy = this.config.tables[table];
1669
+ if (!strategy || strategy.strategy === "auto") {
1670
+ if (this.powerSyncAdapter) {
1671
+ const powerSyncTables = this.getPowerSyncTables();
1672
+ if (!powerSyncTables.includes(table)) {
1673
+ if (this.supabaseAdapter) {
1674
+ return this.supabaseAdapter;
1675
+ }
1676
+ throw new Error(`Table "${table}" is not configured for PowerSync sync and Supabase adapter is not available. Either add this table to the PowerSync schema or initialize the Supabase adapter.`);
1677
+ }
1678
+ }
1679
+ return this.getAutoAdapter(strategy);
1680
+ }
1681
+ if (strategy.strategy === "powersync" && this.autoDetector && this.supabaseAdapter) {
1682
+ const detection = this.autoDetector.detect();
1683
+ if (detection.powerSyncStatus === "initializing" /* INITIALIZING */ && detection.isOnline) {
1684
+ return this.supabaseAdapter;
1685
+ }
1686
+ }
1687
+ const existing = this.adapters.get(table);
1688
+ if (existing) {
1689
+ return existing;
1690
+ }
1691
+ const adapter = this.createAdapter(strategy);
1692
+ this.adapters.set(table, adapter);
1693
+ return adapter;
1694
+ }
1695
+ /**
1696
+ * Get the PowerSync adapter directly
1697
+ *
1698
+ * @returns PowerSync adapter or null if not initialized
1699
+ */
1700
+ getPowerSyncAdapter() {
1701
+ return this.powerSyncAdapter;
1702
+ }
1703
+ /**
1704
+ * Get the Supabase adapter directly
1705
+ *
1706
+ * @returns Supabase adapter or null if not initialized
1707
+ */
1708
+ getSupabaseAdapter() {
1709
+ return this.supabaseAdapter;
1710
+ }
1711
+ /**
1712
+ * Get the Cached adapter directly
1713
+ *
1714
+ * @returns Cached adapter or null if not initialized
1715
+ */
1716
+ getCachedAdapter() {
1717
+ return this.cachedAdapter;
1718
+ }
1719
+ /**
1720
+ * Get all configured table names
1721
+ *
1722
+ * @returns Array of table names with explicit strategy configuration
1723
+ */
1724
+ getConfiguredTables() {
1725
+ return Object.keys(this.config.tables);
1726
+ }
1727
+ /**
1728
+ * Get the strategy for a specific table
1729
+ *
1730
+ * @param table - The table name
1731
+ * @returns The table strategy or undefined if not configured
1732
+ */
1733
+ getTableStrategy(table) {
1734
+ return this.config.tables[table];
1735
+ }
1736
+ /**
1737
+ * Check if a table uses PowerSync strategy
1738
+ *
1739
+ * @param table - The table name
1740
+ * @returns True if table uses PowerSync or Hybrid strategy
1741
+ */
1742
+ usesPowerSync(table) {
1743
+ const strategy = this.config.tables[table];
1744
+ return strategy?.strategy === "powersync" || strategy?.strategy === "hybrid";
1745
+ }
1746
+ /**
1747
+ * Get all tables that use PowerSync
1748
+ *
1749
+ * @returns Array of table names using PowerSync or Hybrid strategy
1750
+ */
1751
+ getPowerSyncTables() {
1752
+ return Object.entries(this.config.tables).filter(([_, strategy]) => strategy.strategy === "powersync" || strategy.strategy === "hybrid").map(([table]) => table);
1753
+ }
1754
+ // ===========================================================================
1755
+ // Auto-Detection Methods
1756
+ // ===========================================================================
1757
+ /**
1758
+ * Get adapter using auto-detection
1759
+ *
1760
+ * @param strategy - Optional auto strategy configuration
1761
+ * @returns The automatically selected adapter
1762
+ */
1763
+ getAutoAdapter(strategy) {
1764
+ if (!this.autoDetector) {
1765
+ if (!this.supabaseAdapter) {
1766
+ throw new Error("No auto-detector configured and Supabase adapter not available. Either initialize auto-detection or set adapters explicitly.");
1767
+ }
1768
+ return this.supabaseAdapter;
1769
+ }
1770
+ const detection = this.autoDetector.detect();
1771
+ this.lastDetectionResult = detection;
1772
+ if (detection.recommendedBackend === "powersync") {
1773
+ if (!this.powerSyncAdapter) {
1774
+ if (!this.supabaseAdapter) {
1775
+ throw new Error("Neither PowerSync nor Supabase adapters are available.");
1776
+ }
1777
+ return this.supabaseAdapter;
1778
+ }
1779
+ return this.powerSyncAdapter;
1780
+ }
1781
+ if (!this.supabaseAdapter) {
1782
+ throw new Error("Supabase adapter not available and PowerSync not recommended.");
1783
+ }
1784
+ return this.supabaseAdapter;
1785
+ }
1786
+ /**
1787
+ * Subscribe to backend changes
1788
+ *
1789
+ * @param callback - Function called when recommended backend changes
1790
+ * @returns Unsubscribe function
1791
+ */
1792
+ onBackendChange(callback) {
1793
+ this.backendChangeListeners.add(callback);
1794
+ return () => {
1795
+ this.backendChangeListeners.delete(callback);
1796
+ };
1797
+ }
1798
+ /**
1799
+ * Notify listeners of backend change
1800
+ *
1801
+ * @param backend - The new recommended backend
1802
+ */
1803
+ notifyBackendChange(backend) {
1804
+ this.backendChangeListeners.forEach((callback) => {
1805
+ try {
1806
+ callback(backend);
1807
+ } catch (error) {
1808
+ console.error("Error in backend change listener:", error);
1809
+ }
1810
+ });
1811
+ }
1812
+ /**
1813
+ * Get the last auto-detection result
1814
+ *
1815
+ * @returns Last detection result or null if never detected
1816
+ */
1817
+ getLastDetectionResult() {
1818
+ return this.lastDetectionResult;
1819
+ }
1820
+ /**
1821
+ * Get the auto-detector instance
1822
+ *
1823
+ * @returns Auto-detector instance or null if not initialized
1824
+ */
1825
+ getAutoDetector() {
1826
+ return this.autoDetector;
1827
+ }
1828
+ // ===========================================================================
1829
+ // Private Methods
1830
+ // ===========================================================================
1831
+ /**
1832
+ * Create an adapter based on the strategy type
1833
+ *
1834
+ * @param strategy - The table strategy configuration
1835
+ * @returns The created adapter
1836
+ * @throws Error if the required base adapter is not initialized
1837
+ */
1838
+ createAdapter(strategy) {
1839
+ switch (strategy.strategy) {
1840
+ case "powersync":
1841
+ if (!this.powerSyncAdapter) {
1842
+ throw new Error("PowerSync adapter not initialized. Ensure PowerSyncAdapter is set before accessing PowerSync tables.");
1843
+ }
1844
+ return this.powerSyncAdapter;
1845
+ case "supabase":
1846
+ if (!this.supabaseAdapter) {
1847
+ throw new Error("Supabase adapter not initialized. Ensure SupabaseAdapter is set before accessing Supabase tables.");
1848
+ }
1849
+ return this.supabaseAdapter;
1850
+ case "cached":
1851
+ if (this.cachedAdapter) {
1852
+ return this.cachedAdapter;
1853
+ }
1854
+ throw new Error("CachedAdapter not yet implemented. This feature will be available in Wave 2. For now, use 'supabase' strategy as a fallback.");
1855
+ case "hybrid":
1856
+ throw new Error("HybridAdapter not yet implemented. This feature will be available in Wave 2. For now, use 'powersync' or 'supabase' strategy as a fallback.");
1857
+ default:
1858
+ if (!this.supabaseAdapter) {
1859
+ throw new Error("Supabase adapter not initialized. Ensure SupabaseAdapter is set before accessing tables.");
1860
+ }
1861
+ return this.supabaseAdapter;
1862
+ }
1863
+ }
1864
+ // ===========================================================================
1865
+ // Utility Methods
1866
+ // ===========================================================================
1867
+ /**
1868
+ * Clear all cached adapters.
1869
+ * Useful when configuration changes and adapters need to be recreated.
1870
+ */
1871
+ clearCache() {
1872
+ this.adapters.clear();
1873
+ }
1874
+ /**
1875
+ * Reset the registry to uninitialized state.
1876
+ * Used during cleanup or testing.
1877
+ */
1878
+ reset() {
1879
+ this.adapters.clear();
1880
+ this.powerSyncAdapter = null;
1881
+ this.supabaseAdapter = null;
1882
+ this.cachedAdapter = null;
1883
+ this.deps = null;
1884
+ this._isInitialized = false;
1885
+ this.autoDetector = null;
1886
+ this.backendChangeListeners.clear();
1887
+ this.lastDetectionResult = null;
1888
+ }
1889
+ /**
1890
+ * Dispose all adapters and clean up resources.
1891
+ * Called when the DataLayerProvider unmounts.
1892
+ */
1893
+ dispose() {
1894
+ this.reset();
1895
+ }
1896
+ /**
1897
+ * Get debug information about the registry state
1898
+ */
1899
+ getDebugInfo() {
1900
+ return {
1901
+ isInitialized: this._isInitialized,
1902
+ hasPowerSync: this.powerSyncAdapter !== null,
1903
+ hasSupabase: this.supabaseAdapter !== null,
1904
+ hasCached: this.cachedAdapter !== null,
1905
+ cachedAdapterCount: this.adapters.size,
1906
+ configuredTableCount: Object.keys(this.config.tables).length,
1907
+ powerSyncTables: this.getPowerSyncTables(),
1908
+ hasAutoDetector: this.autoDetector !== null,
1909
+ lastDetectionResult: this.lastDetectionResult
1910
+ };
1911
+ }
1912
+ };
1913
+ function createAdapterRegistry(config) {
1914
+ return new AdapterRegistry(config);
1915
+ }
1916
+
1917
+ // src/adapters/supabase-adapter.ts
1918
+ var SupabaseAdapter = class {
1919
+ constructor(supabase, schema) {
1920
+ this.supabase = supabase;
1921
+ this.schema = schema;
1922
+ }
1923
+ name = "supabase";
1924
+ capabilities = {
1925
+ supportsSubscribe: true,
1926
+ supportsOffline: false,
1927
+ supportsCache: false,
1928
+ supportsSync: false
1929
+ };
1930
+ // ===========================================================================
1931
+ // Private Helper - Table Name Parsing
1932
+ // ===========================================================================
1933
+ /**
1934
+ * Parse a table identifier to extract schema and table name.
1935
+ * Handles schema-qualified names like "core.Profile" -> { schema: "core", tableName: "Profile" }
1936
+ *
1937
+ * @param table - The table name, optionally schema-qualified (e.g., "users" or "core.Profile")
1938
+ * @returns Object with schema (defaults to "public") and tableName
1939
+ */
1940
+ parseTableIdentifier(table) {
1941
+ if (table.includes(".")) {
1942
+ const [schema, ...rest] = table.split(".");
1943
+ return {
1944
+ schema,
1945
+ tableName: rest.join(".")
1946
+ };
1947
+ }
1948
+ return {
1949
+ schema: "public",
1950
+ tableName: table
1951
+ };
1952
+ }
1953
+ // ===========================================================================
1954
+ // Query Operations
1955
+ // ===========================================================================
1956
+ /**
1957
+ * Execute a query and return results with optional count
1958
+ *
1959
+ * @param table - The table name to query
1960
+ * @param options - Query options (select, where, orderBy, limit, offset)
1961
+ * @returns Promise resolving to query results with optional count
1962
+ */
1963
+ async query(table, options) {
1964
+ const {
1965
+ select = "*",
1966
+ where,
1967
+ orderBy,
1968
+ limit,
1969
+ offset
1970
+ } = options;
1971
+ const {
1972
+ schema,
1973
+ tableName
1974
+ } = this.parseTableIdentifier(table);
1975
+ let query = this.supabase.schema(schema).from(tableName).select(select, {
1976
+ count: "exact"
1977
+ });
1978
+ if (where) {
1979
+ query = this.applyWhereClause(query, where);
1980
+ }
1981
+ if (orderBy && orderBy.length > 0) {
1982
+ for (const order of orderBy) {
1983
+ query = query.order(order.field, {
1984
+ ascending: order.direction === "asc"
1985
+ });
1986
+ }
1987
+ }
1988
+ if (limit !== void 0 && offset !== void 0) {
1989
+ query = query.range(offset, offset + limit - 1);
1990
+ } else if (limit !== void 0) {
1991
+ query = query.limit(limit);
1992
+ }
1993
+ const {
1994
+ data,
1995
+ error,
1996
+ count
1997
+ } = await query;
1998
+ if (error) {
1999
+ throw new Error(`Supabase query error on ${table}: ${error.message}`);
2000
+ }
2001
+ return {
2002
+ data: data ?? [],
2003
+ count: count ?? void 0
2004
+ };
2005
+ }
2006
+ /**
2007
+ * Query a single record by ID
2008
+ *
2009
+ * @param table - The table name to query
2010
+ * @param id - The record ID
2011
+ * @param options - Optional query options (mainly for select)
2012
+ * @returns Promise resolving to the record or null if not found
2013
+ */
2014
+ async queryById(table, id, options) {
2015
+ const select = options?.select ?? "*";
2016
+ const {
2017
+ schema,
2018
+ tableName
2019
+ } = this.parseTableIdentifier(table);
2020
+ const {
2021
+ data,
2022
+ error
2023
+ } = await this.supabase.schema(schema).from(tableName).select(select).eq("id", id).single();
2024
+ if (error) {
2025
+ if (error.code === "PGRST116") {
2026
+ return null;
2027
+ }
2028
+ throw new Error(`Supabase queryById error on ${table}: ${error.message}`);
2029
+ }
2030
+ return data;
2031
+ }
2032
+ // ===========================================================================
2033
+ // Mutation Operations
2034
+ // ===========================================================================
2035
+ /**
2036
+ * Insert a new record
2037
+ *
2038
+ * @param table - The table name
2039
+ * @param data - The data to insert
2040
+ * @returns Promise resolving to the inserted record
2041
+ */
2042
+ async insert(table, data) {
2043
+ const {
2044
+ schema,
2045
+ tableName
2046
+ } = this.parseTableIdentifier(table);
2047
+ const {
2048
+ data: insertedData,
2049
+ error
2050
+ } = await this.supabase.schema(schema).from(tableName).insert(data).select().single();
2051
+ if (error) {
2052
+ throw new Error(`Supabase insert error on ${table}: ${error.message}`);
2053
+ }
2054
+ return insertedData;
2055
+ }
2056
+ /**
2057
+ * Update an existing record by ID
2058
+ *
2059
+ * @param table - The table name
2060
+ * @param id - The record ID to update
2061
+ * @param data - The data to update
2062
+ * @returns Promise resolving to the updated record
2063
+ */
2064
+ async update(table, id, data) {
2065
+ const {
2066
+ schema,
2067
+ tableName
2068
+ } = this.parseTableIdentifier(table);
2069
+ const {
2070
+ data: updatedData,
2071
+ error
2072
+ } = await this.supabase.schema(schema).from(tableName).update(data).eq("id", id).select().single();
2073
+ if (error) {
2074
+ throw new Error(`Supabase update error on ${table}: ${error.message}`);
2075
+ }
2076
+ return updatedData;
2077
+ }
2078
+ /**
2079
+ * Upsert (insert or update) a record
2080
+ *
2081
+ * @param table - The table name
2082
+ * @param data - The data to upsert
2083
+ * @returns Promise resolving to the upserted record
2084
+ */
2085
+ async upsert(table, data) {
2086
+ const {
2087
+ schema,
2088
+ tableName
2089
+ } = this.parseTableIdentifier(table);
2090
+ const {
2091
+ data: upsertedData,
2092
+ error
2093
+ } = await this.supabase.schema(schema).from(tableName).upsert(data, {
2094
+ onConflict: "id"
2095
+ }).select().single();
2096
+ if (error) {
2097
+ throw new Error(`Supabase upsert error on ${table}: ${error.message}`);
2098
+ }
2099
+ return upsertedData;
2100
+ }
2101
+ /**
2102
+ * Delete a record by ID
2103
+ *
2104
+ * @param table - The table name
2105
+ * @param id - The record ID to delete
2106
+ * @returns Promise that resolves when deletion is complete
2107
+ */
2108
+ async delete(table, id) {
2109
+ const {
2110
+ schema,
2111
+ tableName
2112
+ } = this.parseTableIdentifier(table);
2113
+ const {
2114
+ error
2115
+ } = await this.supabase.schema(schema).from(tableName).delete().eq("id", id);
2116
+ if (error) {
2117
+ throw new Error(`Supabase delete error on ${table}: ${error.message}`);
2118
+ }
2119
+ }
2120
+ // ===========================================================================
2121
+ // Subscription (Real-time)
2122
+ // ===========================================================================
2123
+ /**
2124
+ * Subscribe to real-time changes on a query
2125
+ *
2126
+ * @param table - The table name to watch
2127
+ * @param options - Query options to filter what to watch
2128
+ * @param callback - Function called with updated data
2129
+ * @returns Unsubscribe function
2130
+ */
2131
+ subscribe(table, options, callback) {
2132
+ const {
2133
+ schema,
2134
+ tableName
2135
+ } = this.parseTableIdentifier(table);
2136
+ const channelName = `v3:${table}:${Date.now()}`;
2137
+ const channel = this.supabase.channel(channelName).on("postgres_changes", {
2138
+ event: "*",
2139
+ schema,
2140
+ table: tableName
2141
+ }, async () => {
2142
+ try {
2143
+ const {
2144
+ data
2145
+ } = await this.query(table, options);
2146
+ callback(data);
2147
+ } catch (error) {
2148
+ console.error(`Supabase subscription refetch error on ${table}:`, error);
2149
+ }
2150
+ }).subscribe();
2151
+ return () => {
2152
+ this.supabase.removeChannel(channel);
2153
+ };
2154
+ }
2155
+ // ===========================================================================
2156
+ // Private Helper Methods
2157
+ // ===========================================================================
2158
+ /**
2159
+ * Apply where clause filters to a Supabase query
2160
+ *
2161
+ * Converts WhereClause to Supabase filter methods:
2162
+ * - Direct value: .eq(field, value)
2163
+ * - { in: [...] }: .in(field, values)
2164
+ * - { gt: n }: .gt(field, n)
2165
+ * - { gte: n }: .gte(field, n)
2166
+ * - { lt: n }: .lt(field, n)
2167
+ * - { lte: n }: .lte(field, n)
2168
+ * - { like: s }: .ilike(field, s)
2169
+ * - { is: null }: .is(field, null)
2170
+ * - { neq: v }: .neq(field, v) or .not(field, "is", null)
2171
+ * - { notIn: [...] }: .not().in(field, values)
2172
+ *
2173
+ * @param query - The Supabase query builder
2174
+ * @param where - The where clause to apply
2175
+ * @returns The query with filters applied
2176
+ */
2177
+ applyWhereClause(query, where) {
2178
+ for (const [field, condition] of Object.entries(where)) {
2179
+ if (condition === null) {
2180
+ query = query.is(field, null);
2181
+ } else if (typeof condition === "string" || typeof condition === "number" || typeof condition === "boolean") {
2182
+ query = query.eq(field, condition);
2183
+ } else if (typeof condition === "object") {
2184
+ const operators = condition;
2185
+ if (operators.in !== void 0) {
2186
+ query = query.in(field, operators.in);
2187
+ }
2188
+ if (operators.gt !== void 0) {
2189
+ query = query.gt(field, operators.gt);
2190
+ }
2191
+ if (operators.gte !== void 0) {
2192
+ query = query.gte(field, operators.gte);
2193
+ }
2194
+ if (operators.lt !== void 0) {
2195
+ query = query.lt(field, operators.lt);
2196
+ }
2197
+ if (operators.lte !== void 0) {
2198
+ query = query.lte(field, operators.lte);
2199
+ }
2200
+ if (operators.like !== void 0) {
2201
+ query = query.ilike(field, operators.like);
2202
+ }
2203
+ if (operators.is !== void 0) {
2204
+ query = query.is(field, null);
2205
+ }
2206
+ if (operators.neq !== void 0) {
2207
+ if (operators.neq === null) {
2208
+ query = query.not(field, "is", null);
2209
+ } else {
2210
+ query = query.neq(field, operators.neq);
2211
+ }
2212
+ }
2213
+ if (operators.notIn !== void 0) {
2214
+ query = query.not(field, "in", `(${operators.notIn.join(",")})`);
2215
+ }
2216
+ }
2217
+ }
2218
+ return query;
2219
+ }
2220
+ };
2221
+ function createSupabaseAdapter(supabase, schema) {
2222
+ return new SupabaseAdapter(supabase, schema);
2223
+ }
2224
+
2225
+ // src/supabase-functions.tsx
2226
+ async function getErrorBody(response) {
2227
+ const stream = response.error.context.body;
2228
+ const reader = stream.getReader();
2229
+ const {
2230
+ value
2231
+ } = await reader.read();
2232
+ const text = new TextDecoder().decode(value);
2233
+ let parsed;
2234
+ try {
2235
+ parsed = JSON.parse(text);
2236
+ } catch {
2237
+ parsed = text;
2238
+ }
2239
+ return parsed;
2240
+ }
2241
+
2242
+ // src/useAI.ts
2243
+ import { c as _c11 } from "react/compiler-runtime";
2244
+ function useAI() {
2245
+ const $ = _c11(2);
2246
+ const supabase = useSupabase();
2247
+ let t0;
2248
+ if ($[0] !== supabase) {
2249
+ const generate = async (prompt, context, options) => {
2250
+ const response = await supabase.functions.invoke("ai", {
2251
+ body: {
2252
+ prompt,
2253
+ context,
2254
+ options
2255
+ }
2256
+ });
2257
+ if (response.error) {
2258
+ throw new Error(`Failed to invoke AI function: ${response.error.message}`);
2259
+ }
2260
+ if (response.data?.error) {
2261
+ throw new Error(response.data.error);
2262
+ }
2263
+ if (!response.data?.success) {
2264
+ throw new Error(response.data?.error || "Unknown error occurred");
2265
+ }
2266
+ if (!response.data?.data?.response) {
2267
+ throw new Error("No response from AI");
2268
+ }
2269
+ return response.data.data.response;
2270
+ };
2271
+ t0 = {
2272
+ generate
2273
+ };
2274
+ $[0] = supabase;
2275
+ $[1] = t0;
2276
+ } else {
2277
+ t0 = $[1];
2278
+ }
2279
+ return t0;
2280
+ }
2281
+
2282
+ // src/useServerAvailability.ts
2283
+ import { useState as useState3, useEffect as useEffect3, useCallback } from "react";
2284
+ var CHECK_TIMEOUT = 1e4;
2285
+ var CHECK_INTERVAL = 3e4;
2286
+ function useServerAvailability(options) {
2287
+ const {
2288
+ enabled = true,
2289
+ checkInterval = CHECK_INTERVAL,
2290
+ timeout = CHECK_TIMEOUT
2291
+ } = options || {};
2292
+ const [isAvailable, setIsAvailable] = useState3(null);
2293
+ const [isChecking, setIsChecking] = useState3(false);
2294
+ const [lastChecked, setLastChecked] = useState3(null);
2295
+ const [error, setError] = useState3(null);
2296
+ const checkAvailability = useCallback(async () => {
2297
+ if (!enabled) return;
2298
+ setIsChecking(true);
2299
+ setError(null);
2300
+ try {
2301
+ const supabaseUrl = getSupabaseUrl();
2302
+ const supabaseAnonKey = process.env.SUPABASE_ANON_KEY || process.env.EXPO_PUBLIC_SUPABASE_ANON_KEY;
2303
+ if (!supabaseUrl) {
2304
+ throw new Error("Supabase URL is not configured");
2305
+ }
2306
+ if (!supabaseAnonKey) {
2307
+ throw new Error("Supabase anon key is not configured");
2308
+ }
2309
+ const controller = new AbortController();
2310
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
2311
+ const healthCheckPromise = fetch(`${supabaseUrl}/rest/v1/`, {
2312
+ method: "HEAD",
2313
+ headers: {
2314
+ apikey: supabaseAnonKey
2315
+ },
2316
+ signal: controller.signal
2317
+ }).then((response) => {
2318
+ clearTimeout(timeoutId);
2319
+ return response.status < 500;
2320
+ }).catch((err_0) => {
2321
+ clearTimeout(timeoutId);
2322
+ if (err_0.name === "AbortError") {
2323
+ return false;
2324
+ }
2325
+ return false;
2326
+ });
2327
+ const available = await healthCheckPromise;
2328
+ setIsAvailable(available);
2329
+ setLastChecked(/* @__PURE__ */ new Date());
2330
+ setError(null);
2331
+ } catch (err) {
2332
+ const error_0 = err instanceof Error ? err : new Error("Unknown error checking server availability");
2333
+ setIsAvailable(false);
2334
+ setError(error_0);
2335
+ setLastChecked(/* @__PURE__ */ new Date());
2336
+ } finally {
2337
+ setIsChecking(false);
2338
+ }
2339
+ }, [enabled, timeout]);
2340
+ useEffect3(() => {
2341
+ if (enabled) {
2342
+ checkAvailability();
2343
+ }
2344
+ }, [enabled, checkAvailability]);
2345
+ useEffect3(() => {
2346
+ if (!enabled || isAvailable !== false) return;
2347
+ const intervalId = setInterval(() => {
2348
+ checkAvailability();
2349
+ }, checkInterval);
2350
+ return () => clearInterval(intervalId);
2351
+ }, [enabled, isAvailable, checkInterval, checkAvailability]);
2352
+ return {
2353
+ isAvailable,
2354
+ isChecking,
2355
+ lastChecked,
2356
+ error,
2357
+ checkAvailability
2358
+ };
2359
+ }
2360
+
2361
+ // src/useSearchQuery.ts
2362
+ import { useMemo as useMemo3 } from "react";
2363
+ import React from "react";
2364
+ function useSearchQuery(baseQuery, searchText, columns, options = {
2365
+ isOptional: true,
2366
+ additionCondition: []
2367
+ }) {
2368
+ const original = React.useRef(null);
2369
+ if (original.current?.lastQuery !== baseQuery) {
2370
+ const b = baseQuery;
2371
+ const urlValue = b.url;
2372
+ const url = urlValue ? typeof urlValue === "string" ? new URL(urlValue) : new URL(urlValue.toString()) : new URL("http://localhost");
2373
+ const method = b.method ?? "GET";
2374
+ const headers = b.headers ?? {};
2375
+ const body = method !== "GET" && method !== "HEAD" ? b.body ?? null : null;
2376
+ const signal = b.signal ?? null;
2377
+ original.current = {
2378
+ lastQuery: baseQuery,
2379
+ original: {
2380
+ url,
2381
+ method,
2382
+ headers,
2383
+ body,
2384
+ signal
2385
+ }
2386
+ };
2387
+ }
2388
+ return useMemo3(() => {
2389
+ const qb = baseQuery;
2390
+ const {
2391
+ url: url_0,
2392
+ method: method_0,
2393
+ body: body_0,
2394
+ signal: signal_0
2395
+ } = original.current.original;
2396
+ qb.url = new URL(url_0.toString());
2397
+ qb.method = method_0;
2398
+ if (method_0 !== "GET" && method_0 !== "HEAD") {
2399
+ qb.body = body_0;
2400
+ } else {
2401
+ delete qb.body;
2402
+ }
2403
+ qb.signal = signal_0;
2404
+ const term = searchText.trim();
2405
+ if (term) {
2406
+ const clauses = columns.map((col) => {
2407
+ const [tbl, colName] = col.split(".");
2408
+ return `${colName ?? tbl}.ilike.%${escapeLikePattern(term)}%`;
2409
+ });
2410
+ clauses.push(...options.additionCondition.filter(Boolean));
2411
+ qb.or(clauses.join(","), {
2412
+ referencedTable: columns.find((c) => c.includes("."))?.split(".")[0]
2413
+ });
2414
+ } else if (!options.isOptional) {
2415
+ const conds = options.additionCondition.filter(Boolean);
2416
+ conds?.length ? qb.or(conds.join(",")) : qb.limit(0);
2417
+ }
2418
+ return qb;
2419
+ }, [baseQuery, searchText, columns.join(","), options.isOptional, options.additionCondition.join(",")]);
2420
+ }
2421
+ function escapeLikePattern(text) {
2422
+ return text?.replace(/[%_]/g, "\\$&");
2423
+ }
2424
+
2425
+ // src/useLiveChangeTracking.ts
2426
+ import { c as _c12 } from "react/compiler-runtime";
2427
+ import { useEffect as useEffect4, useState as useState4 } from "react";
2428
+ var import_moment = __toESM(require_moment(), 1);
2429
+ function useLiveChangeTracking(tableName, item, action) {
2430
+ const $ = _c12(12);
2431
+ const [changeLog, setChangeLog] = useState4(null);
2432
+ const [oldItem, setOldItem] = useState4(null);
2433
+ const supabase = useSupabase();
2434
+ let t0;
2435
+ if ($[0] !== item || $[1] !== oldItem || $[2] !== supabase || $[3] !== tableName) {
2436
+ t0 = () => {
2437
+ setChangeLog(null);
2438
+ if (isUsable(item) === false) {
2439
+ return;
2440
+ }
2441
+ if (isUsable(oldItem) === false) {
2442
+ setOldItem(item);
2443
+ return;
2444
+ }
2445
+ const itemId = item.id;
2446
+ if (isUsable(itemId) === false) {
2447
+ return;
2448
+ }
2449
+ const changes = getObjectChanges(oldItem, item);
2450
+ if (Object.keys(changes).length === 0) {
2451
+ return;
2452
+ }
2453
+ supabase.schema("core").from("OperationLog").select().filter("tableName", "eq", tableName).filter("recordId", "eq", itemId).order("changeAt", {
2454
+ ascending: false
2455
+ }).limit(1).single().then((x) => {
2456
+ if (isUsable(x.data) === false) {
2457
+ return;
2458
+ }
2459
+ const data = x.data;
2460
+ if (data.sessionId === UserSessionId) {
2461
+ return;
2462
+ }
2463
+ const changeLog_0 = {
2464
+ modifiedByUserId: data.changeBy,
2465
+ changedOn: import_moment.default.utc(data.changeAt),
2466
+ changes
2467
+ };
2468
+ setChangeLog(changeLog_0);
2469
+ });
2470
+ setOldItem(item);
2471
+ };
2472
+ $[0] = item;
2473
+ $[1] = oldItem;
2474
+ $[2] = supabase;
2475
+ $[3] = tableName;
2476
+ $[4] = t0;
2477
+ } else {
2478
+ t0 = $[4];
2479
+ }
2480
+ let t1;
2481
+ if ($[5] !== item) {
2482
+ t1 = [item];
2483
+ $[5] = item;
2484
+ $[6] = t1;
2485
+ } else {
2486
+ t1 = $[6];
2487
+ }
2488
+ useEffect4(t0, t1);
2489
+ let t2;
2490
+ if ($[7] !== action || $[8] !== changeLog) {
2491
+ t2 = () => {
2492
+ if (isUsable(changeLog) && action) {
2493
+ action(changeLog.changes, changeLog);
2494
+ }
2495
+ };
2496
+ $[7] = action;
2497
+ $[8] = changeLog;
2498
+ $[9] = t2;
2499
+ } else {
2500
+ t2 = $[9];
2501
+ }
2502
+ let t3;
2503
+ if ($[10] !== changeLog) {
2504
+ t3 = [changeLog];
2505
+ $[10] = changeLog;
2506
+ $[11] = t3;
2507
+ } else {
2508
+ t3 = $[11];
2509
+ }
2510
+ useEffect4(t2, t3);
2511
+ return changeLog;
2512
+ }
2513
+
2514
+ // src/useLatestOperationLog.ts
2515
+ import { c as _c13 } from "react/compiler-runtime";
2516
+ function useLatestOperationLog(tableName, recordId) {
2517
+ const $ = _c13(8);
2518
+ const supabase = useSupabase();
2519
+ const t0 = supabase;
2520
+ let t1;
2521
+ if ($[0] !== recordId || $[1] !== t0 || $[2] !== tableName) {
2522
+ t1 = t0.schema("core").from("OperationLog").select(OperationLog.defaultQuery).eq("recordId", String(recordId)).eq("tableName", tableName).order("changeAt", {
2523
+ ascending: false
2524
+ }).limit(1).maybeSingle();
2525
+ $[0] = recordId;
2526
+ $[1] = t0;
2527
+ $[2] = tableName;
2528
+ $[3] = t1;
2529
+ } else {
2530
+ t1 = $[3];
2531
+ }
2532
+ let t2;
2533
+ if ($[4] !== recordId) {
2534
+ t2 = isUsable(recordId);
2535
+ $[4] = recordId;
2536
+ $[5] = t2;
2537
+ } else {
2538
+ t2 = $[5];
2539
+ }
2540
+ let t3;
2541
+ if ($[6] !== t2) {
2542
+ t3 = {
2543
+ refetchOnMount: true,
2544
+ refetchOnWindowFocus: true,
2545
+ staleTime: 0,
2546
+ enabled: t2
2547
+ };
2548
+ $[6] = t2;
2549
+ $[7] = t3;
2550
+ } else {
2551
+ t3 = $[7];
2552
+ }
2553
+ return useDbQuery(t1, t3);
2554
+ }
2555
+
2556
+ // src/useAutosaveState.ts
2557
+ import { useCallback as useCallback2, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef5, useState as useState5 } from "react";
2558
+ function newTimeActivity(date) {
2559
+ return {
2560
+ activityDate: date.clone().startOf("day").toISOString(true),
2561
+ description: "",
2562
+ hasRequestBillableChange: false,
2563
+ hasRequestVerification: false,
2564
+ hours: 0,
2565
+ userNotes: "",
2566
+ adminNotes: "",
2567
+ userId: null,
2568
+ clientId: null,
2569
+ projectId: null,
2570
+ workingPhaseId: null,
2571
+ roleId: null,
2572
+ taskId: null,
2573
+ subtaskId: null,
2574
+ weeklyTimesheetId: null,
2575
+ id: null,
2576
+ BillingDetails: {
2577
+ status: "Unknown",
2578
+ id: null,
2579
+ orderHint: "",
2580
+ chargeTableId: null,
2581
+ cosmosId: null,
2582
+ amount: 0,
2583
+ rate: 0,
2584
+ type: "TimeActivity"
2585
+ }
2586
+ };
2587
+ }
2588
+ function getNewValue(action, prevState) {
2589
+ return typeof action === "function" ? action(prevState) : action;
2590
+ }
2591
+ function useAutosaveState(relation, defaultValue, options) {
2592
+ const [value, setValue] = useState5(() => defaultValue);
2593
+ const [baseValue, setBaseValue] = useState5(() => defaultValue);
2594
+ const baseValueRef = useRef5(defaultValue);
2595
+ const pendingChangesRef = useRef5(/* @__PURE__ */ new Map());
2596
+ const currentId = useRef5(null);
2597
+ const newOptions = useMemo4(() => options ? {
2598
+ ...options,
2599
+ primaryKeys: options.primaryKeys ?? ["id"]
2600
+ } : {
2601
+ delay: 200,
2602
+ primaryKeys: ["id"]
2603
+ }, [options]);
2604
+ const upsertMutation = useDbUpsert(relation, {
2605
+ invalidateTables: [relation]
2606
+ });
2607
+ const saveEntityChanges = useCallback2(async (entityId) => {
2608
+ if (__DEV__) {
2609
+ console.log("[Autosave] saveEntityChanges called:", {
2610
+ entityId,
2611
+ relation,
2612
+ hasPendingEntry: pendingChangesRef.current.has(entityId)
2613
+ });
2614
+ }
2615
+ const pending = pendingChangesRef.current.get(entityId);
2616
+ if (!pending) {
2617
+ if (__DEV__) {
2618
+ console.log("[Autosave] No pending changes found for entity:", entityId);
2619
+ }
2620
+ return;
2621
+ }
2622
+ const changes = diff(pending.baseValue, pending.currentValue);
2623
+ if (__DEV__) {
2624
+ console.log("[Autosave] Computed diff:", {
2625
+ entityId,
2626
+ relation,
2627
+ changeKeys: Object.keys(changes),
2628
+ changes,
2629
+ baseValue: pending.baseValue,
2630
+ currentValue: pending.currentValue
2631
+ });
2632
+ }
2633
+ if (Object.keys(changes).length === 0) {
2634
+ if (__DEV__) {
2635
+ console.log("[Autosave] No changes detected, skipping save for:", entityId);
2636
+ }
2637
+ pendingChangesRef.current.delete(entityId);
2638
+ return;
2639
+ }
2640
+ const patch = {
2641
+ ...changes,
2642
+ id: entityId
2643
+ };
2644
+ const finalPatch = newOptions.transformBeforeMutation ? newOptions.transformBeforeMutation(patch) : patch;
2645
+ if (__DEV__) {
2646
+ console.log("[Autosave] Calling mutateAsync:", {
2647
+ entityId,
2648
+ relation,
2649
+ patch,
2650
+ finalPatch,
2651
+ hasTransform: !!newOptions.transformBeforeMutation
2652
+ });
2653
+ }
2654
+ try {
2655
+ const result = await upsertMutation.mutateAsync(finalPatch);
2656
+ if (__DEV__) {
2657
+ console.log("[Autosave] mutateAsync SUCCESS:", {
2658
+ entityId,
2659
+ relation,
2660
+ finalPatch,
2661
+ result
2662
+ });
2663
+ }
2664
+ pendingChangesRef.current.delete(entityId);
2665
+ } catch (error) {
2666
+ if (__DEV__) {
2667
+ console.error("[Autosave] mutateAsync FAILED:", {
2668
+ entityId,
2669
+ relation,
2670
+ finalPatch,
2671
+ error,
2672
+ errorMessage: error instanceof Error ? error.message : String(error),
2673
+ errorStack: error instanceof Error ? error.stack : void 0
2674
+ });
2675
+ }
2676
+ throw error;
2677
+ }
2678
+ }, [relation, upsertMutation, newOptions.transformBeforeMutation]);
2679
+ const updateValue = useCallback2((update) => {
2680
+ setValue((prev) => {
2681
+ const newValue = getNewValue(update, prev);
2682
+ const entityId_0 = newValue.id;
2683
+ if (!entityId_0) return newValue;
2684
+ let pending_0 = pendingChangesRef.current.get(entityId_0);
2685
+ if (!pending_0) {
2686
+ pending_0 = {
2687
+ baseValue: baseValueRef.current,
2688
+ currentValue: newValue,
2689
+ timeoutId: null
2690
+ };
2691
+ pendingChangesRef.current.set(entityId_0, pending_0);
2692
+ if (__DEV__) {
2693
+ console.log("[Autosave] Created new pending entry using baseValueRef:", {
2694
+ entityId: entityId_0,
2695
+ baseValueId: baseValueRef.current?.id
2696
+ });
2697
+ }
2698
+ } else {
2699
+ pending_0.currentValue = newValue;
2700
+ }
2701
+ if (pending_0.timeoutId) {
2702
+ clearTimeout(pending_0.timeoutId);
2703
+ }
2704
+ pending_0.timeoutId = setTimeout(() => {
2705
+ saveEntityChanges(entityId_0);
2706
+ }, newOptions.delay);
2707
+ return newValue;
2708
+ });
2709
+ }, [saveEntityChanges, newOptions.delay]);
2710
+ const setNewEntity = useCallback2((newEntity) => {
2711
+ baseValueRef.current = newEntity;
2712
+ if (__DEV__) {
2713
+ console.log("[Autosave] setNewEntity - baseValueRef updated synchronously:", {
2714
+ entityId: newEntity.id,
2715
+ relation
2716
+ });
2717
+ }
2718
+ setValue(newEntity);
2719
+ setBaseValue(newEntity);
2720
+ currentId.current = newEntity.id;
2721
+ }, [relation]);
2722
+ useEffect5(() => {
2723
+ return () => {
2724
+ pendingChangesRef.current.forEach((pending_1) => {
2725
+ if (pending_1.timeoutId) clearTimeout(pending_1.timeoutId);
2726
+ });
2727
+ };
2728
+ }, []);
2729
+ const saveCurrentValue = useCallback2(async () => {
2730
+ if (currentId.current) {
2731
+ await saveEntityChanges(currentId.current);
2732
+ }
2733
+ }, [saveEntityChanges]);
2734
+ return [value, updateValue, upsertMutation, setValue, setNewEntity, saveCurrentValue];
2735
+ }
2736
+
2737
+ // src/useToastError.ts
2738
+ import { c as _c14 } from "react/compiler-runtime";
2739
+ import { useEffect as useEffect6 } from "react";
2740
+ import { useToast } from "@pol-studios/hooks/toast";
2741
+ function useToastError(mutation) {
2742
+ const $ = _c14(5);
2743
+ const toast = useToast();
2744
+ let t0;
2745
+ if ($[0] !== mutation.error || $[1] !== toast) {
2746
+ t0 = () => {
2747
+ if (isUsable(mutation.error) === false) {
2748
+ return;
2749
+ }
2750
+ toast.toast({
2751
+ title: "Error",
2752
+ description: mutation.error.message
2753
+ });
2754
+ };
2755
+ $[0] = mutation.error;
2756
+ $[1] = toast;
2757
+ $[2] = t0;
2758
+ } else {
2759
+ t0 = $[2];
2760
+ }
2761
+ let t1;
2762
+ if ($[3] !== mutation.error) {
2763
+ t1 = [mutation.error];
2764
+ $[3] = mutation.error;
2765
+ $[4] = t1;
2766
+ } else {
2767
+ t1 = $[4];
2768
+ }
2769
+ useEffect6(t0, t1);
2770
+ return mutation;
2771
+ }
2772
+
2773
+ // src/advance-query.tsx
2774
+ async function executeAdvanceQuery(supabase, query, filterLayer) {
2775
+ const parser = new PostgrestParser(query);
2776
+ const filterGroup = {
2777
+ id: filterLayer.id,
2778
+ op: filterLayer.op,
2779
+ not: filterLayer.not,
2780
+ filters: filterLayer.filters.map(normalizeFilter).filter((f) => f !== null)
2781
+ };
2782
+ const pagination = {
2783
+ offset: void 0,
2784
+ limit: void 0
2785
+ };
2786
+ const sort = [...filterLayer.sort || []];
2787
+ const searchParams = Array.from(parser.searchParams.entries());
2788
+ searchParams.forEach(([k, v]) => {
2789
+ if (k.includes("offset")) {
2790
+ pagination.offset = Number(v);
2791
+ return;
2792
+ }
2793
+ if (k.includes("limit")) {
2794
+ pagination.limit = Number(v);
2795
+ return;
2796
+ }
2797
+ if (k.includes("order")) {
2798
+ const orderColumns = v.split(",");
2799
+ orderColumns.forEach((x) => {
2800
+ const values2 = x.split(".");
2801
+ sort.push({
2802
+ field: values2[0],
2803
+ direction: values2[1] === "asc" ? "asc" : "desc"
2804
+ });
2805
+ });
2806
+ return;
2807
+ }
2808
+ if (v.includes(".") === false) return;
2809
+ const values = v.split(".");
2810
+ const column = k;
2811
+ const rawCondition = values[0];
2812
+ let condition = "";
2813
+ const value = values[1];
2814
+ if (column == "select") return;
2815
+ switch (rawCondition) {
2816
+ case "eq":
2817
+ condition = "=";
2818
+ break;
2819
+ case "in":
2820
+ condition = "in";
2821
+ break;
2822
+ case "lt":
2823
+ condition = "<";
2824
+ break;
2825
+ case "gt":
2826
+ condition = ">";
2827
+ break;
2828
+ case "lte":
2829
+ condition = "<=";
2830
+ break;
2831
+ case "gte":
2832
+ condition = ">=";
2833
+ break;
2834
+ case "is":
2835
+ condition = "is";
2836
+ break;
2837
+ case "ilike":
2838
+ condition = "ilike";
2839
+ break;
2840
+ case "neq":
2841
+ condition = "=";
2842
+ break;
2843
+ case "like":
2844
+ condition = "contains";
2845
+ break;
2846
+ }
2847
+ filterGroup.filters.push({
2848
+ id: `filter_${column}_${Date.now()}`,
2849
+ field: column,
2850
+ op: condition,
2851
+ value,
2852
+ display: `${column} ${condition} ${value}`
2853
+ });
2854
+ });
2855
+ const stripUIProperties = (obj) => {
2856
+ return JSON.parse(JSON.stringify(obj, (key, value) => {
2857
+ if (key === "display" || key === "info" || key === "options") {
2858
+ return void 0;
2859
+ }
2860
+ return value;
2861
+ }));
2862
+ };
2863
+ const cleanedBody = stripUIProperties({
2864
+ table: parser.table,
2865
+ schema: parser.schema,
2866
+ select: parser.select,
2867
+ filters: filterGroup,
2868
+ pagination,
2869
+ sort,
2870
+ count: "exact"
2871
+ });
2872
+ const response = await supabase.functions.invoke("query", {
2873
+ body: cleanedBody,
2874
+ method: "POST"
2875
+ });
2876
+ if (response.error) {
2877
+ return {
2878
+ data: null,
2879
+ count: null,
2880
+ error: response.error
2881
+ };
2882
+ }
2883
+ return {
2884
+ data: response.data?.data ?? null,
2885
+ count: response.data?.count ?? null,
2886
+ error: null
2887
+ };
2888
+ }
2889
+
2890
+ // src/storage/useStorageUrl.ts
2891
+ var import_moment2 = __toESM(require_moment(), 1);
2892
+ import { useRef as useRef6 } from "react";
2893
+ import { useIndexedDB } from "@pol-studios/hooks/storage";
2894
+ var cacheVersions = /* @__PURE__ */ new Map();
2895
+ var cacheVersionListeners = /* @__PURE__ */ new Map();
2896
+ var retryAttempts = /* @__PURE__ */ new Map();
2897
+ function useStorageUrl() {
2898
+ const db = useIndexedDB({
2899
+ dbName: "polstudios",
2900
+ storeName: "cached-urls"
2901
+ });
2902
+ const storedUrls = useRef6(/* @__PURE__ */ new Map());
2903
+ const supabase = useSupabase();
2904
+ function getCacheVersion(entity) {
2905
+ const key = `${entity.bucketId}${entity.path}`;
2906
+ return cacheVersions.get(key) || 0;
2907
+ }
2908
+ function subscribeToCacheVersion(entity_0, callback) {
2909
+ const key_0 = `${entity_0.bucketId}${entity_0.path}`;
2910
+ if (!cacheVersionListeners.has(key_0)) {
2911
+ cacheVersionListeners.set(key_0, /* @__PURE__ */ new Set());
2912
+ }
2913
+ cacheVersionListeners.get(key_0).add(callback);
2914
+ return () => {
2915
+ cacheVersionListeners.get(key_0)?.delete(callback);
2916
+ };
2917
+ }
2918
+ async function expireCache(entity_1) {
2919
+ const key_1 = `${entity_1.bucketId}${entity_1.path}`;
2920
+ const dbKeys = await db.getAllKeys();
2921
+ const keysToDelete = Array.from(new Set([...Array.from(storedUrls.current.keys()), ...dbKeys].filter((value) => value.startsWith(key_1))));
2922
+ await Promise.all(keysToDelete.map(async (x) => {
2923
+ storedUrls.current.delete(x);
2924
+ await db.removeItem(x);
2925
+ }));
2926
+ const currentVersion = cacheVersions.get(key_1) || 0;
2927
+ cacheVersions.set(key_1, currentVersion + 1);
2928
+ const listeners = cacheVersionListeners.get(key_1);
2929
+ if (listeners) {
2930
+ listeners.forEach((callback_0) => {
2931
+ callback_0();
2932
+ });
2933
+ }
2934
+ }
2935
+ async function baseFetchUrl(entity_2, options, isPublic = false) {
2936
+ if (isUsable(entity_2) === false) return;
2937
+ const optionsString = JSON.stringify(options);
2938
+ if (isUsable(entity_2.bucketId) === false) {
2939
+ return;
2940
+ }
2941
+ if (isUsable(entity_2.path) === false) {
2942
+ return;
2943
+ }
2944
+ const key_2 = `${entity_2.bucketId}${entity_2.path}${optionsString ?? ""}-cached-url`;
2945
+ const inMemoryItem = storedUrls.current.get(key_2);
2946
+ let item = inMemoryItem;
2947
+ if (isUsable(inMemoryItem) === false) {
2948
+ item = await db.getItem(key_2) ?? void 0;
2949
+ if (isUsable(item)) {
2950
+ }
2951
+ } else {
2952
+ }
2953
+ if (isUsable(item) && (0, import_moment2.default)(item.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
2954
+ return item.url;
2955
+ }
2956
+ const base = supabase.storage.from(entity_2.bucketId);
2957
+ let download = options?.download;
2958
+ if (typeof options?.download === "string") {
2959
+ const ext = entity_2.path.split(".").pop() ?? "";
2960
+ download = options?.download.endsWith(ext) ? options?.download : options?.download + "." + ext;
2961
+ }
2962
+ const newOptions = options ? {
2963
+ ...options,
2964
+ download
2965
+ } : void 0;
2966
+ const retryKey = `${entity_2.bucketId}/${entity_2.path}`;
2967
+ const currentRetries = retryAttempts.get(retryKey) || 0;
2968
+ let url;
2969
+ if (isPublic) {
2970
+ url = base.getPublicUrl(entity_2.path, newOptions).data.publicUrl;
2971
+ } else {
2972
+ try {
2973
+ console.log("Creating signed URL for", entity_2.path);
2974
+ const result = await base.createSignedUrl(entity_2.path, 60 * 100, newOptions);
2975
+ url = result.data?.signedUrl;
2976
+ if (isUsable(url)) {
2977
+ retryAttempts.delete(retryKey);
2978
+ } else if (currentRetries < 3) {
2979
+ retryAttempts.set(retryKey, currentRetries + 1);
2980
+ throw new Error("Failed to get signed URL");
2981
+ }
2982
+ } catch (error) {
2983
+ if (currentRetries < 3) {
2984
+ retryAttempts.set(retryKey, currentRetries + 1);
2985
+ const delay = Math.min(1e3 * Math.pow(2, currentRetries), 5e3);
2986
+ await new Promise((resolve) => setTimeout(resolve, delay));
2987
+ return baseFetchUrl(entity_2, options, isPublic);
2988
+ }
2989
+ retryAttempts.delete(retryKey);
2990
+ return void 0;
2991
+ }
2992
+ }
2993
+ if (isUsable(url) === false) return url;
2994
+ const cachedUrl = {
2995
+ key: key_2,
2996
+ url,
2997
+ expiresOn: (0, import_moment2.default)().add(60 * 100, "seconds").toISOString(true)
2998
+ };
2999
+ storedUrls.current.set(key_2, cachedUrl);
3000
+ db.setItem(key_2, cachedUrl);
3001
+ return url;
3002
+ }
3003
+ async function fetchUrl(entity_3, options_0) {
3004
+ return baseFetchUrl(entity_3, options_0, false);
3005
+ }
3006
+ async function fetchPublicUrl(entity_4, options_1) {
3007
+ return baseFetchUrl(entity_4, options_1, true);
3008
+ }
3009
+ async function prefetchImage(entity_5, options_2) {
3010
+ const url_0 = await fetchUrl(entity_5, options_2);
3011
+ if (url_0) {
3012
+ new Image().src = url_0;
3013
+ }
3014
+ }
3015
+ async function fetchUrls(entities, options_3) {
3016
+ const results = /* @__PURE__ */ new Map();
3017
+ if (entities.length === 0) return results;
3018
+ const optionsString_0 = JSON.stringify(options_3);
3019
+ const expirySeconds = 60 * 100;
3020
+ const byBucket = /* @__PURE__ */ new Map();
3021
+ for (const entity_6 of entities) {
3022
+ if (!isUsable(entity_6.bucketId) || !isUsable(entity_6.path)) continue;
3023
+ const list = byBucket.get(entity_6.bucketId) ?? [];
3024
+ list.push(entity_6);
3025
+ byBucket.set(entity_6.bucketId, list);
3026
+ }
3027
+ for (const [bucketId, bucketEntities] of byBucket) {
3028
+ const uncached = [];
3029
+ for (const entity_7 of bucketEntities) {
3030
+ const key_3 = `${entity_7.bucketId}${entity_7.path}${optionsString_0 ?? ""}-cached-url`;
3031
+ const entityKey = `${entity_7.bucketId}/${entity_7.path}`;
3032
+ let item_0 = storedUrls.current.get(key_3);
3033
+ if (!isUsable(item_0)) {
3034
+ item_0 = await db.getItem(key_3) ?? void 0;
3035
+ }
3036
+ if (isUsable(item_0) && (0, import_moment2.default)(item_0.expiresOn).isAfter((0, import_moment2.default)().add(-1 * 60, "seconds"))) {
3037
+ results.set(entityKey, item_0.url);
3038
+ } else {
3039
+ uncached.push(entity_7);
3040
+ }
3041
+ }
3042
+ if (uncached.length > 0) {
3043
+ const paths = uncached.map((e) => e.path);
3044
+ const base_0 = supabase.storage.from(bucketId);
3045
+ try {
3046
+ console.log("Signed URLs created");
3047
+ const {
3048
+ data,
3049
+ error: error_0
3050
+ } = await base_0.createSignedUrls(paths, expirySeconds);
3051
+ if (!error_0 && data) {
3052
+ const expiresOn = (0, import_moment2.default)().add(expirySeconds, "seconds").toISOString(true);
3053
+ for (let i = 0; i < uncached.length; i++) {
3054
+ const entity_9 = uncached[i];
3055
+ const urlData = data[i];
3056
+ const entityKey_1 = `${entity_9.bucketId}/${entity_9.path}`;
3057
+ const cacheKey = `${entity_9.bucketId}${entity_9.path}${optionsString_0 ?? ""}-cached-url`;
3058
+ if (urlData?.signedUrl) {
3059
+ results.set(entityKey_1, urlData.signedUrl);
3060
+ const cachedUrl_0 = {
3061
+ key: cacheKey,
3062
+ url: urlData.signedUrl,
3063
+ expiresOn
3064
+ };
3065
+ storedUrls.current.set(cacheKey, cachedUrl_0);
3066
+ db.setItem(cacheKey, cachedUrl_0);
3067
+ } else {
3068
+ results.set(entityKey_1, void 0);
3069
+ }
3070
+ }
3071
+ } else {
3072
+ for (const entity_10 of uncached) {
3073
+ const entityKey_2 = `${entity_10.bucketId}/${entity_10.path}`;
3074
+ const url_2 = await fetchUrl(entity_10, options_3);
3075
+ results.set(entityKey_2, url_2);
3076
+ }
3077
+ }
3078
+ } catch {
3079
+ for (const entity_8 of uncached) {
3080
+ const entityKey_0 = `${entity_8.bucketId}/${entity_8.path}`;
3081
+ const url_1 = await fetchUrl(entity_8, options_3);
3082
+ results.set(entityKey_0, url_1);
3083
+ }
3084
+ }
3085
+ }
3086
+ }
3087
+ return results;
3088
+ }
3089
+ return {
3090
+ fetchUrl,
3091
+ fetchUrls,
3092
+ prefetchImage,
3093
+ fetchPublicUrl,
3094
+ expireCache,
3095
+ getCacheVersion,
3096
+ subscribeToCacheVersion
3097
+ };
3098
+ }
3099
+
3100
+ // src/storage/useStoragePath.ts
3101
+ import { c as _c15 } from "react/compiler-runtime";
3102
+ import { useEffect as useEffect7, useState as useState6 } from "react";
3103
+ function getContentType(metadata, path) {
3104
+ if (metadata?.contentType) {
3105
+ return metadata.contentType;
3106
+ }
3107
+ const ext = path.split(".").pop()?.toUpperCase();
3108
+ return ext || "Unknown";
3109
+ }
3110
+ function useStoragePath(storagePath, bucketId, t0) {
3111
+ const $ = _c15(40);
3112
+ let t1;
3113
+ if ($[0] !== t0) {
3114
+ t1 = t0 === void 0 ? {} : t0;
3115
+ $[0] = t0;
3116
+ $[1] = t1;
3117
+ } else {
3118
+ t1 = $[1];
3119
+ }
3120
+ const options = t1;
3121
+ const {
3122
+ fetchMetadata: t2,
3123
+ transform,
3124
+ download
3125
+ } = options;
3126
+ const fetchMetadata = t2 === void 0 ? true : t2;
3127
+ const [url, setUrl] = useState6(null);
3128
+ const [error, setError] = useState6(null);
3129
+ const {
3130
+ fetchUrl
3131
+ } = useStorageUrl();
3132
+ const supabase = useSupabase();
3133
+ let t3;
3134
+ if ($[2] !== bucketId || $[3] !== download || $[4] !== fetchUrl || $[5] !== storagePath || $[6] !== transform) {
3135
+ t3 = () => {
3136
+ if (!isUsable(storagePath) || !isUsable(bucketId)) {
3137
+ setUrl(null);
3138
+ return;
3139
+ }
3140
+ let cancelled = false;
3141
+ fetchUrl({
3142
+ bucketId,
3143
+ path: storagePath
3144
+ }, {
3145
+ transform,
3146
+ download
3147
+ }).then((signedUrl) => {
3148
+ if (!cancelled) {
3149
+ setUrl(signedUrl ?? null);
3150
+ setError(null);
3151
+ }
3152
+ }).catch((err) => {
3153
+ if (!cancelled) {
3154
+ setError(err instanceof Error ? err : new Error(String(err)));
3155
+ setUrl(null);
3156
+ }
3157
+ });
3158
+ return () => {
3159
+ cancelled = true;
3160
+ };
3161
+ };
3162
+ $[2] = bucketId;
3163
+ $[3] = download;
3164
+ $[4] = fetchUrl;
3165
+ $[5] = storagePath;
3166
+ $[6] = transform;
3167
+ $[7] = t3;
3168
+ } else {
3169
+ t3 = $[7];
3170
+ }
3171
+ let t4;
3172
+ if ($[8] !== transform) {
3173
+ t4 = JSON.stringify(transform);
3174
+ $[8] = transform;
3175
+ $[9] = t4;
3176
+ } else {
3177
+ t4 = $[9];
3178
+ }
3179
+ let t5;
3180
+ if ($[10] !== bucketId || $[11] !== download || $[12] !== storagePath || $[13] !== t4) {
3181
+ t5 = [storagePath, bucketId, t4, download];
3182
+ $[10] = bucketId;
3183
+ $[11] = download;
3184
+ $[12] = storagePath;
3185
+ $[13] = t4;
3186
+ $[14] = t5;
3187
+ } else {
3188
+ t5 = $[14];
3189
+ }
3190
+ useEffect7(t3, t5);
3191
+ let t6;
3192
+ if ($[15] !== bucketId || $[16] !== storagePath || $[17] !== supabase) {
3193
+ t6 = supabase.schema("storage").from("objects").select("metadata").eq("bucket_id", bucketId).eq("name", storagePath ?? "").maybeSingle();
3194
+ $[15] = bucketId;
3195
+ $[16] = storagePath;
3196
+ $[17] = supabase;
3197
+ $[18] = t6;
3198
+ } else {
3199
+ t6 = $[18];
3200
+ }
3201
+ const storageQuery = t6;
3202
+ let t7;
3203
+ if ($[19] !== bucketId || $[20] !== fetchMetadata || $[21] !== storagePath) {
3204
+ t7 = fetchMetadata && isUsable(storagePath) && isUsable(bucketId);
3205
+ $[19] = bucketId;
3206
+ $[20] = fetchMetadata;
3207
+ $[21] = storagePath;
3208
+ $[22] = t7;
3209
+ } else {
3210
+ t7 = $[22];
3211
+ }
3212
+ let t8;
3213
+ if ($[23] !== t7) {
3214
+ t8 = {
3215
+ enabled: t7
3216
+ };
3217
+ $[23] = t7;
3218
+ $[24] = t8;
3219
+ } else {
3220
+ t8 = $[24];
3221
+ }
3222
+ const metadataRequest = useDbQuery(storageQuery, t8);
3223
+ const metadata = metadataRequest.data?.metadata ?? null;
3224
+ const t9 = storagePath ?? "";
3225
+ let t10;
3226
+ if ($[25] !== metadata || $[26] !== t9) {
3227
+ t10 = getContentType(metadata, t9);
3228
+ $[25] = metadata;
3229
+ $[26] = t9;
3230
+ $[27] = t10;
3231
+ } else {
3232
+ t10 = $[27];
3233
+ }
3234
+ const contentType = t10;
3235
+ let t11;
3236
+ if ($[28] !== error || $[29] !== fetchMetadata || $[30] !== metadataRequest.isFetching || $[31] !== storagePath || $[32] !== url) {
3237
+ t11 = isUsable(storagePath) && url === null && error === null || fetchMetadata && metadataRequest.isFetching;
3238
+ $[28] = error;
3239
+ $[29] = fetchMetadata;
3240
+ $[30] = metadataRequest.isFetching;
3241
+ $[31] = storagePath;
3242
+ $[32] = url;
3243
+ $[33] = t11;
3244
+ } else {
3245
+ t11 = $[33];
3246
+ }
3247
+ const isLoading = t11;
3248
+ let t12;
3249
+ if ($[34] !== contentType || $[35] !== error || $[36] !== isLoading || $[37] !== metadata || $[38] !== url) {
3250
+ t12 = {
3251
+ url,
3252
+ metadata,
3253
+ contentType,
3254
+ isLoading,
3255
+ error
3256
+ };
3257
+ $[34] = contentType;
3258
+ $[35] = error;
3259
+ $[36] = isLoading;
3260
+ $[37] = metadata;
3261
+ $[38] = url;
3262
+ $[39] = t12;
3263
+ } else {
3264
+ t12 = $[39];
3265
+ }
3266
+ return t12;
3267
+ }
3268
+
3269
+ // src/storage/bucketConfig.ts
3270
+ var BUCKETS = {
3271
+ AVATARS: "avatars",
3272
+ FIXTURE_CATALOG_COVER: "fixture-catalog-cover",
3273
+ FIXTURE_ATTACHMENTS: "fixture-attachments",
3274
+ UNIT_DOCUMENTATION: "unit-documentation-attachments",
3275
+ DATASHEETS: "datasheets",
3276
+ PATTERNS: "patterns",
3277
+ LOGOS: "logos",
3278
+ RECEIPTS: "receipts",
3279
+ TICKET_ATTACHMENTS: "ticket-attachment",
3280
+ PROCESS_RESULTS: "process-results",
3281
+ DATA_EXCHANGE_IMPORTS: "data-exchange-imports",
3282
+ EMAIL_TEMPLATES: "email-templates",
3283
+ EMAIL_TEMPLATES_ASSETS: "email-templates-assets"
3284
+ };
3285
+
3286
+ // src/utilities/query-utils.ts
3287
+ function createInCondition(column, values) {
3288
+ let condition = "";
3289
+ if (values.length > 2e3) {
3290
+ throw new Error("Too many values to create in condition");
3291
+ }
3292
+ chunkArray(values, 99).forEach((x, index) => {
3293
+ if (index == 0) {
3294
+ condition = `${column}.in.(${x.join(",")})`;
3295
+ return;
3296
+ }
3297
+ condition += `,${column}.in.(${x.join(",")})`;
3298
+ });
3299
+ return condition;
3300
+ }
3301
+
3302
+ // src/changelog/useChangelogMutations.ts
3303
+ import { c as _c16 } from "react/compiler-runtime";
3304
+ var useUpsertChangelog = () => {
3305
+ const $ = _c16(1);
3306
+ let t0;
3307
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3308
+ t0 = {
3309
+ invalidateTables: ["Changelog", "ChangelogEntry", "ChangelogMedia"]
3310
+ };
3311
+ $[0] = t0;
3312
+ } else {
3313
+ t0 = $[0];
3314
+ }
3315
+ return useDbUpsert("Changelog", t0);
3316
+ };
3317
+ var useDeleteChangelog = () => {
3318
+ return useDbDelete("Changelog");
3319
+ };
3320
+ var useUpsertChangelogEntry = () => {
3321
+ const $ = _c16(1);
3322
+ let t0;
3323
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3324
+ t0 = {
3325
+ invalidateTables: ["ChangelogEntry", "ChangelogMedia"]
3326
+ };
3327
+ $[0] = t0;
3328
+ } else {
3329
+ t0 = $[0];
3330
+ }
3331
+ return useDbUpsert("ChangelogEntry", t0);
3332
+ };
3333
+ var useMultiUpsertChangelogEntries = () => {
3334
+ const $ = _c16(1);
3335
+ let t0;
3336
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3337
+ t0 = ["id"];
3338
+ $[0] = t0;
3339
+ } else {
3340
+ t0 = $[0];
3341
+ }
3342
+ return useDbMultiUpsert("ChangelogEntry", t0, "*, ChangelogMedia (*)");
3343
+ };
3344
+ var useDeleteChangelogEntry = () => {
3345
+ return useDbDelete("ChangelogEntry");
3346
+ };
3347
+ var useMultiDeleteChangelogEntries = () => {
3348
+ return useDbMultiDelete("ChangelogEntry");
3349
+ };
3350
+ var useUpsertChangelogMedia = () => {
3351
+ const $ = _c16(1);
3352
+ let t0;
3353
+ if ($[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel")) {
3354
+ t0 = {
3355
+ invalidateTables: ["ChangelogMedia"]
3356
+ };
3357
+ $[0] = t0;
3358
+ } else {
3359
+ t0 = $[0];
3360
+ }
3361
+ return useDbUpsert("ChangelogMedia", t0);
3362
+ };
3363
+ var useDeleteChangelogMedia = () => {
3364
+ return useDbDelete("ChangelogMedia");
3365
+ };
3366
+ var useUploadChangelogMedia = () => {
3367
+ return {
3368
+ mutateAsync: async () => ({
3369
+ path: "",
3370
+ publicUrl: ""
3371
+ })
3372
+ };
3373
+ };
3374
+
3375
+ // src/changelog/useChangelogQuery.ts
3376
+ import { c as _c17 } from "react/compiler-runtime";
3377
+ var useChangelogs = (options) => {
3378
+ const supabase = useSupabase();
3379
+ const query = supabase.from("Changelog").select(`
3380
+ *,
3381
+ ChangelogEntry (
3382
+ *,
3383
+ ChangelogMedia (*)
3384
+ )
3385
+ `).order("releaseDate", {
3386
+ ascending: false
3387
+ }).order("order", {
3388
+ foreignTable: "ChangelogEntry",
3389
+ ascending: true
3390
+ }).order("order", {
3391
+ foreignTable: "ChangelogEntry.ChangelogMedia",
3392
+ ascending: true
3393
+ });
3394
+ if (options?.realtime) {
3395
+ return useDbRealtimeQuery(query, {
3396
+ crossOrganization: true
3397
+ });
3398
+ }
3399
+ return useDbQuery(query, {
3400
+ crossOrganization: true
3401
+ });
3402
+ };
3403
+ var usePublishedChangelogs = (options) => {
3404
+ const supabase = useSupabase();
3405
+ const query = supabase.from("Changelog").select(`
3406
+ *,
3407
+ ChangelogEntry (
3408
+ *,
3409
+ ChangelogMedia (*)
3410
+ )
3411
+ `).eq("isPublished", true).order("releaseDate", {
3412
+ ascending: false
3413
+ }).order("order", {
3414
+ foreignTable: "ChangelogEntry",
3415
+ ascending: true
3416
+ }).order("order", {
3417
+ foreignTable: "ChangelogEntry.ChangelogMedia",
3418
+ ascending: true
3419
+ });
3420
+ if (options?.realtime) {
3421
+ return useDbRealtimeQuery(query, {
3422
+ crossOrganization: true
3423
+ });
3424
+ }
3425
+ return useDbQuery(query, {
3426
+ crossOrganization: true
3427
+ });
3428
+ };
3429
+ var useChangelogById = (id) => {
3430
+ const $ = _c17(5);
3431
+ const supabase = useSupabase();
3432
+ let t0;
3433
+ if ($[0] !== id || $[1] !== supabase) {
3434
+ t0 = supabase.from("Changelog").select("\n *,\n ChangelogEntry (\n *,\n ChangelogMedia (*)\n )\n ").eq("id", id).order("order", {
3435
+ foreignTable: "ChangelogEntry",
3436
+ ascending: true
3437
+ }).order("order", {
3438
+ foreignTable: "ChangelogEntry.ChangelogMedia",
3439
+ ascending: true
3440
+ }).single();
3441
+ $[0] = id;
3442
+ $[1] = supabase;
3443
+ $[2] = t0;
3444
+ } else {
3445
+ t0 = $[2];
3446
+ }
3447
+ const t1 = !!id;
3448
+ let t2;
3449
+ if ($[3] !== t1) {
3450
+ t2 = {
3451
+ enabled: t1,
3452
+ crossOrganization: true
3453
+ };
3454
+ $[3] = t1;
3455
+ $[4] = t2;
3456
+ } else {
3457
+ t2 = $[4];
3458
+ }
3459
+ return useDbQuery(t0, t2);
3460
+ };
3461
+ var useChangelogBySlug = (slug) => {
3462
+ const $ = _c17(5);
3463
+ const supabase = useSupabase();
3464
+ let t0;
3465
+ if ($[0] !== slug || $[1] !== supabase) {
3466
+ t0 = supabase.from("Changelog").select("\n *,\n ChangelogEntry (\n *,\n ChangelogMedia (*)\n )\n ").eq("slug", slug).order("order", {
3467
+ foreignTable: "ChangelogEntry",
3468
+ ascending: true
3469
+ }).order("order", {
3470
+ foreignTable: "ChangelogEntry.ChangelogMedia",
3471
+ ascending: true
3472
+ }).single();
3473
+ $[0] = slug;
3474
+ $[1] = supabase;
3475
+ $[2] = t0;
3476
+ } else {
3477
+ t0 = $[2];
3478
+ }
3479
+ const t1 = !!slug;
3480
+ let t2;
3481
+ if ($[3] !== t1) {
3482
+ t2 = {
3483
+ enabled: t1,
3484
+ crossOrganization: true
3485
+ };
3486
+ $[3] = t1;
3487
+ $[4] = t2;
3488
+ } else {
3489
+ t2 = $[4];
3490
+ }
3491
+ return useDbQuery(t0, t2);
3492
+ };
3493
+ var useChangelogEntries = (changelogId) => {
3494
+ const $ = _c17(5);
3495
+ const supabase = useSupabase();
3496
+ let t0;
3497
+ if ($[0] !== changelogId || $[1] !== supabase) {
3498
+ t0 = supabase.from("ChangelogEntry").select("*, ChangelogMedia (*)").eq("changelogId", changelogId).order("order", {
3499
+ ascending: true
3500
+ }).order("order", {
3501
+ foreignTable: "ChangelogMedia",
3502
+ ascending: true
3503
+ });
3504
+ $[0] = changelogId;
3505
+ $[1] = supabase;
3506
+ $[2] = t0;
3507
+ } else {
3508
+ t0 = $[2];
3509
+ }
3510
+ const t1 = !!changelogId;
3511
+ let t2;
3512
+ if ($[3] !== t1) {
3513
+ t2 = {
3514
+ enabled: t1,
3515
+ crossOrganization: true
3516
+ };
3517
+ $[3] = t1;
3518
+ $[4] = t2;
3519
+ } else {
3520
+ t2 = $[4];
3521
+ }
3522
+ return useDbQuery(t0, t2);
3523
+ };
3524
+ var useChangelogMedia = (entryId) => {
3525
+ const $ = _c17(5);
3526
+ const supabase = useSupabase();
3527
+ let t0;
3528
+ if ($[0] !== entryId || $[1] !== supabase) {
3529
+ t0 = supabase.from("ChangelogMedia").select("*").eq("changelogEntryId", entryId).order("order", {
3530
+ ascending: true
3531
+ });
3532
+ $[0] = entryId;
3533
+ $[1] = supabase;
3534
+ $[2] = t0;
3535
+ } else {
3536
+ t0 = $[2];
3537
+ }
3538
+ const t1 = !!entryId;
3539
+ let t2;
3540
+ if ($[3] !== t1) {
3541
+ t2 = {
3542
+ enabled: t1,
3543
+ crossOrganization: true
3544
+ };
3545
+ $[3] = t1;
3546
+ $[4] = t2;
3547
+ } else {
3548
+ t2 = $[4];
3549
+ }
3550
+ return useDbQuery(t0, t2);
3551
+ };
3552
+
3553
+ // src/nl-training/useFeedbackList.ts
3554
+ import { c as _c18 } from "react/compiler-runtime";
3555
+ import { useQuery as useQuery2 } from "@tanstack/react-query";
3556
+ function useFeedbackList(t0) {
3557
+ const $ = _c18(10);
3558
+ let t1;
3559
+ if ($[0] !== t0) {
3560
+ t1 = t0 === void 0 ? {} : t0;
3561
+ $[0] = t0;
3562
+ $[1] = t1;
3563
+ } else {
3564
+ t1 = $[1];
3565
+ }
3566
+ const params = t1;
3567
+ const supabase = useSupabase();
3568
+ let t2;
3569
+ if ($[2] !== params) {
3570
+ t2 = ["feedback-list", params];
3571
+ $[2] = params;
3572
+ $[3] = t2;
3573
+ } else {
3574
+ t2 = $[3];
3575
+ }
3576
+ let t3;
3577
+ if ($[4] !== params || $[5] !== supabase) {
3578
+ t3 = async () => {
3579
+ const searchParams = new URLSearchParams();
3580
+ if (params.resolved !== void 0) {
3581
+ searchParams.append("resolved", String(params.resolved));
3582
+ }
3583
+ if (params.status) {
3584
+ searchParams.append("status", params.status);
3585
+ }
3586
+ if (params.limit) {
3587
+ searchParams.append("limit", String(params.limit));
3588
+ }
3589
+ if (params.offset) {
3590
+ searchParams.append("offset", String(params.offset));
3591
+ }
3592
+ if (params.userId) {
3593
+ searchParams.append("userId", params.userId);
3594
+ }
3595
+ if (params.startDate) {
3596
+ searchParams.append("startDate", params.startDate);
3597
+ }
3598
+ if (params.endDate) {
3599
+ searchParams.append("endDate", params.endDate);
3600
+ }
3601
+ const {
3602
+ data,
3603
+ error
3604
+ } = await supabase.functions.invoke("query", {
3605
+ body: {},
3606
+ method: "GET",
3607
+ headers: {
3608
+ "X-Path": `/query/feedback?${searchParams.toString()}`
3609
+ }
3610
+ });
3611
+ if (error) {
3612
+ throw error;
3613
+ }
3614
+ return data;
3615
+ };
3616
+ $[4] = params;
3617
+ $[5] = supabase;
3618
+ $[6] = t3;
3619
+ } else {
3620
+ t3 = $[6];
3621
+ }
3622
+ let t4;
3623
+ if ($[7] !== t2 || $[8] !== t3) {
3624
+ t4 = {
3625
+ queryKey: t2,
3626
+ queryFn: t3
3627
+ };
3628
+ $[7] = t2;
3629
+ $[8] = t3;
3630
+ $[9] = t4;
3631
+ } else {
3632
+ t4 = $[9];
3633
+ }
3634
+ return useQuery2(t4);
3635
+ }
3636
+
3637
+ // src/nl-training/useSubmitFeedback.ts
3638
+ import { c as _c19 } from "react/compiler-runtime";
3639
+ import { useMutation as useMutation6, useQueryClient } from "@tanstack/react-query";
3640
+ function useSubmitFeedback() {
3641
+ const $ = _c19(7);
3642
+ const supabase = useSupabase();
3643
+ const queryClient = useQueryClient();
3644
+ let t0;
3645
+ if ($[0] !== supabase) {
3646
+ t0 = async (params) => {
3647
+ const {
3648
+ data,
3649
+ error
3650
+ } = await supabase.functions.invoke("query", {
3651
+ body: params,
3652
+ method: "POST",
3653
+ headers: {
3654
+ "X-Path": "/query/feedback"
3655
+ }
3656
+ });
3657
+ if (error) {
3658
+ throw error;
3659
+ }
3660
+ return data;
3661
+ };
3662
+ $[0] = supabase;
3663
+ $[1] = t0;
3664
+ } else {
3665
+ t0 = $[1];
3666
+ }
3667
+ let t1;
3668
+ if ($[2] !== queryClient) {
3669
+ t1 = () => {
3670
+ queryClient.invalidateQueries({
3671
+ queryKey: ["feedback-list"]
3672
+ });
3673
+ };
3674
+ $[2] = queryClient;
3675
+ $[3] = t1;
3676
+ } else {
3677
+ t1 = $[3];
3678
+ }
3679
+ let t2;
3680
+ if ($[4] !== t0 || $[5] !== t1) {
3681
+ t2 = {
3682
+ mutationFn: t0,
3683
+ onSuccess: t1
3684
+ };
3685
+ $[4] = t0;
3686
+ $[5] = t1;
3687
+ $[6] = t2;
3688
+ } else {
3689
+ t2 = $[6];
3690
+ }
3691
+ return useMutation6(t2);
3692
+ }
3693
+
3694
+ // src/nl-training/useApplyFeedback.ts
3695
+ import { c as _c20 } from "react/compiler-runtime";
3696
+ import { useMutation as useMutation7, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
3697
+ function useApplyFeedback() {
3698
+ const $ = _c20(7);
3699
+ const supabase = useSupabase();
3700
+ const queryClient = useQueryClient2();
3701
+ let t0;
3702
+ if ($[0] !== supabase) {
3703
+ t0 = async (memoryId) => {
3704
+ const {
3705
+ data,
3706
+ error
3707
+ } = await supabase.functions.invoke("query", {
3708
+ body: {},
3709
+ method: "POST",
3710
+ headers: {
3711
+ "X-Path": `/query/feedback/${memoryId}/apply`
3712
+ }
3713
+ });
3714
+ if (error) {
3715
+ throw error;
3716
+ }
3717
+ return data;
3718
+ };
3719
+ $[0] = supabase;
3720
+ $[1] = t0;
3721
+ } else {
3722
+ t0 = $[1];
3723
+ }
3724
+ let t1;
3725
+ if ($[2] !== queryClient) {
3726
+ t1 = () => {
3727
+ queryClient.invalidateQueries({
3728
+ queryKey: ["feedback-list"]
3729
+ });
3730
+ };
3731
+ $[2] = queryClient;
3732
+ $[3] = t1;
3733
+ } else {
3734
+ t1 = $[3];
3735
+ }
3736
+ let t2;
3737
+ if ($[4] !== t0 || $[5] !== t1) {
3738
+ t2 = {
3739
+ mutationFn: t0,
3740
+ onSuccess: t1
3741
+ };
3742
+ $[4] = t0;
3743
+ $[5] = t1;
3744
+ $[6] = t2;
3745
+ } else {
3746
+ t2 = $[6];
3747
+ }
3748
+ return useMutation7(t2);
3749
+ }
3750
+
3751
+ // src/nl-training/useResolveFeedback.ts
3752
+ import { c as _c21 } from "react/compiler-runtime";
3753
+ import { useMutation as useMutation8, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
3754
+ function useResolveFeedback() {
3755
+ const $ = _c21(7);
3756
+ const supabase = useSupabase();
3757
+ const queryClient = useQueryClient3();
3758
+ let t0;
3759
+ if ($[0] !== supabase) {
3760
+ t0 = async (memoryId) => {
3761
+ const {
3762
+ data,
3763
+ error
3764
+ } = await supabase.functions.invoke("query", {
3765
+ body: {},
3766
+ method: "POST",
3767
+ headers: {
3768
+ "X-Path": `/query/feedback/${memoryId}/resolve`
3769
+ }
3770
+ });
3771
+ if (error) {
3772
+ throw error;
3773
+ }
3774
+ return data;
3775
+ };
3776
+ $[0] = supabase;
3777
+ $[1] = t0;
3778
+ } else {
3779
+ t0 = $[1];
3780
+ }
3781
+ let t1;
3782
+ if ($[2] !== queryClient) {
3783
+ t1 = () => {
3784
+ queryClient.invalidateQueries({
3785
+ queryKey: ["feedback-list"]
3786
+ });
3787
+ };
3788
+ $[2] = queryClient;
3789
+ $[3] = t1;
3790
+ } else {
3791
+ t1 = $[3];
3792
+ }
3793
+ let t2;
3794
+ if ($[4] !== t0 || $[5] !== t1) {
3795
+ t2 = {
3796
+ mutationFn: t0,
3797
+ onSuccess: t1
3798
+ };
3799
+ $[4] = t0;
3800
+ $[5] = t1;
3801
+ $[6] = t2;
3802
+ } else {
3803
+ t2 = $[6];
3804
+ }
3805
+ return useMutation8(t2);
3806
+ }
3807
+
3808
+ export {
3809
+ useDbDelete,
3810
+ useDbInfiniteQuery,
3811
+ useDbInsert,
3812
+ useDbMultiDelete,
3813
+ useDbMultiUpsert,
3814
+ useDbPartialAdvanceQuery,
3815
+ useDbPartialQuery,
3816
+ useDbRealtime,
3817
+ convertFilterToRealtimeQuery,
3818
+ useDbRealtimeQuery,
3819
+ useDbUpdate,
3820
+ useMutationSuccess,
3821
+ useMutationSuccessRN,
3822
+ ADAPTER_STRATEGIES,
3823
+ BackendStatus,
3824
+ AdapterAutoDetector,
3825
+ createAdapterAutoDetector,
3826
+ AdapterRegistry,
3827
+ createAdapterRegistry,
3828
+ SupabaseAdapter,
3829
+ createSupabaseAdapter,
3830
+ getErrorBody,
3831
+ useAI,
3832
+ useServerAvailability,
3833
+ useSearchQuery,
3834
+ useLiveChangeTracking,
3835
+ useLatestOperationLog,
3836
+ newTimeActivity,
3837
+ useAutosaveState,
3838
+ useToastError,
3839
+ executeAdvanceQuery,
3840
+ useStorageUrl,
3841
+ useStoragePath,
3842
+ BUCKETS,
3843
+ createInCondition,
3844
+ useUpsertChangelog,
3845
+ useDeleteChangelog,
3846
+ useUpsertChangelogEntry,
3847
+ useMultiUpsertChangelogEntries,
3848
+ useDeleteChangelogEntry,
3849
+ useMultiDeleteChangelogEntries,
3850
+ useUpsertChangelogMedia,
3851
+ useDeleteChangelogMedia,
3852
+ useUploadChangelogMedia,
3853
+ useChangelogs,
3854
+ usePublishedChangelogs,
3855
+ useChangelogById,
3856
+ useChangelogBySlug,
3857
+ useChangelogEntries,
3858
+ useChangelogMedia,
3859
+ useFeedbackList,
3860
+ useSubmitFeedback,
3861
+ useApplyFeedback,
3862
+ useResolveFeedback
3863
+ };
3864
+ //# sourceMappingURL=chunk-NZON56CB.js.map