suparisma 0.0.1 → 0.0.3

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 (38) hide show
  1. package/README.md +156 -3
  2. package/dist/config.js +12 -3
  3. package/dist/generators/coreGenerator.js +122 -40
  4. package/dist/generators/hookGenerator.js +16 -7
  5. package/dist/generators/indexGenerator.js +12 -7
  6. package/dist/generators/supabaseClientGenerator.js +5 -5
  7. package/dist/generators/typeGenerator.js +22 -22
  8. package/dist/index.js +103 -25
  9. package/{src/suparisma/generated/useSuparismaUser.ts → dist/suparisma/generated/hooks/useSuparismaUser.js} +19 -35
  10. package/dist/suparisma/generated/index.js +33 -0
  11. package/dist/suparisma/generated/types/UserTypes.js +4 -0
  12. package/dist/suparisma/generated/utils/core.js +1090 -0
  13. package/dist/suparisma/generated/utils/supabase-client.js +8 -0
  14. package/package.json +12 -2
  15. package/prisma/schema.prisma +19 -3
  16. package/tsconfig.json +1 -1
  17. package/src/config.ts +0 -7
  18. package/src/generated/hooks/useSuparismaUser.ts +0 -77
  19. package/src/generated/index.ts +0 -50
  20. package/src/generated/types/UserTypes.ts +0 -400
  21. package/src/generated/utils/core.ts +0 -1413
  22. package/src/generated/utils/supabase-client.ts +0 -7
  23. package/src/generators/coreGenerator.ts +0 -1426
  24. package/src/generators/hookGenerator.ts +0 -110
  25. package/src/generators/indexGenerator.ts +0 -117
  26. package/src/generators/supabaseClientGenerator.ts +0 -24
  27. package/src/generators/typeGenerator.ts +0 -587
  28. package/src/index.ts +0 -339
  29. package/src/parser.ts +0 -134
  30. package/src/suparisma/generated/UserTypes.ts +0 -400
  31. package/src/suparisma/generated/core.ts +0 -1413
  32. package/src/suparisma/generated/hooks/useSuparismaUser.ts +0 -77
  33. package/src/suparisma/generated/index.ts +0 -50
  34. package/src/suparisma/generated/supabase-client-generated.ts +0 -9
  35. package/src/suparisma/generated/types/UserTypes.ts +0 -400
  36. package/src/suparisma/generated/utils/core.ts +0 -1413
  37. package/src/suparisma/generated/utils/supabase-client.ts +0 -7
  38. package/src/types.ts +0 -57
