@pol-studios/db 1.0.31 → 1.0.34

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