@@ -1,1426 +0,0 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { OUTPUT_DIR } from '../config';
4
-
5
- /**
6
- * Generate core hook factory file
7
- */
8
- export function generateCoreFile(): void {
9
- const coreContent = `// THIS FILE IS AUTO-GENERATED - DO NOT EDIT DIRECTLY
10
- // Edit the generator script instead: scripts/generate-realtime-hooks.ts
11
-
12
- import { useEffect, useState, useCallback, useRef } from 'react';
13
- import { supabase } from '@monorepo/src/lib/supabase';
14
-
15
- /**
16
- * Represents a single search query against a field
17
- * @example
18
- * // Search for users with names containing "john"
19
- * const query = { field: "name", value: "john" };
20
- */
21
- export type SearchQuery = {
22
- /** The field name to search in */
23
- field: string;
24
- /** The search term/value to look for */
25
- value: string;
26
- };
27
-
28
- // Define type for Supabase query builder
29
- export type SupabaseQueryBuilder = ReturnType<ReturnType<typeof supabase.from>['select']>;
30
-
31
- /**
32
- * Advanced filter operators for complex queries
33
- * @example
34
- * // Users older than 21
35
- * { age: { gt: 21 } }
36
- *
37
- * @example
38
- * // Posts with titles containing "news"
39
- * { title: { contains: "news" } }
40
- */
41
- export type FilterOperators<T> = {
42
- /** Equal to value */
43
- equals?: T;
44
- /** Not equal to value */
45
- not?: T;
46
- /** Value is in the array */
47
- in?: T[];
48
- /** Value is not in the array */
49
- notIn?: T[];
50
- /** Less than value */
51
- lt?: T;
52
- /** Less than or equal to value */
53
- lte?: T;
54
- /** Greater than value */
55
- gt?: T;
56
- /** Greater than or equal to value */
57
- gte?: T;
58
- /** String contains value (case insensitive) */
59
- contains?: string;
60
- /** String starts with value (case insensitive) */
61
- startsWith?: string;
62
- /** String ends with value (case insensitive) */
63
- endsWith?: string;
64
- };
65
-
66
- // Type for a single field in an advanced where filter
67
- export type AdvancedWhereInput<T> = {
68
- [K in keyof T]?: T[K] | FilterOperators<T[K]>;
69
- };
70
-
71
- /**
72
- * Configuration options for the Suparisma hooks
73
- * @example
74
- * // Basic usage
75
- * const { data } = useSuparismaUser();
76
- *
77
- * @example
78
- * // With filtering
79
- * const { data } = useSuparismaUser({
80
- * where: { age: { gt: 21 } }
81
- * });
82
- *
83
- * @example
84
- * // With ordering and limits
85
- * const { data } = useSuparismaUser({
86
- * orderBy: { created_at: 'desc' },
87
- * limit: 10
88
- * });
89
- */
90
- export type SuparismaOptions<TWhereInput, TOrderByInput> = {
91
- /** Whether to enable realtime updates (default: true) */
92
- realtime?: boolean;
93
- /** Custom channel name for realtime subscription */
94
- channelName?: string;
95
- /** Type-safe filter for queries and realtime events */
96
- where?: TWhereInput;
97
- /** Legacy string filter (use 'where' instead for type safety) */
98
- realtimeFilter?: string;
99
- /** Type-safe ordering for queries */
100
- orderBy?: TOrderByInput;
101
- /** Limit the number of records returned */
102
- limit?: number;
103
- /** Offset for pagination (skip records) */
104
- offset?: number;
105
- };
106
-
107
- /**
108
- * Return type for database operations
109
- * @example
110
- * const result = await users.create({ name: "John" });
111
- * if (result.error) {
112
- * console.error(result.error);
113
- * } else {
114
- * console.log(result.data);
115
- * }
116
- */
117
- export type ModelResult<T> = Promise<{
118
- data: T;
119
- error: null;
120
- } | {
121
- data: null;
122
- error: Error;
123
- }>;
124
-
125
- /**
126
- * Complete search state and methods for searchable models
127
- * @example
128
- * // Search for users with name containing "john"
129
- * users.search.addQuery({ field: "name", value: "john" });
130
- *
131
- * @example
132
- * // Check if search is loading
133
- * if (users.search.loading) {
134
- * return <div>Searching...</div>;
135
- * }
136
- */
137
- export type SearchState = {
138
- /** Current active search queries */
139
- queries: SearchQuery[];
140
- /** Whether a search is currently in progress */
141
- loading: boolean;
142
- /** Replace all search queries with a new set */
143
- setQueries: (queries: SearchQuery[]) => void;
144
- /** Add a new search query (replaces existing query for same field) */
145
- addQuery: (query: SearchQuery) => void;
146
- /** Remove a search query by field name */
147
- removeQuery: (field: string) => void;
148
- /** Clear all search queries and return to normal data fetching */
149
- clearQueries: () => void;
150
- };
151
-
152
- /**
153
- * Convert a type-safe where filter to Supabase filter string
154
- */
155
- export function buildFilterString<T>(where?: T): string | undefined {
156
- if (!where) return undefined;
157
-
158
- const filters: string[] = [];
159
-
160
- for (const [key, value] of Object.entries(where)) {
161
- if (value !== undefined) {
162
- if (typeof value === 'object' && value !== null) {
163
- // Handle advanced operators
164
- const advancedOps = value as unknown as FilterOperators<any>;
165
-
166
- if ('equals' in advancedOps && advancedOps.equals !== undefined) {
167
- filters.push(\`\${key}=eq.\${advancedOps.equals}\`);
168
- }
169
-
170
- if ('not' in advancedOps && advancedOps.not !== undefined) {
171
- filters.push(\`\${key}=neq.\${advancedOps.not}\`);
172
- }
173
-
174
- if ('gt' in advancedOps && advancedOps.gt !== undefined) {
175
- filters.push(\`\${key}=gt.\${advancedOps.gt}\`);
176
- }
177
-
178
- if ('gte' in advancedOps && advancedOps.gte !== undefined) {
179
- filters.push(\`\${key}=gte.\${advancedOps.gte}\`);
180
- }
181
-
182
- if ('lt' in advancedOps && advancedOps.lt !== undefined) {
183
- filters.push(\`\${key}=lt.\${advancedOps.lt}\`);
184
- }
185
-
186
- if ('lte' in advancedOps && advancedOps.lte !== undefined) {
187
- filters.push(\`\${key}=lte.\${advancedOps.lte}\`);
188
- }
189
-
190
- if ('in' in advancedOps && advancedOps.in?.length) {
191
- filters.push(\`\${key}=in.(\${advancedOps.in.join(',')})\`);
192
- }
193
-
194
- if ('contains' in advancedOps && advancedOps.contains !== undefined) {
195
- filters.push(\`\${key}=ilike.*\${advancedOps.contains}*\`);
196
- }
197
-
198
- if ('startsWith' in advancedOps && advancedOps.startsWith !== undefined) {
199
- filters.push(\`\${key}=ilike.\${advancedOps.startsWith}%\`);
200
- }
201
-
202
- if ('endsWith' in advancedOps && advancedOps.endsWith !== undefined) {
203
- filters.push(\`\${key}=ilike.%\${advancedOps.endsWith}\`);
204
- }
205
- } else {
206
- // Simple equality
207
- filters.push(\`\${key}=eq.\${value}\`);
208
- }
209
- }
210
- }
211
-
212
- return filters.length > 0 ? filters.join(',') : undefined;
213
- }
214
-
215
- /**
216
- * Apply filter to the query builder
217
- */
218
- export function applyFilter<T>(
219
- query: SupabaseQueryBuilder,
220
- where: T
221
- ): SupabaseQueryBuilder {
222
- if (!where) return query;
223
-
224
- let filteredQuery = query;
225
-
226
- // Apply each filter condition
227
- for (const [key, value] of Object.entries(where)) {
228
- if (value !== undefined) {
229
- if (typeof value === 'object' && value !== null) {
230
- // Handle advanced operators
231
- const advancedOps = value as unknown as FilterOperators<any>;
232
-
233
- if ('equals' in advancedOps && advancedOps.equals !== undefined) {
234
- // @ts-ignore: Supabase typing issue
235
- filteredQuery = filteredQuery.eq(key, advancedOps.equals);
236
- }
237
-
238
- if ('not' in advancedOps && advancedOps.not !== undefined) {
239
- // @ts-ignore: Supabase typing issue
240
- filteredQuery = filteredQuery.neq(key, advancedOps.not);
241
- }
242
-
243
- if ('gt' in advancedOps && advancedOps.gt !== undefined) {
244
- // @ts-ignore: Supabase typing issue
245
- filteredQuery = filteredQuery.gt(key, advancedOps.gt);
246
- }
247
-
248
- if ('gte' in advancedOps && advancedOps.gte !== undefined) {
249
- // @ts-ignore: Supabase typing issue
250
- filteredQuery = filteredQuery.gte(key, advancedOps.gte);
251
- }
252
-
253
- if ('lt' in advancedOps && advancedOps.lt !== undefined) {
254
- // @ts-ignore: Supabase typing issue
255
- filteredQuery = filteredQuery.lt(key, advancedOps.lt);
256
- }
257
-
258
- if ('lte' in advancedOps && advancedOps.lte !== undefined) {
259
- // @ts-ignore: Supabase typing issue
260
- filteredQuery = filteredQuery.lte(key, advancedOps.lte);
261
- }
262
-
263
- if ('in' in advancedOps && advancedOps.in?.length) {
264
- // @ts-ignore: Supabase typing issue
265
- filteredQuery = filteredQuery.in(key, advancedOps.in);
266
- }
267
-
268
- if ('contains' in advancedOps && advancedOps.contains !== undefined) {
269
- // @ts-ignore: Supabase typing issue
270
- filteredQuery = filteredQuery.ilike(key, \`*\${advancedOps.contains}*\`);
271
- }
272
-
273
- if ('startsWith' in advancedOps && advancedOps.startsWith !== undefined) {
274
- // @ts-ignore: Supabase typing issue
275
- filteredQuery = filteredQuery.ilike(key, \`\${advancedOps.startsWith}%\`);
276
- }
277
-
278
- if ('endsWith' in advancedOps && advancedOps.endsWith !== undefined) {
279
- // @ts-ignore: Supabase typing issue
280
- filteredQuery = filteredQuery.ilike(key, \`%\${advancedOps.endsWith}\`);
281
- }
282
- } else {
283
- // Simple equality
284
- // @ts-ignore: Supabase typing issue
285
- filteredQuery = filteredQuery.eq(key, value);
286
- }
287
- }
288
- }
289
-
290
- return filteredQuery;
291
- }
292
-
293
- /**
294
- * Apply order by to the query builder
295
- */
296
- export function applyOrderBy<T>(
297
- query: SupabaseQueryBuilder,
298
- orderBy?: T,
299
- hasCreatedAt?: boolean
300
- ): SupabaseQueryBuilder {
301
- if (!orderBy) {
302
- // By default, sort by created_at if available
303
- if (hasCreatedAt) {
304
- // @ts-ignore: Supabase typing issue
305
- return query.order('created_at', { ascending: false });
306
- }
307
- return query;
308
- }
309
-
310
- // Apply each order by clause
311
- let orderedQuery = query;
312
- for (const [key, direction] of Object.entries(orderBy)) {
313
- // @ts-ignore: Supabase typing issue
314
- orderedQuery = orderedQuery.order(key, {
315
- ascending: direction === 'asc'
316
- });
317
- }
318
-
319
- return orderedQuery;
320
- }
321
-
322
- /**
323
- * Core hook factory function that creates a type-safe realtime hook for a specific model.
324
- * This is the foundation for all Suparisma hooks.
325
- */
326
- export function createSuparismaHook<
327
- TModel,
328
- TWithRelations,
329
- TCreateInput,
330
- TUpdateInput,
331
- TWhereInput,
332
- TWhereUniqueInput,
333
- TOrderByInput
334
- >(config: {
335
- tableName: string;
336
- hasCreatedAt: boolean;
337
- hasUpdatedAt: boolean;
338
- searchFields?: string[];
339
- defaultValues?: Record<string, string>; // Added parameter for default values
340
- }) {
341
- const { tableName, hasCreatedAt, hasUpdatedAt, searchFields = [], defaultValues = {} } = config;
342
-
343
- /**
344
- * The main hook function that provides all data access methods for a model.
345
- *
346
- * @param options - Optional configuration for data fetching, filtering, and realtime
347
- *
348
- * @returns An API object with data state and CRUD methods
349
- *
350
- * @example
351
- * // Basic usage
352
- * const users = useSuparismaUser();
353
- * const { data, loading, error } = users;
354
- *
355
- * @example
356
- * // With filtering
357
- * const users = useSuparismaUser({
358
- * where: { role: 'admin' },
359
- * orderBy: { created_at: 'desc' }
360
- * });
361
- */
362
- return function useSuparismaHook(options: SuparismaOptions<TWhereInput, TOrderByInput> = {}) {
363
- const {
364
- realtime = true,
365
- channelName,
366
- where,
367
- realtimeFilter,
368
- orderBy,
369
- limit,
370
- offset,
371
- } = options;
372
-
373
- // Compute the actual filter string from the type-safe where object or use legacy filter
374
- const computedFilter = where ? buildFilterString(where) : realtimeFilter;
375
-
376
- // Single data collection for holding results
377
- const [data, setData] = useState<TWithRelations[]>([]);
378
- const [error, setError] = useState<Error | null>(null);
379
- const [loading, setLoading] = useState<boolean>(false);
380
-
381
- // Search state
382
- const [searchQueries, setSearchQueries] = useState<SearchQuery[]>([]);
383
- const [searchLoading, setSearchLoading] = useState<boolean>(false);
384
-
385
- const initialLoadRef = useRef(false);
386
- const channelRef = useRef<ReturnType<typeof supabase.channel> | null>(null);
387
- const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
388
- const isSearchingRef = useRef<boolean>(false);
389
-
390
- // Create the search state object with all required methods
391
- const search: SearchState = {
392
- queries: searchQueries,
393
- loading: searchLoading,
394
-
395
- // Set all search queries at once
396
- setQueries: useCallback((queries: SearchQuery[]) => {
397
- // Validate that all fields are searchable
398
- const validQueries = queries.filter(query =>
399
- searchFields.includes(query.field) && query.value.trim() !== ''
400
- );
401
-
402
- setSearchQueries(validQueries);
403
-
404
- // Execute search if there are valid queries
405
- if (validQueries.length > 0) {
406
- executeSearch(validQueries);
407
- } else {
408
- // If no valid queries, reset to normal data fetching
409
- isSearchingRef.current = false;
410
- findMany({ where, orderBy, take: limit, skip: offset });
411
- }
412
- }, [where, orderBy, limit, offset]),
413
-
414
- // Add a single search query
415
- addQuery: useCallback((query: SearchQuery) => {
416
- // Validate that the field is searchable
417
- if (!searchFields.includes(query.field) || query.value.trim() === '') {
418
- return;
419
- }
420
-
421
- setSearchQueries(prev => {
422
- // Replace if query for this field already exists, otherwise add
423
- const exists = prev.some(q => q.field === query.field);
424
- const newQueries = exists
425
- ? prev.map(q => q.field === query.field ? query : q)
426
- : [...prev, query];
427
-
428
- // Execute search with updated queries
429
- executeSearch(newQueries);
430
-
431
- return newQueries;
432
- });
433
- }, []),
434
-
435
- // Remove a search query by field
436
- removeQuery: useCallback((field: string) => {
437
- setSearchQueries(prev => {
438
- const newQueries = prev.filter(q => q.field !== field);
439
-
440
- // If we still have queries, execute search with remaining queries
441
- if (newQueries.length > 0) {
442
- executeSearch(newQueries);
443
- } else {
444
- // If no queries left, reset to normal data fetching
445
- isSearchingRef.current = false;
446
- findMany({ where, orderBy, take: limit, skip: offset });
447
- }
448
-
449
- return newQueries;
450
- });
451
- }, [where, orderBy, limit, offset]),
452
-
453
- // Clear all search queries
454
- clearQueries: useCallback(() => {
455
- setSearchQueries([]);
456
- isSearchingRef.current = false;
457
- findMany({ where, orderBy, take: limit, skip: offset });
458
- }, [where, orderBy, limit, offset])
459
- };
460
-
461
- // Execute search based on queries
462
- const executeSearch = useCallback(async (queries: SearchQuery[]) => {
463
- // Clear the previous timeout
464
- if (searchTimeoutRef.current) {
465
- clearTimeout(searchTimeoutRef.current);
466
- }
467
-
468
- // Skip if no searchable fields or no valid queries
469
- if (searchFields.length === 0 || queries.length === 0) {
470
- return;
471
- }
472
-
473
- setSearchLoading(true);
474
- isSearchingRef.current = true;
475
-
476
- // Use debounce to prevent rapid searches
477
- searchTimeoutRef.current = setTimeout(async () => {
478
- try {
479
- let results: TWithRelations[] = [];
480
-
481
- // Execute RPC function for each query using Promise.all
482
- const searchPromises = queries.map(query => {
483
- // Build function name: search_tablename_by_fieldname_prefix
484
- const functionName = \`search_\${tableName}_by_\${query.field}_prefix\`;
485
-
486
- // Call RPC function
487
- return supabase.rpc(functionName, { prefix: query.value.trim() });
488
- });
489
-
490
- // Execute all search queries in parallel
491
- const searchResults = await Promise.all(searchPromises);
492
-
493
- // Combine and deduplicate results
494
- const allResults: Record<string, TWithRelations> = {};
495
-
496
- // Process each search result
497
- searchResults.forEach((result, index) => {
498
- if (result.error) {
499
- console.error(\`Search error for \${queries[index]?.field}:\`, result.error);
500
- return;
501
- }
502
-
503
- if (result.data) {
504
- // Add each result, using id as key to deduplicate
505
- for (const item of result.data as TWithRelations[]) {
506
- // @ts-ignore: Assume item has an id property
507
- if (item.id) {
508
- // @ts-ignore: Add to results using id as key
509
- allResults[item.id] = item;
510
- }
511
- }
512
- }
513
- });
514
-
515
- // Convert back to array
516
- results = Object.values(allResults);
517
-
518
- // Apply any where conditions client-side
519
- if (where) {
520
- results = results.filter((item) => {
521
- for (const [key, value] of Object.entries(where)) {
522
- if (typeof value === 'object' && value !== null) {
523
- // Skip complex filters for now
524
- continue;
525
- }
526
-
527
- if (item[key as keyof typeof item] !== value) {
528
- return false;
529
- }
530
- }
531
- return true;
532
- });
533
- }
534
-
535
- // Apply ordering if needed
536
- if (orderBy) {
537
- const orderEntries = Object.entries(orderBy);
538
- if (orderEntries.length > 0) {
539
- const [orderField, direction] = orderEntries[0] || [];
540
- results = [...results].sort((a, b) => {
541
- const aValue = a[orderField as keyof typeof a] ?? '';
542
- const bValue = b[orderField as keyof typeof b] ?? '';
543
-
544
- if (direction === 'asc') {
545
- return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
546
- } else {
547
- return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
548
- }
549
- });
550
- }
551
- }
552
-
553
- // Apply pagination if needed
554
- if (limit && limit > 0) {
555
- results = results.slice(0, limit);
556
- }
557
-
558
- if (offset && offset > 0) {
559
- results = results.slice(offset);
560
- }
561
-
562
- // Update data with search results
563
- setData(results);
564
- } catch (err) {
565
- console.error('Search error:', err);
566
- setError(err as Error);
567
- } finally {
568
- setSearchLoading(false);
569
- }
570
- }, 300); // 300ms debounce
571
- }, [tableName, searchFields, where, orderBy, limit, offset]);
572
-
573
- /**
574
- * Fetch multiple records with support for filtering, sorting, and pagination.
575
- *
576
- * @param params - Query parameters for filtering and ordering records
577
- * @returns A promise with the fetched data or error
578
- *
579
- * @example
580
- * // Get all active users
581
- * const result = await users.findMany({
582
- * where: { active: true }
583
- * });
584
- *
585
- * @example
586
- * // Get 10 most recent posts with pagination
587
- * const page1 = await posts.findMany({
588
- * orderBy: { created_at: 'desc' },
589
- * take: 10,
590
- * skip: 0
591
- * });
592
- *
593
- * const page2 = await posts.findMany({
594
- * orderBy: { created_at: 'desc' },
595
- * take: 10,
596
- * skip: 10
597
- * });
598
- */
599
- const findMany = useCallback(async (params?: {
600
- where?: TWhereInput;
601
- orderBy?: TOrderByInput;
602
- take?: number;
603
- skip?: number;
604
- }): ModelResult<TWithRelations[]> => {
605
- try {
606
- setLoading(true);
607
- setError(null);
608
-
609
- let query = supabase.from(tableName).select('*');
610
-
611
- // Apply where conditions if provided
612
- if (params?.where) {
613
- query = applyFilter(query, params.where);
614
- }
615
-
616
- // Apply order by if provided
617
- if (params?.orderBy) {
618
- query = applyOrderBy(query, params.orderBy, hasCreatedAt);
619
- } else if (hasCreatedAt) {
620
- // Default ordering if available
621
- // @ts-ignore: Supabase typing issue
622
- query = query.order('created_at', { ascending: false });
623
- }
624
-
625
- // Apply limit if provided
626
- if (params?.take) {
627
- query = query.limit(params.take);
628
- }
629
-
630
- // Apply offset if provided (for pagination)
631
- if (params?.skip) {
632
- query = query.range(params.skip, params.skip + (params.take || 10) - 1);
633
- }
634
-
635
- const { data, error } = await query;
636
-
637
- if (error) throw error;
638
-
639
- const typedData = (data || []) as TWithRelations[];
640
-
641
- // Only update data if not currently searching
642
- if (!isSearchingRef.current) {
643
- setData(typedData);
644
- }
645
-
646
- return { data: typedData, error: null };
647
- } catch (err: any) {
648
- console.error('Error finding records:', err);
649
- setError(err);
650
- return { data: null, error: err };
651
- } finally {
652
- setLoading(false);
653
- }
654
- }, []);
655
-
656
- /**
657
- * Find a single record by its unique identifier (usually ID).
658
- *
659
- * @param where - The unique identifier to find the record by
660
- * @returns A promise with the found record or error
661
- *
662
- * @example
663
- * // Find user by ID
664
- * const result = await users.findUnique({ id: "123" });
665
- * if (result.data) {
666
- * console.log("Found user:", result.data.name);
667
- * }
668
- */
669
- const findUnique = useCallback(async (
670
- where: TWhereUniqueInput
671
- ): ModelResult<TWithRelations> => {
672
- try {
673
- setLoading(true);
674
- setError(null);
675
-
676
- // Find the primary field (usually 'id')
677
- // @ts-ignore: Supabase typing issue
678
- const primaryKey = Object.keys(where)[0];
679
- if (!primaryKey) {
680
- throw new Error('A unique identifier is required');
681
- }
682
-
683
- const value = where[primaryKey as keyof typeof where];
684
- if (value === undefined) {
685
- throw new Error('A unique identifier is required');
686
- }
687
-
688
- const { data, error } = await supabase
689
- .from(tableName)
690
- .select('*')
691
- .eq(primaryKey, value)
692
- .maybeSingle();
693
-
694
- if (error) throw error;
695
-
696
- return { data: data as TWithRelations, error: null };
697
- } catch (err: any) {
698
- console.error('Error finding unique record:', err);
699
- setError(err);
700
- return { data: null, error: err };
701
- } finally {
702
- setLoading(false);
703
- }
704
- }, []);
705
-
706
- // Set up realtime subscription for the list
707
- useEffect(() => {
708
- if (!realtime) return;
709
-
710
- // Clean up previous subscription if it exists
711
- if (channelRef.current) {
712
- channelRef.current.unsubscribe();
713
- channelRef.current = null;
714
- }
715
-
716
- const channelId = channelName || \`changes_to_\${tableName}_\${Math.random().toString(36).substring(2, 15)}\`;
717
-
718
- // Store the current filter and options for closure
719
- const currentFilter = computedFilter;
720
- const currentWhere = where;
721
- const currentOrderBy = orderBy;
722
- const currentLimit = limit;
723
- const currentOffset = offset;
724
-
725
- console.log(\`Setting up subscription for \${tableName} with filter: \${currentFilter}\`);
726
-
727
- const channel = supabase
728
- .channel(channelId)
729
- .on(
730
- 'postgres_changes',
731
- {
732
- event: '*',
733
- schema: 'public',
734
- table: tableName,
735
- filter: currentFilter,
736
- },
737
- (payload) => {
738
- console.log(\`Received \${payload.eventType} event for \${tableName}\`, payload);
739
-
740
- // Skip realtime updates when search is active
741
- if (isSearchingRef.current) return;
742
-
743
- if (payload.eventType === 'INSERT') {
744
- // Process insert event
745
- setData((prev) => {
746
- try {
747
- const newRecord = payload.new as TWithRelations;
748
- console.log(\`Processing INSERT for \${tableName}\`, { newRecord });
749
-
750
- // Check if this record matches our filter if we have one
751
- if (currentWhere) {
752
- let matchesFilter = true;
753
-
754
- // Check each filter condition
755
- for (const [key, value] of Object.entries(currentWhere)) {
756
- if (typeof value === 'object' && value !== null) {
757
- // Complex filter - this is handled by Supabase, assume it matches
758
- } else if (newRecord[key as keyof typeof newRecord] !== value) {
759
- matchesFilter = false;
760
- console.log(\`Filter mismatch on \${key}\`, { expected: value, actual: newRecord[key as keyof typeof newRecord] });
761
- break;
762
- }
763
- }
764
-
765
- if (!matchesFilter) {
766
- console.log('New record does not match filter criteria, skipping');
767
- return prev;
768
- }
769
- }
770
-
771
- // Check if record already exists (avoid duplicates)
772
- const exists = prev.some(item =>
773
- // @ts-ignore: Supabase typing issue
774
- 'id' in item && 'id' in newRecord && item.id === newRecord.id
775
- );
776
-
777
- if (exists) {
778
- console.log('Record already exists, skipping insertion');
779
- return prev;
780
- }
781
-
782
- // Add the new record to the data
783
- let newData = [newRecord, ...prev];
784
-
785
- // Apply ordering if specified
786
- if (currentOrderBy) {
787
- const [orderField, direction] = Object.entries(currentOrderBy)[0] || [];
788
- if (orderField) {
789
- newData = [...newData].sort((a, b) => {
790
- const aValue = a[orderField as keyof typeof a] ?? '';
791
- const bValue = b[orderField as keyof typeof b] ?? '';
792
-
793
- if (direction === 'asc') {
794
- return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
795
- } else {
796
- return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
797
- }
798
- });
799
- }
800
- }
801
-
802
- // Apply limit if specified
803
- if (currentLimit && currentLimit > 0) {
804
- newData = newData.slice(0, currentLimit);
805
- }
806
-
807
- return newData;
808
- } catch (error) {
809
- console.error('Error processing INSERT event:', error);
810
- return prev;
811
- }
812
- });
813
- } else if (payload.eventType === 'UPDATE') {
814
- // Process update event
815
- setData((prev) => {
816
- // Skip if search is active
817
- if (isSearchingRef.current) {
818
- return prev;
819
- }
820
-
821
- return prev.map((item) =>
822
- // @ts-ignore: Supabase typing issue
823
- 'id' in item && 'id' in payload.new && item.id === payload.new.id
824
- ? (payload.new as TWithRelations)
825
- : item
826
- );
827
- });
828
- } else if (payload.eventType === 'DELETE') {
829
- // Process delete event
830
- setData((prev) => {
831
- // Skip if search is active
832
- if (isSearchingRef.current) {
833
- return prev;
834
- }
835
-
836
- // Save the current size before filtering
837
- const currentSize = prev.length;
838
-
839
- // Filter out the deleted item
840
- const filteredData = prev.filter((item) => {
841
- // @ts-ignore: Supabase typing issue
842
- return !('id' in item && 'id' in payload.old && item.id === payload.old.id);
843
- });
844
-
845
- // If we need to maintain the size with a limit
846
- if (currentLimit && currentLimit > 0 && filteredData.length < currentSize && currentSize === currentLimit) {
847
- console.log(\`Record deleted with limit \${currentLimit}, will fetch additional record to maintain size\`);
848
-
849
- // Use setTimeout to ensure this state update completes first
850
- setTimeout(() => {
851
- findMany({
852
- where: currentWhere,
853
- orderBy: currentOrderBy,
854
- take: currentLimit,
855
- skip: currentOffset
856
- });
857
- }, 0);
858
- }
859
-
860
- return filteredData;
861
- });
862
- }
863
- }
864
- )
865
- .subscribe((status) => {
866
- console.log(\`Subscription status for \${tableName}\`, status);
867
- });
868
-
869
- // Store the channel ref
870
- channelRef.current = channel;
871
-
872
- return () => {
873
- console.log(\`Unsubscribing from \${channelId}\`);
874
- if (channelRef.current) {
875
- channelRef.current.unsubscribe();
876
- channelRef.current = null;
877
- }
878
-
879
- if (searchTimeoutRef.current) {
880
- clearTimeout(searchTimeoutRef.current);
881
- searchTimeoutRef.current = null;
882
- }
883
- };
884
- }, [realtime, channelName, computedFilter]);
885
-
886
- // Create a memoized options object to prevent unnecessary re-renders
887
- const optionsRef = useRef({ where, orderBy, limit, offset });
888
-
889
- // Compare current options with previous options
890
- const optionsChanged = useCallback(() => {
891
- // Create stable string representations for deep comparison
892
- const whereStr = where ? JSON.stringify(where) : '';
893
- const orderByStr = orderBy ? JSON.stringify(orderBy) : '';
894
- const prevWhereStr = optionsRef.current.where ? JSON.stringify(optionsRef.current.where) : '';
895
- const prevOrderByStr = optionsRef.current.orderBy ? JSON.stringify(optionsRef.current.orderBy) : '';
896
-
897
- // Compare the stable representations
898
- const hasChanged =
899
- whereStr !== prevWhereStr ||
900
- orderByStr !== prevOrderByStr ||
901
- limit !== optionsRef.current.limit ||
902
- offset !== optionsRef.current.offset;
903
-
904
- if (hasChanged) {
905
- // Update the ref with the new values
906
- optionsRef.current = { where, orderBy, limit, offset };
907
- return true;
908
- }
909
-
910
- return false;
911
- }, [where, orderBy, limit, offset]);
912
-
913
- // Load initial data based on options
914
- useEffect(() => {
915
- // Skip if search is active
916
- if (isSearchingRef.current) return;
917
-
918
- // Skip if we've already loaded or if no filter criteria are provided
919
- if (initialLoadRef.current) {
920
- // Only reload if options have changed significantly
921
- if (optionsChanged()) {
922
- console.log(\`Options changed for \${tableName}, reloading data\`);
923
- findMany({
924
- where,
925
- orderBy,
926
- take: limit,
927
- skip: offset
928
- });
929
- }
930
- return;
931
- }
932
-
933
- // Initial load
934
- initialLoadRef.current = true;
935
- findMany({
936
- where,
937
- orderBy,
938
- take: limit,
939
- skip: offset
940
- });
941
- }, [findMany, where, orderBy, limit, offset, optionsChanged]);
942
-
943
- /**
944
- * Create a new record with the provided data.
945
- * Default values from the schema will be applied if not provided.
946
- *
947
- * @param data - The data to create the record with
948
- * @returns A promise with the created record or error
949
- *
950
- * @example
951
- * // Create a new user
952
- * const result = await users.create({
953
- * name: "John Doe",
954
- * email: "john@example.com"
955
- * });
956
- *
957
- * @example
958
- * // Create with custom ID (overriding default)
959
- * const result = await users.create({
960
- * id: "custom-id-123",
961
- * name: "John Doe"
962
- * });
963
- */
964
- const create = useCallback(async (
965
- data: TCreateInput
966
- ): ModelResult<TWithRelations> => {
967
- try {
968
- setLoading(true);
969
- setError(null);
970
-
971
- const now = new Date().toISOString();
972
-
973
- // Apply default values from schema
974
- const appliedDefaults: Record<string, any> = {};
975
-
976
- // Apply all default values that aren't already in the data
977
- for (const [field, defaultValue] of Object.entries(defaultValues)) {
978
- // @ts-ignore: Supabase typing issue
979
- if (!(field in data)) {
980
- // Parse the default value based on its type
981
- if (defaultValue.includes('now()') || defaultValue.includes('now')) {
982
- appliedDefaults[field] = now;
983
- } else if (defaultValue.includes('uuid()') || defaultValue.includes('uuid')) {
984
- appliedDefaults[field] = crypto.randomUUID();
985
- } else if (defaultValue.includes('cuid()') || defaultValue.includes('cuid')) {
986
- // Simple cuid-like implementation for client-side
987
- appliedDefaults[field] = 'c' + Math.random().toString(36).substring(2, 15);
988
- } else if (defaultValue.includes('true')) {
989
- appliedDefaults[field] = true;
990
- } else if (defaultValue.includes('false')) {
991
- appliedDefaults[field] = false;
992
- } else if (!isNaN(Number(defaultValue))) {
993
- // If it's a number
994
- appliedDefaults[field] = Number(defaultValue);
995
- } else {
996
- // String or other value, remove quotes if present
997
- const strValue = defaultValue.replace(/^["'](.*)["']$/, '$1');
998
- appliedDefaults[field] = strValue;
999
- }
1000
- }
1001
- }
1002
-
1003
- const itemWithDefaults = {
1004
- ...appliedDefaults, // Apply schema defaults first
1005
- ...data, // Then user data (overrides defaults)
1006
- ...(hasCreatedAt ? { created_at: now } : {}), // Always set timestamps
1007
- ...(hasUpdatedAt ? { updated_at: now } : {})
1008
- };
1009
-
1010
- const { data: result, error } = await supabase
1011
- .from(tableName)
1012
- .insert([itemWithDefaults])
1013
- .select();
1014
-
1015
- if (error) throw error;
1016
-
1017
- // Return created record
1018
- return { data: result?.[0] as TWithRelations, error: null };
1019
- } catch (err: any) {
1020
- console.error('Error creating record:', err);
1021
- setError(err);
1022
- return { data: null, error: err };
1023
- } finally {
1024
- setLoading(false);
1025
- }
1026
- }, []);
1027
-
1028
- /**
1029
- * Update an existing record identified by a unique identifier.
1030
- *
1031
- * @param params - Object containing the identifier and update data
1032
- * @returns A promise with the updated record or error
1033
- *
1034
- * @example
1035
- * // Update a user's name
1036
- * const result = await users.update({
1037
- * where: { id: "123" },
1038
- * data: { name: "New Name" }
1039
- * });
1040
- *
1041
- * @example
1042
- * // Update multiple fields
1043
- * const result = await users.update({
1044
- * where: { id: "123" },
1045
- * data: {
1046
- * name: "New Name",
1047
- * active: false
1048
- * }
1049
- * });
1050
- */
1051
- const update = useCallback(async (params: {
1052
- where: TWhereUniqueInput;
1053
- data: TUpdateInput;
1054
- }): ModelResult<TWithRelations> => {
1055
- try {
1056
- setLoading(true);
1057
- setError(null);
1058
-
1059
- // Find the primary field (usually 'id')
1060
- // @ts-ignore: Supabase typing issue
1061
- const primaryKey = Object.keys(params.where)[0];
1062
- if (!primaryKey) {
1063
- throw new Error('A unique identifier is required');
1064
- }
1065
-
1066
- const value = params.where[primaryKey as keyof typeof params.where];
1067
- if (value === undefined) {
1068
- throw new Error('A unique identifier is required');
1069
- }
1070
-
1071
- const now = new Date().toISOString();
1072
-
1073
- // We do not apply default values for updates
1074
- // Default values are only for creation, not for updates,
1075
- // as existing records already have these values set
1076
-
1077
- const itemWithDefaults = {
1078
- ...params.data,
1079
- ...(hasUpdatedAt ? { updated_at: now } : {})
1080
- };
1081
-
1082
- const { data, error } = await supabase
1083
- .from(tableName)
1084
- .update(itemWithDefaults)
1085
- .eq(primaryKey, value)
1086
- .select();
1087
-
1088
- if (error) throw error;
1089
-
1090
- // Return updated record
1091
- return { data: data?.[0] as TWithRelations, error: null };
1092
- } catch (err: any) {
1093
- console.error('Error updating record:', err);
1094
- setError(err);
1095
- return { data: null, error: err };
1096
- } finally {
1097
- setLoading(false);
1098
- }
1099
- }, []);
1100
-
1101
- /**
1102
- * Delete a record by its unique identifier.
1103
- *
1104
- * @param where - The unique identifier to delete the record by
1105
- * @returns A promise with the deleted record or error
1106
- *
1107
- * @example
1108
- * // Delete a user by ID
1109
- * const result = await users.delete({ id: "123" });
1110
- * if (result.data) {
1111
- * console.log("Deleted user:", result.data.name);
1112
- * }
1113
- */
1114
- const deleteRecord = useCallback(async (
1115
- where: TWhereUniqueInput
1116
- ): ModelResult<TWithRelations> => {
1117
- try {
1118
- setLoading(true);
1119
- setError(null);
1120
-
1121
- // Find the primary field (usually 'id')
1122
- // @ts-ignore: Supabase typing issue
1123
- const primaryKey = Object.keys(where)[0];
1124
- if (!primaryKey) {
1125
- throw new Error('A unique identifier is required');
1126
- }
1127
-
1128
- const value = where[primaryKey as keyof typeof where];
1129
- if (value === undefined) {
1130
- throw new Error('A unique identifier is required');
1131
- }
1132
-
1133
- // First fetch the record to return it
1134
- const { data: recordToDelete } = await supabase
1135
- .from(tableName)
1136
- .select('*')
1137
- .eq(primaryKey, value)
1138
- .maybeSingle();
1139
-
1140
- if (!recordToDelete) {
1141
- throw new Error('Record not found');
1142
- }
1143
-
1144
- // Then delete it
1145
- const { error } = await supabase
1146
- .from(tableName)
1147
- .delete()
1148
- .eq(primaryKey, value);
1149
-
1150
- if (error) throw error;
1151
-
1152
- // Return the deleted record
1153
- return { data: recordToDelete as TWithRelations, error: null };
1154
- } catch (err: any) {
1155
- console.error('Error deleting record:', err);
1156
- setError(err);
1157
- return { data: null, error: err };
1158
- } finally {
1159
- setLoading(false);
1160
- }
1161
- }, []);
1162
-
1163
- /**
1164
- * Delete multiple records matching the filter criteria.
1165
- *
1166
- * @param params - Query parameters for filtering records to delete
1167
- * @returns A promise with the count of deleted records or error
1168
- *
1169
- * @example
1170
- * // Delete all inactive users
1171
- * const result = await users.deleteMany({
1172
- * where: { active: false }
1173
- * });
1174
- * console.log(\`Deleted \${result.count} inactive users\`);
1175
- *
1176
- * @example
1177
- * // Delete all records (use with caution!)
1178
- * const result = await users.deleteMany();
1179
- */
1180
- const deleteMany = useCallback(async (params?: {
1181
- where?: TWhereInput;
1182
- }): Promise<{ count: number; error: Error | null }> => {
1183
- try {
1184
- setLoading(true);
1185
- setError(null);
1186
-
1187
- // First, get the records that will be deleted to count them
1188
- let query = supabase.from(tableName).select('*');
1189
-
1190
- // Apply where conditions if provided
1191
- if (params?.where) {
1192
- query = applyFilter(query, params.where);
1193
- }
1194
-
1195
- // Get records that will be deleted
1196
- const { data: recordsToDelete, error: fetchError } = await query;
1197
-
1198
- if (fetchError) throw fetchError;
1199
-
1200
- if (!recordsToDelete?.length) {
1201
- return { count: 0, error: null };
1202
- }
1203
-
1204
- // Build the delete query
1205
- let deleteQuery = supabase.from(tableName).delete();
1206
-
1207
- // Apply the same filter to the delete operation
1208
- if (params?.where) {
1209
- // @ts-ignore: Supabase typing issue
1210
- deleteQuery = applyFilter(deleteQuery, params.where);
1211
- }
1212
-
1213
- // Perform the delete
1214
- const { error: deleteError } = await deleteQuery;
1215
-
1216
- if (deleteError) throw deleteError;
1217
-
1218
- // Return the count of deleted records
1219
- return { count: recordsToDelete.length, error: null };
1220
- } catch (err: any) {
1221
- console.error('Error deleting multiple records:', err);
1222
- setError(err);
1223
- return { count: 0, error: err };
1224
- } finally {
1225
- setLoading(false);
1226
- }
1227
- }, []);
1228
-
1229
- /**
1230
- * Find the first record matching the filter criteria.
1231
- *
1232
- * @param params - Query parameters for filtering and ordering
1233
- * @returns A promise with the first matching record or error
1234
- *
1235
- * @example
1236
- * // Find the first admin user
1237
- * const result = await users.findFirst({
1238
- * where: { role: 'admin' }
1239
- * });
1240
- *
1241
- * @example
1242
- * // Find the oldest post
1243
- * const result = await posts.findFirst({
1244
- * orderBy: { created_at: 'asc' }
1245
- * });
1246
- */
1247
- const findFirst = useCallback(async (params?: {
1248
- where?: TWhereInput;
1249
- orderBy?: TOrderByInput;
1250
- }): ModelResult<TWithRelations> => {
1251
- try {
1252
- const result = await findMany({
1253
- ...params,
1254
- take: 1
1255
- });
1256
-
1257
- if (result.error) return { data: null, error: result.error };
1258
- if (!result.data.length) return { data: null, error: new Error('No records found') };
1259
-
1260
- // @ts-ignore: Supabase typing issue
1261
- return { data: result.data[0], error: null };
1262
- } catch (err: any) {
1263
- console.error('Error finding first record:', err);
1264
- return { data: null, error: err };
1265
- }
1266
- }, [findMany]);
1267
-
1268
- /**
1269
- * Create a record if it doesn't exist, or update it if it does.
1270
- *
1271
- * @param params - Object containing the identifier, update data, and create data
1272
- * @returns A promise with the created or updated record or error
1273
- *
1274
- * @example
1275
- * // Upsert a user by ID
1276
- * const result = await users.upsert({
1277
- * where: { id: "123" },
1278
- * update: { lastLogin: new Date().toISOString() },
1279
- * create: {
1280
- * id: "123",
1281
- * name: "John Doe",
1282
- * email: "john@example.com",
1283
- * lastLogin: new Date().toISOString()
1284
- * }
1285
- * });
1286
- */
1287
- const upsert = useCallback(async (params: {
1288
- where: TWhereUniqueInput;
1289
- update: TUpdateInput;
1290
- create: TCreateInput;
1291
- }): ModelResult<TWithRelations> => {
1292
- try {
1293
- // Check if record exists
1294
- const { data: existing } = await findUnique(params.where);
1295
-
1296
- // Update if exists, otherwise create
1297
- if (existing) {
1298
- return update({ where: params.where, data: params.update });
1299
- } else {
1300
- return create(params.create);
1301
- }
1302
- } catch (err: any) {
1303
- console.error('Error upserting record:', err);
1304
- return { data: null, error: err };
1305
- }
1306
- }, [findUnique, update, create]);
1307
-
1308
- /**
1309
- * Count the number of records matching the filter criteria.
1310
- *
1311
- * @param params - Query parameters for filtering
1312
- * @returns A promise with the count of matching records
1313
- *
1314
- * @example
1315
- * // Count all users
1316
- * const count = await users.count();
1317
- *
1318
- * @example
1319
- * // Count active users
1320
- * const activeCount = await users.count({
1321
- * where: { active: true }
1322
- * });
1323
- */
1324
- const count = useCallback(async (params?: {
1325
- where?: TWhereInput;
1326
- }): Promise<number> => {
1327
- try {
1328
- let query = supabase.from(tableName).select('*', { count: 'exact', head: true });
1329
-
1330
- // Use provided where filter, or fall back to the hook's original where filter
1331
- const effectiveWhere = params?.where ?? where;
1332
-
1333
- if (effectiveWhere) {
1334
- query = applyFilter(query, effectiveWhere);
1335
- }
1336
-
1337
- const { count, error } = await query;
1338
-
1339
- if (error) throw error;
1340
-
1341
- return count || 0;
1342
- } catch (err) {
1343
- console.error('Error counting records:', err);
1344
- return 0;
1345
- }
1346
- }, [where]);
1347
-
1348
- /**
1349
- * Manually refresh the data with current filter settings.
1350
- * Useful after external operations or when realtime is disabled.
1351
- *
1352
- * @param params - Optional override parameters for this specific refresh
1353
- * @returns A promise with the refreshed data or error
1354
- *
1355
- * @example
1356
- * // Refresh with current filter settings
1357
- * await users.refresh();
1358
- *
1359
- * @example
1360
- * // Refresh with different filters for this call only
1361
- * await users.refresh({
1362
- * where: { active: true },
1363
- * orderBy: { name: 'asc' }
1364
- * });
1365
- */
1366
- const refresh = useCallback((params?: {
1367
- where?: TWhereInput;
1368
- orderBy?: TOrderByInput;
1369
- take?: number;
1370
- skip?: number;
1371
- }) => {
1372
- // If search is active, refresh search results
1373
- if (isSearchingRef.current && searchQueries.length > 0) {
1374
- executeSearch(searchQueries);
1375
- return Promise.resolve({ data: data, error: null });
1376
- }
1377
-
1378
- // Otherwise, refresh normal data using original params if not explicitly overridden
1379
- return findMany({
1380
- where: params?.where ?? where,
1381
- orderBy: params?.orderBy ?? orderBy,
1382
- take: params?.take ?? limit,
1383
- skip: params?.skip ?? offset
1384
- });
1385
- }, [findMany, data, searchQueries, where, orderBy, limit, offset]);
1386
-
1387
- // Construct final hook API with or without search
1388
- const api = {
1389
- // State
1390
- data,
1391
- error,
1392
- loading,
1393
-
1394
- // Finder methods
1395
- findUnique,
1396
- findMany,
1397
- findFirst,
1398
-
1399
- // Mutation methods
1400
- create,
1401
- update,
1402
- delete: deleteRecord,
1403
- deleteMany,
1404
- upsert,
1405
-
1406
- // Utilities
1407
- count,
1408
-
1409
- // Manual refresh
1410
- refresh
1411
- };
1412
-
1413
- // Add search object if searchable fields are present
1414
- return searchFields.length > 0
1415
- ? {
1416
- ...api,
1417
- search
1418
- }
1419
- : api;
1420
- };
1421
- }`;
1422
-
1423
- const outputPath = path.join(OUTPUT_DIR, 'core.ts');
1424
- fs.writeFileSync(outputPath, coreContent);
1425
- console.log(`Updated core hook factory with improved refresh and count functions at ${outputPath}`);
1426
- }