supabase-typed-query 0.2.0 → 0.2.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.
@@ -0,0 +1,349 @@
1
+ # Integration Tests
2
+
3
+ This document describes how to set up and run integration tests for supabase-typed-query.
4
+
5
+ ## Overview
6
+
7
+ Integration tests verify that our library works correctly against a real Supabase database. We support two testing approaches:
8
+
9
+ - **Unit Tests**: Fast, mock-based tests that don't require a database (default for `pnpm test:unit`)
10
+ - **Integration Tests**: Real database tests that verify actual Supabase behavior (`pnpm test:integration`)
11
+
12
+ ## Test Architecture
13
+
14
+ ```
15
+ supabase-typed-query → Supabase Client → PostgreSQL/Supabase Database
16
+ ```
17
+
18
+ ## Test Coverage
19
+
20
+ The integration tests are organized into three main test suites with **65+ comprehensive tests**:
21
+
22
+ ### Query API Tests (`Query.integration.spec.ts`)
23
+
24
+ - **Basic Query Execution** (6 tests): one(), many(), first(), oneOrThrow(), manyOrThrow(), firstOrThrow()
25
+ - **Comparison Operators** (8 tests): gt, gte, lt, lte, neq, in, is null, is true/false
26
+ - **Pattern Matching** (2 tests): like, ilike (case-insensitive)
27
+ - **OR Chaining** (3 tests): Single OR, multiple OR, OR with IS conditions
28
+ - **Functional Operations** (9 tests): map, chained map, filter, filter+map, limit, offset, pagination
29
+ - **Soft Delete Operations** (3 tests): includeDeleted(), excludeDeleted(), onlyDeleted()
30
+ - **Complex Query Chains** (2 tests): Combined operations, type safety
31
+
32
+ **Total**: ~33 Query API integration tests
33
+
34
+ ### Entity API Tests (`Entity.integration.spec.ts`)
35
+
36
+ - **getGlobalItems()** (3 tests): Fetch all, with conditions, soft delete filtering
37
+ - **getItem()** (2 tests): Fetch by ID, not found handling
38
+ - **addItems()** (2 tests): Single insert, batch insert
39
+ - **updateItem()** (2 tests): Update by ID, non-existent item
40
+ - **deleteItem()** (2 tests): Hard delete, soft delete
41
+ - **deleteItems()** (1 test): Batch delete
42
+ - **OrThrow Variants** (6 tests): All \*OrThrow methods with success and error cases
43
+ - **Multi-tenancy** (1 test): Partition key support
44
+ - **Error Handling** (1 test): Database constraint violations
45
+
46
+ **Total**: ~20 Entity API integration tests
47
+
48
+ ### Advanced Query Tests (`QueryAdvanced.integration.spec.ts`)
49
+
50
+ - **Complex Query Chains** (3 tests): OR+filter+map+limit, nested transformations, multiple conditions
51
+ - **Pagination Scenarios** (3 tests): Offset-based pagination, limit only, offset only
52
+ - **Concurrent Query Execution** (2 tests): Multiple concurrent queries, concurrent map operations
53
+ - **Edge Cases** (4 tests): Empty results, long OR chains, no matches, null comparisons
54
+ - **Performance Characteristics** (2 tests): Large result sets, multiple filters
55
+ - **Type Safety** (2 tests): Types through complex chains, nested transformations
56
+ - **Real-world Scenarios** (3 tests): Recent posts query, admin emails, paginated search
57
+
58
+ **Total**: ~19 Advanced integration tests
59
+
60
+ ### Helper Utilities (`database-setup.ts`)
61
+
62
+ - Connection management (Supabase/PostgREST)
63
+ - Test data creation (single/batch)
64
+ - Soft delete test data generation
65
+ - Automatic cleanup with test\_ prefix pattern
66
+
67
+ ## Local Development Setup
68
+
69
+ ### Option 1: Using Your Own Supabase Project (Recommended)
70
+
71
+ 1. **Create a Supabase project** (or use existing one):
72
+ - Go to [supabase.com](https://supabase.com)
73
+ - Create a new project or select existing
74
+ - Get your project URL and anon key from Project Settings > API
75
+
76
+ 2. **Set up test schema**:
77
+
78
+ The integration tests require specific tables in your database. We provide a complete SQL schema file:
79
+
80
+ **Option A: Using the provided schema file**
81
+
82
+ ```bash
83
+ # Copy the SQL schema from test/integration/schema.sql
84
+ # and run it in your Supabase SQL editor
85
+ cat test/integration/schema.sql
86
+ ```
87
+
88
+ **Option B: Run the SQL directly**
89
+
90
+ ```sql
91
+ -- Create test tables in your Supabase SQL editor
92
+ -- See test/integration/schema.sql for the complete schema
93
+
94
+ -- Users table
95
+ CREATE TABLE users (
96
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
97
+ name TEXT NOT NULL,
98
+ email TEXT UNIQUE NOT NULL,
99
+ age INTEGER,
100
+ active BOOLEAN DEFAULT true,
101
+ role TEXT,
102
+ created_at TIMESTAMPTZ DEFAULT now(),
103
+ deleted TIMESTAMPTZ -- Soft delete column
104
+ );
105
+
106
+ -- Posts table
107
+ CREATE TABLE posts (
108
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
109
+ title TEXT NOT NULL,
110
+ content TEXT,
111
+ author_id UUID REFERENCES users(id) ON DELETE CASCADE,
112
+ status TEXT,
113
+ view_count INTEGER DEFAULT 0,
114
+ published_at TIMESTAMPTZ,
115
+ created_at TIMESTAMPTZ DEFAULT now(),
116
+ deleted TIMESTAMPTZ -- Soft delete column
117
+ );
118
+
119
+ -- Comments table
120
+ CREATE TABLE comments (
121
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
122
+ post_id UUID REFERENCES posts(id) ON DELETE CASCADE,
123
+ user_id UUID REFERENCES users(id) ON DELETE CASCADE,
124
+ text TEXT NOT NULL,
125
+ created_at TIMESTAMPTZ DEFAULT now(),
126
+ deleted TIMESTAMPTZ -- Soft delete column
127
+ );
128
+
129
+ -- Create indexes for better query performance
130
+ CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
131
+ CREATE INDEX IF NOT EXISTS idx_users_active ON users(active) WHERE deleted IS NULL;
132
+ CREATE INDEX IF NOT EXISTS idx_posts_author ON posts(author_id);
133
+ CREATE INDEX IF NOT EXISTS idx_posts_status ON posts(status) WHERE deleted IS NULL;
134
+ CREATE INDEX IF NOT EXISTS idx_comments_post ON comments(post_id);
135
+ CREATE INDEX IF NOT EXISTS idx_comments_user ON comments(user_id);
136
+ ```
137
+
138
+ > **Note**: The complete schema with indexes and seed data is available in `test/integration/schema.sql`
139
+
140
+ 3. **Configure environment variables**:
141
+
142
+ ```bash
143
+ cp .env.integration.example .env.integration
144
+ # Edit .env.integration with your Supabase credentials:
145
+ TEST_SUPABASE_URL=https://your-project-ref.supabase.co
146
+ TEST_SUPABASE_ANON_KEY=your-anon-key-here
147
+ ```
148
+
149
+ 4. **Run integration tests**:
150
+ ```bash
151
+ pnpm test:integration # Run once
152
+ pnpm test:integration:watch # Watch mode
153
+ pnpm test:integration:coverage # With coverage
154
+ ```
155
+
156
+ ### Option 2: Using Supabase CLI (Local)
157
+
158
+ 1. **Install Supabase CLI**:
159
+
160
+ ```bash
161
+ npm install -g supabase
162
+ ```
163
+
164
+ 2. **Start local Supabase**:
165
+
166
+ ```bash
167
+ supabase start
168
+ ```
169
+
170
+ 3. **Configure for local Supabase**:
171
+
172
+ ```bash
173
+ # .env.integration
174
+ TEST_SUPABASE_URL=http://localhost:54321
175
+ TEST_SUPABASE_ANON_KEY=your-local-anon-key # From supabase start output
176
+ ```
177
+
178
+ 4. **Run tests**:
179
+ ```bash
180
+ pnpm test:integration
181
+ ```
182
+
183
+ ## Available Test Scripts
184
+
185
+ ```json
186
+ {
187
+ "test": "Run all unit tests (no database required)",
188
+ "test:watch": "Run unit tests in watch mode",
189
+ "test:unit": "Run unit tests only",
190
+ "test:unit:watch": "Run unit tests in watch mode",
191
+ "test:unit:coverage": "Run unit tests with coverage",
192
+ "test:integration": "Run integration tests (requires database)",
193
+ "test:integration:watch": "Run integration tests in watch mode",
194
+ "test:integration:coverage": "Run integration tests with coverage",
195
+ "test:ci": "Run both unit and integration tests"
196
+ }
197
+ ```
198
+
199
+ ## Environment Variables
200
+
201
+ ### Integration Tests
202
+
203
+ - `TEST_SUPABASE_URL` - Your Supabase project URL
204
+ - `TEST_SUPABASE_ANON_KEY` - Your Supabase anonymous key
205
+ - `TEST_POSTGREST_URL` - Alternative: Direct PostgREST endpoint (for CI)
206
+ - `TEST_POSTGREST_ANON_KEY` - Alternative: JWT token for PostgREST
207
+
208
+ ### Legacy Support
209
+
210
+ These environment variables are also supported for backwards compatibility:
211
+
212
+ - `SUPABASE_TEST_URL`
213
+ - `SUPABASE_TEST_ANON_KEY`
214
+
215
+ ## Writing Integration Tests
216
+
217
+ Integration tests should be placed in `test/integration/` with the `.integration.spec.ts` suffix:
218
+
219
+ ```typescript
220
+ // test/integration/MyFeature.integration.spec.ts
221
+ import { beforeAll, describe, expect, it } from "vitest"
222
+ import { DatabaseSetup } from "./database-setup"
223
+
224
+ describe("My Feature Integration Tests", () => {
225
+ const dbSetup = new DatabaseSetup()
226
+
227
+ beforeAll(async () => {
228
+ await dbSetup.initialize()
229
+ await dbSetup.cleanupTestData()
230
+ })
231
+
232
+ it("should test my feature", async () => {
233
+ const client = dbSetup.getClient()
234
+
235
+ // Create test data
236
+ const testData = await dbSetup.createTestData()
237
+
238
+ // Test your feature using the query builder
239
+ const { data, error } = await client.from("users").select("*").eq("id", testData.userId)
240
+
241
+ expect(error).toBeNull()
242
+ expect(data).toBeDefined()
243
+ })
244
+ })
245
+ ```
246
+
247
+ ## Best Practices
248
+
249
+ 1. **Use DatabaseSetup**: Always use the `DatabaseSetup` class for consistent database initialization and cleanup
250
+
251
+ 2. **Clean Test Data**: Use test data prefixed with `test_` for easy cleanup:
252
+
253
+ ```typescript
254
+ email: "test_user@example.com"
255
+ title: "test_my_feature"
256
+ ```
257
+
258
+ 3. **Deterministic Tests**: Avoid relying on existing database state - create your own test data
259
+
260
+ 4. **Sequential Execution**: Integration tests run sequentially to avoid database conflicts
261
+
262
+ 5. **Error Handling**: Always check for both `error` and `data` in responses:
263
+
264
+ ```typescript
265
+ const { data, error } = await client.from("table").select("*")
266
+ expect(error).toBeNull()
267
+ expect(data).toBeDefined()
268
+ ```
269
+
270
+ 6. **Cleanup**: The `DatabaseSetup` class automatically cleans up test data before each run
271
+
272
+ ## CI/CD Integration
273
+
274
+ ### GitHub Actions Example
275
+
276
+ ```yaml
277
+ name: Integration Tests
278
+
279
+ on: [push, pull_request]
280
+
281
+ jobs:
282
+ test:
283
+ runs-on: ubuntu-latest
284
+
285
+ steps:
286
+ - uses: actions/checkout@v4
287
+
288
+ - name: Setup Node.js
289
+ uses: actions/setup-node@v4
290
+ with:
291
+ node-version: "20"
292
+
293
+ - name: Install dependencies
294
+ run: pnpm install
295
+
296
+ - name: Run unit tests
297
+ run: pnpm test:unit
298
+
299
+ - name: Run integration tests
300
+ env:
301
+ TEST_SUPABASE_URL: ${{ secrets.TEST_SUPABASE_URL }}
302
+ TEST_SUPABASE_ANON_KEY: ${{ secrets.TEST_SUPABASE_ANON_KEY }}
303
+ run: pnpm test:integration
304
+ ```
305
+
306
+ Add your Supabase credentials as GitHub secrets:
307
+
308
+ - `TEST_SUPABASE_URL`
309
+ - `TEST_SUPABASE_ANON_KEY`
310
+
311
+ ## Troubleshooting
312
+
313
+ ### "Database connection failed"
314
+
315
+ - Verify your `TEST_SUPABASE_URL` and `TEST_SUPABASE_ANON_KEY` are correct
316
+ - Check that your Supabase project is active and accessible
317
+ - Ensure you're using the correct URL format: `https://your-project.supabase.co`
318
+
319
+ ### "Table does not exist" errors
320
+
321
+ - Integration tests will skip gracefully if tables don't exist
322
+ - To run full integration tests, create the test schema (see setup instructions above)
323
+ - Alternatively, adjust tests to use your own database schema
324
+
325
+ ### Tests failing intermittently
326
+
327
+ - Integration tests run sequentially to avoid conflicts
328
+ - If tests fail intermittently, check for leftover test data
329
+ - Run cleanup manually: Create a test file that calls `dbSetup.cleanupTestData()`
330
+
331
+ ### "No environment variables" warning
332
+
333
+ - Create `.env.integration` file with your credentials
334
+ - Ensure the file is in the project root directory
335
+ - Check that file is not ignored by git (it should be in `.gitignore`)
336
+
337
+ ## Performance
338
+
339
+ - **Unit Tests**: Very fast (~10-50ms per test) - no database required
340
+ - **Integration Tests**: Moderate (~100-500ms per test) - requires database connection
341
+
342
+ Unit tests should always be preferred for fast feedback. Use integration tests to verify actual database behavior and catch issues that mocks might miss.
343
+
344
+ ## Security
345
+
346
+ - **Never commit** `.env.integration` or `.env.test` files to git
347
+ - Use separate Supabase projects for testing vs production
348
+ - Consider using Row Level Security (RLS) even for test projects
349
+ - Rotate anon keys periodically for test projects
package/dist/index.js CHANGED
@@ -42,9 +42,9 @@ const toError = (error) => {
42
42
  return new SupabaseError(error);
43
43
  };
44
44
  const log = {
45
- error: (msg) => console.error(`[supabase-typed-query] ${msg}`),
46
- warn: (msg) => console.warn(`[supabase-typed-query] ${msg}`),
47
- info: (msg) => console.info(`[supabase-typed-query] ${msg}`)
45
+ error: (msg) => process.env.NODE_ENV !== "test" && console.error(`[supabase-typed-query] ${msg}`),
46
+ warn: (msg) => process.env.NODE_ENV !== "test" && console.warn(`[supabase-typed-query] ${msg}`),
47
+ info: (msg) => process.env.NODE_ENV !== "test" && console.info(`[supabase-typed-query] ${msg}`)
48
48
  };
49
49
  const TABLES_WITHOUT_DELETED = /* @__PURE__ */ new Set([]);
50
50
  const wrapAsync$1 = (fn) => {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/utils/errors.ts","../src/query/QueryBuilder.ts","../src/query/Query.ts","../src/query/index.ts","../src/entity/Entity.ts"],"sourcesContent":["/**\n * Supabase/Postgrest error structure\n */\nexport type SupabaseErrorObject = {\n message: string\n code?: string\n details?: string\n hint?: string\n}\n\n/**\n * Custom Error class that preserves Supabase error details\n */\nexport class SupabaseError extends Error {\n readonly code?: string\n readonly details?: string\n readonly hint?: string\n\n constructor(error: SupabaseErrorObject | unknown) {\n // Check for Error instances FIRST before checking for Supabase error objects\n // because Error instances also have a message property\n if (error instanceof Error) {\n super(error.message)\n this.name = error.name\n this.stack = error.stack\n } else if (isSupabaseError(error)) {\n super(error.message)\n this.name = \"SupabaseError\"\n this.code = error.code\n this.details = error.details\n this.hint = error.hint\n } else {\n super(String(error))\n this.name = \"SupabaseError\"\n }\n }\n\n /**\n * Override toString to include all error details\n */\n override toString(): string {\n const parts = [this.message]\n if (this.code) parts.push(`[Code: ${this.code}]`)\n if (this.details) parts.push(`Details: ${this.details}`)\n if (this.hint) parts.push(`Hint: ${this.hint}`)\n return parts.join(\" | \")\n }\n}\n\n/**\n * Type guard for Supabase error objects\n */\nfunction isSupabaseError(error: unknown): error is SupabaseErrorObject {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as SupabaseErrorObject).message === \"string\"\n )\n}\n\n/**\n * Convert any error to a proper Error instance\n */\nexport const toError = (error: unknown): Error => {\n if (error instanceof Error) {\n return error\n }\n return new SupabaseError(error)\n}\n","import type { SupabaseClientType, TableNames, TableRow } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { Brand, FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok, Option } from \"functype\"\n\nimport type { IsConditions, MappedQuery, Query, QueryBuilderConfig, QueryCondition, WhereConditions } from \"./Query\"\n\n// Simple console logging for open source version\nconst log = {\n error: (msg: string) => console.error(`[supabase-typed-query] ${msg}`),\n warn: (msg: string) => console.warn(`[supabase-typed-query] ${msg}`),\n info: (msg: string) => console.info(`[supabase-typed-query] ${msg}`),\n}\n\n// Tables that don't have a deleted field (like version tracking tables)\n// Tables that don't have a deleted field - consumers can override this\nconst TABLES_WITHOUT_DELETED = new Set<string>([])\n\n/**\n * Functional QueryBuilder implementation using closures instead of classes\n */\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n // FPromise in newer functype versions is just a promise with additional methods\n // We can use the FPromise constructor if available, or cast it\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\nexport const QueryBuilder = <T extends TableNames>(\n client: SupabaseClientType,\n config: QueryBuilderConfig<T>,\n): Query<T> => {\n /**\n * Build the Supabase query from accumulated conditions\n */\n const buildSupabaseQuery = () => {\n const { table, conditions, order, limit, offset } = config\n\n // Start with base query (just the table reference)\n const baseQuery = client.from(table)\n\n // Handle multiple conditions with OR logic\n const queryWithConditions =\n conditions.length === 1 ? applyCondition(baseQuery, conditions[0]) : applyOrConditions(baseQuery, conditions)\n\n // Apply ordering if specified\n const queryWithOrder = order ? queryWithConditions.order(order[0], order[1]) : queryWithConditions\n\n // Apply pagination\n const finalQuery = (() => {\n if (limit && offset !== undefined) {\n // Use range for offset + limit\n return queryWithOrder.range(offset, offset + limit - 1)\n } else if (limit) {\n // Just limit\n return queryWithOrder.limit(limit)\n } else if (offset !== undefined) {\n // Just offset (need to use a large upper bound)\n return queryWithOrder.range(offset, Number.MAX_SAFE_INTEGER)\n }\n return queryWithOrder\n })()\n\n return finalQuery\n }\n\n /**\n * Apply a single condition to the query\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyCondition = (query: any, condition: QueryCondition<T>): any => {\n const { where, is, wherein, gt, gte, lt, lte, neq, like, ilike } = condition\n\n // Process WHERE conditions, extracting operators from the where object\n const processedWhere: Record<string, unknown> = {}\n const extractedOperators: {\n gt?: Record<string, unknown>\n gte?: Record<string, unknown>\n lt?: Record<string, unknown>\n lte?: Record<string, unknown>\n neq?: Record<string, unknown>\n like?: Record<string, string>\n ilike?: Record<string, string>\n } = {}\n\n if (where) {\n // Extract top-level operators from where object\n const {\n gt: whereGt,\n gte: whereGte,\n lt: whereLt,\n lte: whereLte,\n neq: whereNeq,\n like: whereLike,\n ilike: whereIlike,\n ...rest\n } = where as Record<string, unknown>\n\n // Store extracted operators\n if (whereGt) extractedOperators.gt = whereGt as Record<string, unknown>\n if (whereGte) extractedOperators.gte = whereGte as Record<string, unknown>\n if (whereLt) extractedOperators.lt = whereLt as Record<string, unknown>\n if (whereLte) extractedOperators.lte = whereLte as Record<string, unknown>\n if (whereNeq) extractedOperators.neq = whereNeq as Record<string, unknown>\n if (whereLike) extractedOperators.like = whereLike as Record<string, string>\n if (whereIlike) extractedOperators.ilike = whereIlike as Record<string, string>\n\n // Process remaining fields\n for (const [key, value] of Object.entries(rest)) {\n if (value && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Date)) {\n // Check if it's an operator object\n const ops = value as Record<string, unknown>\n if (ops.gte !== undefined) {\n extractedOperators.gte = {\n ...extractedOperators.gte,\n [key]: ops.gte,\n }\n }\n if (ops.gt !== undefined) {\n extractedOperators.gt = { ...extractedOperators.gt, [key]: ops.gt }\n }\n if (ops.lte !== undefined) {\n extractedOperators.lte = {\n ...extractedOperators.lte,\n [key]: ops.lte,\n }\n }\n if (ops.lt !== undefined) {\n extractedOperators.lt = { ...extractedOperators.lt, [key]: ops.lt }\n }\n if (ops.neq !== undefined) {\n extractedOperators.neq = {\n ...extractedOperators.neq,\n [key]: ops.neq,\n }\n }\n if (ops.like !== undefined) {\n extractedOperators.like = {\n ...extractedOperators.like,\n [key]: ops.like as string,\n }\n }\n if (ops.ilike !== undefined) {\n extractedOperators.ilike = {\n ...extractedOperators.ilike,\n [key]: ops.ilike as string,\n }\n }\n if (ops.in !== undefined) {\n // Handle IN operator\n if (!wherein) {\n const cond = condition as unknown as Record<string, unknown>\n cond.wherein = {}\n }\n const whereinObj = condition.wherein as Record<string, unknown>\n whereinObj[key] = ops.in\n }\n if (ops.is !== undefined) {\n // Handle IS operator\n if (!is) {\n const cond = condition as unknown as Record<string, unknown>\n cond.is = {}\n }\n const isObj = condition.is as Record<string, unknown>\n isObj[key] = ops.is\n }\n // If no operators found, treat as regular value\n if (!ops.gte && !ops.gt && !ops.lte && !ops.lt && !ops.neq && !ops.like && !ops.ilike && !ops.in && !ops.is) {\n processedWhere[key] = value\n }\n } else {\n // Regular value\n processedWhere[key] = value\n }\n }\n }\n\n // Merge extracted operators with explicitly passed operators\n const mergedGt = { ...gt, ...extractedOperators.gt }\n const mergedGte = { ...gte, ...extractedOperators.gte }\n const mergedLt = { ...lt, ...extractedOperators.lt }\n const mergedLte = { ...lte, ...extractedOperators.lte }\n const mergedNeq = { ...neq, ...extractedOperators.neq }\n const mergedLike = { ...like, ...extractedOperators.like }\n const mergedIlike = { ...ilike, ...extractedOperators.ilike }\n\n // Apply WHERE conditions\n const baseQuery = query.select(\"*\").match(processedWhere)\n\n // Apply soft delete filter based on softDeleteMode\n const queryWithSoftDelete = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return baseQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return baseQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return baseQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return baseQuery\n })()\n\n // Apply WHERE IN conditions\n const queryWithWhereIn = wherein\n ? List(Object.entries(wherein)).foldLeft(queryWithSoftDelete)((q, [column, values]) =>\n q.in(column, values as never),\n )\n : queryWithSoftDelete\n\n // Apply IS conditions\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithWhereIn)((q, [column, value]) =>\n q.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithWhereIn\n\n // Apply comparison operators using merged values\n const queryWithGt =\n Object.keys(mergedGt).length > 0\n ? Object.entries(mergedGt).reduce((q, [key, value]) => q.gt(key, value), queryWithIs)\n : queryWithIs\n\n const queryWithGte =\n Object.keys(mergedGte).length > 0\n ? Object.entries(mergedGte).reduce((q, [key, value]) => q.gte(key, value), queryWithGt)\n : queryWithGt\n\n const queryWithLt =\n Object.keys(mergedLt).length > 0\n ? Object.entries(mergedLt).reduce((q, [key, value]) => q.lt(key, value), queryWithGte)\n : queryWithGte\n\n const queryWithLte =\n Object.keys(mergedLte).length > 0\n ? Object.entries(mergedLte).reduce((q, [key, value]) => q.lte(key, value), queryWithLt)\n : queryWithLt\n\n const queryWithNeq =\n Object.keys(mergedNeq).length > 0\n ? Object.entries(mergedNeq).reduce((q, [key, value]) => q.neq(key, value), queryWithLte)\n : queryWithLte\n\n // Apply pattern matching using merged values\n const queryWithLike =\n Object.keys(mergedLike).length > 0\n ? Object.entries(mergedLike).reduce((q, [key, pattern]) => q.like(key, pattern as string), queryWithNeq)\n : queryWithNeq\n\n const queryWithIlike =\n Object.keys(mergedIlike).length > 0\n ? Object.entries(mergedIlike).reduce((q, [key, pattern]) => q.ilike(key, pattern as string), queryWithLike)\n : queryWithLike\n\n return queryWithIlike\n }\n\n /**\n * Apply multiple conditions with OR logic\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyOrConditions = (query: any, conditions: QueryCondition<T>[]): any => {\n // Start with select\n const selectQuery = query.select(\"*\")\n\n // Apply soft delete filter based on softDeleteMode\n const baseQuery = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return selectQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return selectQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return selectQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return selectQuery\n })()\n\n // Separate common conditions from varying conditions\n const commonConditions = new Map<string, unknown>()\n const varyingConditions: QueryCondition<T>[] = []\n\n // Find conditions that are common across all OR branches\n if (conditions.length > 0) {\n const firstCondition = conditions[0]\n\n // Check each key-value pair in the first condition\n Object.entries(firstCondition.where).forEach(([key, value]) => {\n // If this key-value pair exists in ALL conditions, it's common\n const isCommonCondition = conditions.every(\n (condition) => (condition.where as Record<string, unknown>)[key] === value,\n )\n\n if (isCommonCondition) {\n commonConditions.set(key, value)\n }\n })\n\n // Create new conditions with common parts removed\n varyingConditions.push(\n ...conditions.map((condition) => {\n const newWhere = { ...condition.where } as Record<string, unknown>\n commonConditions.forEach((_, key) => {\n delete newWhere[key]\n })\n return {\n where: newWhere as WhereConditions<TableRow<T>>,\n is: condition.is,\n wherein: condition.wherein,\n }\n }),\n )\n }\n\n // Apply common conditions first\n const queryWithCommon = Array.from(commonConditions.entries()).reduce((query, [key, value]) => {\n if (value === null) {\n return query.is(key, null)\n } else {\n return query.eq(key, value)\n }\n }, baseQuery)\n\n // If no varying conditions remain, we're done\n if (varyingConditions.every((condition) => Object.keys(condition.where).length === 0)) {\n return queryWithCommon\n }\n\n // Build OR conditions from the varying parts only\n const orConditions = varyingConditions\n .map((condition) => {\n const parts: string[] = []\n\n // Add WHERE conditions (only the varying ones)\n Object.entries(condition.where).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.eq.\"${value}\"`)\n }\n })\n\n // Add IS conditions\n if (condition.is) {\n Object.entries(condition.is).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.is.${value}`)\n }\n })\n }\n\n // Add WHERE IN conditions\n if (condition.wherein) {\n Object.entries(condition.wherein).forEach(([key, values]) => {\n if (values && Array.isArray(values) && values.length > 0) {\n const valueList = values.map((v: unknown) => `\"${v}\"`).join(\",\")\n parts.push(`${key}.in.(${valueList})`)\n }\n })\n }\n\n // Add comparison operators\n if (condition.gt) {\n Object.entries(condition.gt).forEach(([key, value]) => {\n parts.push(`${key}.gt.${value}`)\n })\n }\n if (condition.gte) {\n Object.entries(condition.gte).forEach(([key, value]) => {\n parts.push(`${key}.gte.${value}`)\n })\n }\n if (condition.lt) {\n Object.entries(condition.lt).forEach(([key, value]) => {\n parts.push(`${key}.lt.${value}`)\n })\n }\n if (condition.lte) {\n Object.entries(condition.lte).forEach(([key, value]) => {\n parts.push(`${key}.lte.${value}`)\n })\n }\n if (condition.neq) {\n Object.entries(condition.neq).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.not.is.null`)\n } else {\n parts.push(`${key}.neq.\"${value}\"`)\n }\n })\n }\n\n // Add pattern matching\n if (condition.like) {\n Object.entries(condition.like).forEach(([key, pattern]) => {\n parts.push(`${key}.like.\"${pattern}\"`)\n })\n }\n if (condition.ilike) {\n Object.entries(condition.ilike).forEach(([key, pattern]) => {\n parts.push(`${key}.ilike.\"${pattern}\"`)\n })\n }\n\n return parts.join(\",\")\n })\n .filter((condition) => condition.length > 0)\n\n // Apply OR conditions if any remain\n\n const finalQuery = orConditions.length > 0 ? queryWithCommon.or(orConditions.join(\",\")) : queryWithCommon\n\n return finalQuery\n }\n\n // Return the Query interface implementation\n return {\n /**\n * Add OR condition to the query\n */\n or: (where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T> => {\n const newConditions = [...config.conditions, { where, is }]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Filter by branded ID with type safety\n */\n whereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n const newConditions = [\n ...config.conditions,\n {\n where: { id: id as unknown } as unknown as WhereConditions<TableRow<T>>,\n },\n ]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Add OR condition with branded ID\n */\n orWhereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n return QueryBuilder(client, config).or({\n id: id as unknown,\n } as unknown as WhereConditions<TableRow<T>>)\n },\n\n /**\n * Apply mapping function to query results\n */\n map: <U>(fn: (item: TableRow<T>) => U): MappedQuery<U> => {\n return createMappedQuery(QueryBuilder(client, config), fn)\n },\n\n /**\n * Apply filter function to query results\n */\n filter: (predicate: (item: TableRow<T>) => boolean): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n filterFn: config.filterFn ? (item: TableRow<T>) => config.filterFn!(item) && predicate(item) : predicate,\n })\n },\n\n /**\n * Limit the number of results\n */\n limit: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n limit: count,\n })\n },\n\n /**\n * Offset the results for pagination\n */\n offset: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n offset: count,\n })\n },\n\n /**\n * Include all records (no soft delete filter)\n */\n includeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"include\") {\n log.warn(`[${config.table}] includeDeleted() called but already including deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"include\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Exclude soft-deleted records (apply deleted IS NULL filter)\n */\n excludeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"exclude\") {\n log.warn(`[${config.table}] excludeDeleted() called but already excluding deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"exclude\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Query only soft-deleted records (apply deleted IS NOT NULL filter)\n */\n onlyDeleted: (): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"only\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Execute query expecting exactly one result\n */\n one: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query.single()\n\n if (error) {\n log.error(`Error getting ${config.table} item: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n\n const result = data as TableRow<T>\n const filteredResult = config.filterFn ? config.filterFn(result) : true\n\n if (!filteredResult) {\n return Ok(Option.none<TableRow<T>>())\n }\n\n return Ok(Option(result))\n } catch (error) {\n log.error(`Error executing single query on ${config.table}: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting zero or more results\n */\n many: (): FPromise<TaskOutcome<List<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query\n\n if (error) {\n log.error(`Error getting ${config.table} items: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n const rawResults = data as TableRow<T>[]\n\n // Apply filter if present\n const results = config.filterFn ? rawResults.filter(config.filterFn) : rawResults\n\n return Ok(List(results))\n } catch (error) {\n log.error(`Error executing multi query on ${config.table}: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting first result from potentially multiple\n */\n first: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n const manyResult = await QueryBuilder(client, config).many()\n const list = manyResult.orThrow()\n if (list.isEmpty) {\n return Ok(Option.none<TableRow<T>>())\n }\n return Ok(Option(list.head))\n })\n },\n\n /**\n * Execute query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found in ${config.table}`))\n },\n\n /**\n * Execute query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<TableRow<T>>> => {\n const result = await QueryBuilder(client, config).many()\n return result.orThrow()\n },\n\n /**\n * Execute query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found in ${config.table}`))\n },\n }\n}\n\n/**\n * Functional MappedQuery implementation\n */\nconst createMappedQuery = <T extends TableNames, U>(\n sourceQuery: Query<T>,\n mapFn: (item: TableRow<T>) => U,\n): MappedQuery<U> => {\n return {\n map: <V>(fn: (item: U) => V): MappedQuery<V> => {\n return createMappedQuery(sourceQuery, (item: TableRow<T>) => fn(mapFn(item)))\n },\n\n filter: (predicate: (item: U) => boolean): MappedQuery<U> => {\n const filteredQuery = sourceQuery.filter((item: TableRow<T>) => predicate(mapFn(item)))\n return createMappedQuery(filteredQuery, mapFn)\n },\n\n one: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.one()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n many: (): FPromise<TaskOutcome<List<U>>> => {\n return wrapAsync(async () => {\n const itemsResult = await sourceQuery.many()\n const items = itemsResult.orThrow()\n return Ok(items.map(mapFn))\n })\n },\n\n first: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.first()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n /**\n * Execute mapped query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found`))\n },\n\n /**\n * Execute mapped query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<U>> => {\n const result = await createMappedQuery(sourceQuery, mapFn).many()\n return result.orThrow()\n },\n\n /**\n * Execute mapped query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found`))\n },\n }\n}\n\n/**\n * Factory function to create new functional QueryBuilder instances\n */\nexport const createQuery = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditions<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n softDeleteConfig?: { mode?: \"include\" | \"exclude\" | \"only\"; appliedByDefault?: boolean },\n): Query<T> => {\n const config: QueryBuilderConfig<T> = {\n table,\n conditions: [{ where, is, wherein }],\n order,\n softDeleteMode: softDeleteConfig?.mode,\n softDeleteAppliedByDefault: softDeleteConfig?.appliedByDefault,\n }\n return QueryBuilder(client, config)\n}\n","import type { EmptyObject, TableNames, TableRow } from \"@/types\"\n\nimport type { Brand, FPromise, List, Option, TaskOutcome } from \"functype\"\n\n// Comparison operators for advanced queries\nexport type ComparisonOperators<V> = {\n gte?: V // Greater than or equal\n gt?: V // Greater than\n lte?: V // Less than or equal\n lt?: V // Less than\n neq?: V // Not equal\n like?: string // LIKE pattern (for string fields)\n ilike?: string // Case-insensitive LIKE\n in?: V[] // IN array\n is?: null | boolean // IS NULL/TRUE/FALSE\n}\n\n// Type-safe WHERE conditions that provide IntelliSense for table columns\n// Supports both direct values and operator objects for advanced queries\nexport type WhereConditions<T extends object> = Partial<{\n [K in keyof T]: T[K] | null | ComparisonOperators<T[K]>\n}> & {\n // Special operators that work across columns with type-safe values\n gte?: Partial<{ [K in keyof T]?: T[K] }>\n gt?: Partial<{ [K in keyof T]?: T[K] }>\n lte?: Partial<{ [K in keyof T]?: T[K] }>\n lt?: Partial<{ [K in keyof T]?: T[K] }>\n neq?: Partial<{ [K in keyof T]?: T[K] }>\n like?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n ilike?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n}\n\n// Enhanced type for IS conditions with field-level type safety\nexport type IsConditions<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Soft delete mode for controlling how deleted records are handled\nexport type SoftDeleteMode = \"include\" | \"exclude\" | \"only\"\n\n// =============================================================================\n// Standard Execution Interfaces for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Base execution interface that all database operations implement\n */\nexport interface ExecutableQuery<T> {\n // TaskOutcome version (for explicit error handling)\n execute(): FPromise<TaskOutcome<T>>\n\n // OrThrow version (for simple error handling)\n executeOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return a single result\n */\nexport interface SingleExecution<T> extends ExecutableQuery<Option<T>> {\n one(): FPromise<TaskOutcome<Option<T>>>\n oneOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return multiple results\n */\nexport interface MultiExecution<T> extends ExecutableQuery<List<T>> {\n many(): FPromise<TaskOutcome<List<T>>>\n manyOrThrow(): Promise<List<T>>\n}\n\n// Branded type support for query conditions\nexport type BrandedWhereParams<T extends object = EmptyObject> = {\n [K in keyof T]?: T[K] | unknown // Simplified to avoid complex conditional types\n}\n\n// Helper type for branded field values\nexport type BrandedFieldValue<T> = T extends Brand<string, infer BaseType> ? T | BaseType : T\n\n// Core Query interface with branded type support\nexport interface Query<T extends TableNames> {\n // Execution methods - explicit about expected results\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<TableRow<T>>\n manyOrThrow(): Promise<List<TableRow<T>>>\n firstOrThrow(): Promise<TableRow<T>>\n\n // Query composition - chainable OR logic with type-safe where conditions\n or(where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T>\n\n // Branded type-aware query methods (simplified)\n whereId<ID extends Brand<string, string>>(id: ID): Query<T>\n orWhereId<ID extends Brand<string, string>>(id: ID): Query<T>\n\n // Functional operations - maintain composability\n map<U>(fn: (item: TableRow<T>) => U): MappedQuery<U>\n filter(predicate: (item: TableRow<T>) => boolean): Query<T>\n\n // Pagination\n limit(count: number): Query<T>\n offset(count: number): Query<T>\n\n // Soft delete filtering\n includeDeleted(): Query<T>\n excludeDeleted(): Query<T>\n onlyDeleted(): Query<T>\n}\n\n// Mapped query for transformed results\nexport interface MappedQuery<U> {\n one(): FPromise<TaskOutcome<Option<U>>>\n many(): FPromise<TaskOutcome<List<U>>>\n first(): FPromise<TaskOutcome<Option<U>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<U>\n manyOrThrow(): Promise<List<U>>\n firstOrThrow(): Promise<U>\n\n // Continue chaining\n map<V>(fn: (item: U) => V): MappedQuery<V>\n filter(predicate: (item: U) => boolean): MappedQuery<U>\n}\n\n// Query condition for internal state management with type-safe where\nexport interface QueryCondition<T extends TableNames> {\n where: WhereConditions<TableRow<T>>\n is?: IsConditions<TableRow<T>>\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>\n // Comparison operators\n gt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n gte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n neq?: Partial<Record<keyof TableRow<T>, unknown>>\n // Pattern matching\n like?: Partial<Record<keyof TableRow<T>, string>>\n ilike?: Partial<Record<keyof TableRow<T>, string>>\n}\n\n// Entity-specific query interfaces for better type safety\nexport interface EntityQuery<T extends TableNames> extends Query<T> {\n // Entity-specific methods can be added here\n normalize(): NormalizedQuery<T>\n}\n\nexport interface NormalizedQuery<T extends TableNames> {\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n}\n\n// Type guards for runtime type checking\nexport const isQuery = <T extends TableNames>(obj: unknown): obj is Query<T> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"or\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\nexport const isMappedQuery = <U>(obj: unknown): obj is MappedQuery<U> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\n// Utility types for query parameters with type safety\nexport type QueryWhereParams<T extends TableNames> = WhereConditions<TableRow<T>>\nexport type QueryIsParams<T extends TableNames> = IsConditions<TableRow<T>>\nexport type QueryWhereinParams<T extends TableNames> = Partial<Record<keyof TableRow<T>, unknown[]>>\nexport type QueryOrderParams<T extends TableNames> = [\n keyof TableRow<T> & string,\n { ascending?: boolean; nullsFirst?: boolean },\n]\n\n// Builder configuration for query construction\nexport interface QueryBuilderConfig<T extends TableNames> {\n table: T\n conditions: QueryCondition<T>[]\n order?: QueryOrderParams<T>\n mapFn?: (item: TableRow<T>) => unknown\n filterFn?: (item: TableRow<T>) => boolean\n limit?: number\n offset?: number\n softDeleteMode?: SoftDeleteMode\n softDeleteAppliedByDefault?: boolean\n}\n","import type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok } from \"functype\"\n\nimport type { Query, WhereConditions } from \"./Query\"\nimport { createQuery } from \"./QueryBuilder\"\n\n// Re-export query types\nexport type {\n ComparisonOperators,\n EntityQuery,\n ExecutableQuery,\n IsConditions,\n MappedQuery,\n MultiExecution,\n Query,\n QueryBuilderConfig,\n QueryCondition,\n QueryIsParams,\n QueryOrderParams,\n QueryWhereinParams,\n QueryWhereParams,\n SingleExecution,\n SoftDeleteMode,\n WhereConditions,\n} from \"./Query\"\n\n// Re-export type guards\nexport { isMappedQuery, isQuery } from \"./Query\"\n\n// Local type for IS conditions\ntype IsConditionsLocal<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\n/**\n * Retrieves a single entity from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @returns A promise resolving to the entity if found\n */\nexport const getEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(baseQuery)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : baseQuery\n\n const { data, error } = await queryWithIs.single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Retrieves multiple entities from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A promise resolving to the entities if found\n */\nexport const getEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }] = [\n \"id\" as keyof TableRow<T> & string,\n { ascending: true },\n ],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const queryOrderBy = queryWithIs.order(order[0], order[1])\n\n const { data, error } = await queryOrderBy\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Adds multiple entities to the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to insert into\n * @param entities - The entities to add\n * @returns A promise resolving to the added entities\n */\nexport const addEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableInsert<T>[],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const { data, error } = await client\n .from(table)\n .insert(entities as never)\n .select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as unknown as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Updates a single entity in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entity data to update\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entity\n */\nexport const updateEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client\n .from(table)\n .update(entities as never)\n .match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select().single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Updates multiple entities in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entities to update\n * @param identity - The column(s) to use as the identity\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entities\n */\nexport const updateEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>[],\n identity: (keyof TableRow<T> & string) | (keyof TableRow<T> & string)[] = \"id\" as keyof TableRow<T> & string,\n where?: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const onConflict = Array.isArray(identity) ? identity.join(\",\") : identity\n\n const baseQuery = client\n .from(table)\n .upsert(entities as never, { onConflict })\n .match(where ?? {})\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Creates a new Query for the specified table with initial conditions.\n * This is the new Query-based API that supports OR chaining and functional operations.\n *\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Initial WHERE conditions to filter by\n * @param is - Initial IS conditions to filter by\n * @param wherein - Initial WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A Query<T> instance that supports chaining and lazy evaluation\n *\n * @example\n * // Simple query\n * const user = await query(client, \"users\", { id: \"123\" }).one()\n *\n * @example\n * // Query with OR logic\n * const users = await query(client, \"users\", { role: \"admin\" })\n * .or({ role: \"moderator\" })\n * .many()\n *\n * @example\n * // Query with functional operations\n * const names = await query(client, \"users\", { active: true })\n * .map(user => user.name)\n * .filter(name => name.startsWith('A'))\n * .many()\n */\nexport const query = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n): Query<T> => {\n return createQuery(client, table, where, is, wherein, order)\n}\n","import { addEntities, updateEntities, updateEntity } from \"@/query\"\nimport type { MultiExecution, Query, SingleExecution, WhereConditions } from \"@/query/Query\"\nimport { createQuery } from \"@/query/QueryBuilder\"\nimport type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\n\nimport type { FPromise, List, TaskOutcome } from \"functype\"\nimport { Option } from \"functype\"\n\n// Field-level type safety for queries\nexport type TypedRecord<T, V> = Partial<Record<keyof T, V>>\n\n// Entity configuration\nexport type EntityConfig = {\n /** Soft delete filtering. true = exclude deleted items, false = include deleted items */\n softDelete: boolean\n /** Partition key for multi-tenant isolation. e.g., { tenant_id: \"123\" } */\n partitionKey?: Record<string, unknown>\n}\n\n// Base parameter types with field-level type safety\nexport type WhereParams<T extends object = EmptyObject> = {\n where?: WhereConditions<T>\n}\n\nexport type IsParams<T extends object = EmptyObject> = {\n is?: TypedRecord<T, null | boolean>\n}\n\nexport type WhereinParams<T extends object = EmptyObject> = {\n wherein?: TypedRecord<T, unknown[]>\n}\n\nexport type OrderParams<T extends object = EmptyObject> = {\n order?: [keyof T & string, { ascending?: boolean; nullsFirst?: boolean }]\n}\n\nexport type IdParam = {\n id: string\n}\n\n// Composable parameter types with field-level type safety\nexport type GetItemParams<T extends object = EmptyObject> = IdParam & WhereParams<T> & IsParams<T>\n\nexport type GetItemsParams<T extends object = EmptyObject> = WhereParams<T> &\n IsParams<T> &\n WhereinParams<T> &\n OrderParams<T>\n\nexport type AddItemsParams<T extends TableNames> = {\n items: TableInsert<T>[]\n}\n\nexport type UpdateItemParams<T extends TableNames, Row extends object = EmptyObject> = IdParam & {\n item: TableUpdate<T>\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\nexport type UpdateItemsParams<T extends TableNames, Row extends object = EmptyObject> = {\n items: TableUpdate<T>[]\n identity?: (keyof Row & string) | (keyof Row & string)[]\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\n// =============================================================================\n// Mutation Query Wrappers for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Wrapper type for multi-result mutation operations that implements standard execution interface\n */\nexport type MutationMultiExecution<T> = FPromise<TaskOutcome<List<T>>> & MultiExecution<T>\n\n/**\n * Wrapper type for single-result mutation operations that implements standard execution interface\n */\nexport type MutationSingleExecution<T> = FPromise<TaskOutcome<T>> & SingleExecution<T>\n\n/**\n * Creates a multi-result mutation query that implements the standard execution interface\n */\nexport function MultiMutationQuery<T>(promise: FPromise<TaskOutcome<List<T>>>): MutationMultiExecution<T> {\n const result = Object.assign(promise, {\n // Standard MultiExecution interface\n many: () => promise,\n manyOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise,\n executeOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n })\n return result as MutationMultiExecution<T>\n}\n\n/**\n * Creates a single-result mutation query that implements the standard execution interface\n */\nexport function SingleMutationQuery<T>(promise: FPromise<TaskOutcome<T>>): MutationSingleExecution<T> {\n const result = Object.assign(promise, {\n // Standard SingleExecution interface\n one: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n oneOrThrow: async (): Promise<T> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n executeOrThrow: async (): Promise<Option<T>> => {\n const taskResult = await promise\n const value = taskResult.orThrow()\n return Option(value)\n },\n })\n return result as MutationSingleExecution<T>\n}\n\n/**\n * Base interface for Entity instances\n */\nexport type IEntity<T extends TableNames> = {\n getItem(params: GetItemParams<TableRow<T>>): Query<T>\n getItems(params?: GetItemsParams<TableRow<T>>): Query<T>\n addItems(params: AddItemsParams<T>): MutationMultiExecution<TableRow<T>>\n updateItem(params: UpdateItemParams<T, TableRow<T>>): MutationSingleExecution<TableRow<T>>\n updateItems(params: UpdateItemsParams<T, TableRow<T>>): MutationMultiExecution<TableRow<T>>\n}\n\n/**\n * Creates an entity interface with methods for interacting with the given table.\n * @param client The Supabase client instance to use for queries.\n * @param name The name of the table to interact with.\n * @param config Configuration for entity behavior (required).\n * @returns An object with methods for interacting with the table.\n */\nexport const Entity = <T extends TableNames>(client: SupabaseClientType, name: T, config: EntityConfig): IEntity<T> => {\n type ROW = TableRow<T>\n\n const softDeleteMode = config.softDelete ? \"exclude\" : \"include\"\n\n /**\n * Retrieve a single item from the given table by ID.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemParams<ROW>} params Parameters.\n * @param {string} params.id The ID of the item to retrieve.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItem({ id, where, is }: GetItemParams<ROW>): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where, id } : { ...where, id }\n return createQuery(\n client,\n name,\n whereWithPartition as unknown as WhereConditions<TableRow<T>>,\n is,\n undefined,\n undefined,\n { mode: softDeleteMode, appliedByDefault: true },\n )\n }\n\n /**\n * Get a list of items from the given table filtered by the given conditions.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemsParams<ROW>} params Optional parameters.\n * @param {TypedRecord<ROW, unknown>} [params.where] Conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @param {[keyof ROW & string, { ascending?: boolean; nullsFirst?: boolean }]} [params.order] Optional ordering parameters.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItems({ where, is, wherein, order }: GetItemsParams<ROW> = {}): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where } : where\n return createQuery(client, name, whereWithPartition as WhereConditions<TableRow<T>>, is, wherein, order, {\n mode: softDeleteMode,\n appliedByDefault: true,\n })\n }\n\n /**\n * Adds multiple items to the given table.\n * @param {AddItemsParams<T>} params Parameters.\n * @param {TableInsert<T>[]} params.items The items to add.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function addItems({ items }: AddItemsParams<T>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(addEntities(client, name, items))\n }\n\n /**\n * Update a single item in the given table.\n * @param {UpdateItemParams<T, ROW>} params Parameters.\n * @param {string} params.id The ID of the item to update.\n * @param {Partial<TableUpdate<T>>} params.item The item to update.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationSingleExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItem({ id, item, where, is, wherein }: UpdateItemParams<T, ROW>): MutationSingleExecution<ROW> {\n return SingleMutationQuery(\n updateEntity(client, name, item, { ...where, id } as unknown as WhereConditions<TableRow<T>>, is, wherein),\n )\n }\n\n /**\n * Update multiple items in the given table.\n * @param {UpdateItemsParams<T, ROW>} params Parameters.\n * @param {TableUpdate<T>[]} params.items The items to update.\n * @param {keyof ROW & string | (keyof ROW & string)[]} [params.identity=\"id\"] The column(s) to use as the identity.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItems({\n items,\n identity = \"id\" as keyof ROW & string,\n where,\n is,\n wherein,\n }: UpdateItemsParams<T, ROW>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(updateEntities(client, name, items, identity, where, is, wherein))\n }\n\n return {\n getItem,\n getItems,\n addItems,\n updateItem,\n updateItems,\n }\n}\n\n/**\n * Type for an entity instance for a specific table\n * @deprecated Use IEntity<T> instead\n */\nexport type EntityType<T extends TableNames> = IEntity<T>\n"],"names":["wrapAsync","query","List","Err","Ok","Option"],"mappings":";;;AAaO,MAAM,sBAAsB,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YA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AA,IACA;AAAA,IACA;AAAA,EAAA,GACyD;AACzD,WAAO,mBAAmB,eAAe,QAAQ,MAAM,OAAO,UAAU,OAAO,IAAI,OAAO,CAAC;AAAA,EAC7F;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/utils/errors.ts","../src/query/QueryBuilder.ts","../src/query/Query.ts","../src/query/index.ts","../src/entity/Entity.ts"],"sourcesContent":["/**\n * Supabase/Postgrest error structure\n */\nexport type SupabaseErrorObject = {\n message: string\n code?: string\n details?: string\n hint?: string\n}\n\n/**\n * Custom Error class that preserves Supabase error details\n */\nexport class SupabaseError extends Error {\n readonly code?: string\n readonly details?: string\n readonly hint?: string\n\n constructor(error: SupabaseErrorObject | unknown) {\n // Check for Error instances FIRST before checking for Supabase error objects\n // because Error instances also have a message property\n if (error instanceof Error) {\n super(error.message)\n this.name = error.name\n this.stack = error.stack\n } else if (isSupabaseError(error)) {\n super(error.message)\n this.name = \"SupabaseError\"\n this.code = error.code\n this.details = error.details\n this.hint = error.hint\n } else {\n super(String(error))\n this.name = \"SupabaseError\"\n }\n }\n\n /**\n * Override toString to include all error details\n */\n override toString(): string {\n const parts = [this.message]\n if (this.code) parts.push(`[Code: ${this.code}]`)\n if (this.details) parts.push(`Details: ${this.details}`)\n if (this.hint) parts.push(`Hint: ${this.hint}`)\n return parts.join(\" | \")\n }\n}\n\n/**\n * Type guard for Supabase error objects\n */\nfunction isSupabaseError(error: unknown): error is SupabaseErrorObject {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as SupabaseErrorObject).message === \"string\"\n )\n}\n\n/**\n * Convert any error to a proper Error instance\n */\nexport const toError = (error: unknown): Error => {\n if (error instanceof Error) {\n return error\n }\n return new SupabaseError(error)\n}\n","import type { SupabaseClientType, TableNames, TableRow } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { Brand, FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok, Option } from \"functype\"\n\nimport type { IsConditions, MappedQuery, Query, QueryBuilderConfig, QueryCondition, WhereConditions } from \"./Query\"\n\n// Simple console logging for open source version\n// Suppress logs during tests to avoid stderr noise in test output\nconst log = {\n error: (msg: string) => process.env.NODE_ENV !== \"test\" && console.error(`[supabase-typed-query] ${msg}`),\n warn: (msg: string) => process.env.NODE_ENV !== \"test\" && console.warn(`[supabase-typed-query] ${msg}`),\n info: (msg: string) => process.env.NODE_ENV !== \"test\" && console.info(`[supabase-typed-query] ${msg}`),\n}\n\n// Tables that don't have a deleted field (like version tracking tables)\n// Tables that don't have a deleted field - consumers can override this\nconst TABLES_WITHOUT_DELETED = new Set<string>([])\n\n/**\n * Functional QueryBuilder implementation using closures instead of classes\n */\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n // FPromise in newer functype versions is just a promise with additional methods\n // We can use the FPromise constructor if available, or cast it\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\nexport const QueryBuilder = <T extends TableNames>(\n client: SupabaseClientType,\n config: QueryBuilderConfig<T>,\n): Query<T> => {\n /**\n * Build the Supabase query from accumulated conditions\n */\n const buildSupabaseQuery = () => {\n const { table, conditions, order, limit, offset } = config\n\n // Start with base query (just the table reference)\n const baseQuery = client.from(table)\n\n // Handle multiple conditions with OR logic\n const queryWithConditions =\n conditions.length === 1 ? applyCondition(baseQuery, conditions[0]) : applyOrConditions(baseQuery, conditions)\n\n // Apply ordering if specified\n const queryWithOrder = order ? queryWithConditions.order(order[0], order[1]) : queryWithConditions\n\n // Apply pagination\n const finalQuery = (() => {\n if (limit && offset !== undefined) {\n // Use range for offset + limit\n return queryWithOrder.range(offset, offset + limit - 1)\n } else if (limit) {\n // Just limit\n return queryWithOrder.limit(limit)\n } else if (offset !== undefined) {\n // Just offset (need to use a large upper bound)\n return queryWithOrder.range(offset, Number.MAX_SAFE_INTEGER)\n }\n return queryWithOrder\n })()\n\n return finalQuery\n }\n\n /**\n * Apply a single condition to the query\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyCondition = (query: any, condition: QueryCondition<T>): any => {\n const { where, is, wherein, gt, gte, lt, lte, neq, like, ilike } = condition\n\n // Process WHERE conditions, extracting operators from the where object\n const processedWhere: Record<string, unknown> = {}\n const extractedOperators: {\n gt?: Record<string, unknown>\n gte?: Record<string, unknown>\n lt?: Record<string, unknown>\n lte?: Record<string, unknown>\n neq?: Record<string, unknown>\n like?: Record<string, string>\n ilike?: Record<string, string>\n } = {}\n\n if (where) {\n // Extract top-level operators from where object\n const {\n gt: whereGt,\n gte: whereGte,\n lt: whereLt,\n lte: whereLte,\n neq: whereNeq,\n like: whereLike,\n ilike: whereIlike,\n ...rest\n } = where as Record<string, unknown>\n\n // Store extracted operators\n if (whereGt) extractedOperators.gt = whereGt as Record<string, unknown>\n if (whereGte) extractedOperators.gte = whereGte as Record<string, unknown>\n if (whereLt) extractedOperators.lt = whereLt as Record<string, unknown>\n if (whereLte) extractedOperators.lte = whereLte as Record<string, unknown>\n if (whereNeq) extractedOperators.neq = whereNeq as Record<string, unknown>\n if (whereLike) extractedOperators.like = whereLike as Record<string, string>\n if (whereIlike) extractedOperators.ilike = whereIlike as Record<string, string>\n\n // Process remaining fields\n for (const [key, value] of Object.entries(rest)) {\n if (value && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Date)) {\n // Check if it's an operator object\n const ops = value as Record<string, unknown>\n if (ops.gte !== undefined) {\n extractedOperators.gte = {\n ...extractedOperators.gte,\n [key]: ops.gte,\n }\n }\n if (ops.gt !== undefined) {\n extractedOperators.gt = { ...extractedOperators.gt, [key]: ops.gt }\n }\n if (ops.lte !== undefined) {\n extractedOperators.lte = {\n ...extractedOperators.lte,\n [key]: ops.lte,\n }\n }\n if (ops.lt !== undefined) {\n extractedOperators.lt = { ...extractedOperators.lt, [key]: ops.lt }\n }\n if (ops.neq !== undefined) {\n extractedOperators.neq = {\n ...extractedOperators.neq,\n [key]: ops.neq,\n }\n }\n if (ops.like !== undefined) {\n extractedOperators.like = {\n ...extractedOperators.like,\n [key]: ops.like as string,\n }\n }\n if (ops.ilike !== undefined) {\n extractedOperators.ilike = {\n ...extractedOperators.ilike,\n [key]: ops.ilike as string,\n }\n }\n if (ops.in !== undefined) {\n // Handle IN operator\n if (!wherein) {\n const cond = condition as unknown as Record<string, unknown>\n cond.wherein = {}\n }\n const whereinObj = condition.wherein as Record<string, unknown>\n whereinObj[key] = ops.in\n }\n if (ops.is !== undefined) {\n // Handle IS operator\n if (!is) {\n const cond = condition as unknown as Record<string, unknown>\n cond.is = {}\n }\n const isObj = condition.is as Record<string, unknown>\n isObj[key] = ops.is\n }\n // If no operators found, treat as regular value\n if (!ops.gte && !ops.gt && !ops.lte && !ops.lt && !ops.neq && !ops.like && !ops.ilike && !ops.in && !ops.is) {\n processedWhere[key] = value\n }\n } else {\n // Regular value\n processedWhere[key] = value\n }\n }\n }\n\n // Merge extracted operators with explicitly passed operators\n const mergedGt = { ...gt, ...extractedOperators.gt }\n const mergedGte = { ...gte, ...extractedOperators.gte }\n const mergedLt = { ...lt, ...extractedOperators.lt }\n const mergedLte = { ...lte, ...extractedOperators.lte }\n const mergedNeq = { ...neq, ...extractedOperators.neq }\n const mergedLike = { ...like, ...extractedOperators.like }\n const mergedIlike = { ...ilike, ...extractedOperators.ilike }\n\n // Apply WHERE conditions\n const baseQuery = query.select(\"*\").match(processedWhere)\n\n // Apply soft delete filter based on softDeleteMode\n const queryWithSoftDelete = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return baseQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return baseQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return baseQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return baseQuery\n })()\n\n // Apply WHERE IN conditions\n const queryWithWhereIn = wherein\n ? List(Object.entries(wherein)).foldLeft(queryWithSoftDelete)((q, [column, values]) =>\n q.in(column, values as never),\n )\n : queryWithSoftDelete\n\n // Apply IS conditions\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithWhereIn)((q, [column, value]) =>\n q.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithWhereIn\n\n // Apply comparison operators using merged values\n const queryWithGt =\n Object.keys(mergedGt).length > 0\n ? Object.entries(mergedGt).reduce((q, [key, value]) => q.gt(key, value), queryWithIs)\n : queryWithIs\n\n const queryWithGte =\n Object.keys(mergedGte).length > 0\n ? Object.entries(mergedGte).reduce((q, [key, value]) => q.gte(key, value), queryWithGt)\n : queryWithGt\n\n const queryWithLt =\n Object.keys(mergedLt).length > 0\n ? Object.entries(mergedLt).reduce((q, [key, value]) => q.lt(key, value), queryWithGte)\n : queryWithGte\n\n const queryWithLte =\n Object.keys(mergedLte).length > 0\n ? Object.entries(mergedLte).reduce((q, [key, value]) => q.lte(key, value), queryWithLt)\n : queryWithLt\n\n const queryWithNeq =\n Object.keys(mergedNeq).length > 0\n ? Object.entries(mergedNeq).reduce((q, [key, value]) => q.neq(key, value), queryWithLte)\n : queryWithLte\n\n // Apply pattern matching using merged values\n const queryWithLike =\n Object.keys(mergedLike).length > 0\n ? Object.entries(mergedLike).reduce((q, [key, pattern]) => q.like(key, pattern as string), queryWithNeq)\n : queryWithNeq\n\n const queryWithIlike =\n Object.keys(mergedIlike).length > 0\n ? Object.entries(mergedIlike).reduce((q, [key, pattern]) => q.ilike(key, pattern as string), queryWithLike)\n : queryWithLike\n\n return queryWithIlike\n }\n\n /**\n * Apply multiple conditions with OR logic\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyOrConditions = (query: any, conditions: QueryCondition<T>[]): any => {\n // Start with select\n const selectQuery = query.select(\"*\")\n\n // Apply soft delete filter based on softDeleteMode\n const baseQuery = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return selectQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return selectQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return selectQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return selectQuery\n })()\n\n // Separate common conditions from varying conditions\n const commonConditions = new Map<string, unknown>()\n const varyingConditions: QueryCondition<T>[] = []\n\n // Find conditions that are common across all OR branches\n if (conditions.length > 0) {\n const firstCondition = conditions[0]\n\n // Check each key-value pair in the first condition\n Object.entries(firstCondition.where).forEach(([key, value]) => {\n // If this key-value pair exists in ALL conditions, it's common\n const isCommonCondition = conditions.every(\n (condition) => (condition.where as Record<string, unknown>)[key] === value,\n )\n\n if (isCommonCondition) {\n commonConditions.set(key, value)\n }\n })\n\n // Create new conditions with common parts removed\n varyingConditions.push(\n ...conditions.map((condition) => {\n const newWhere = { ...condition.where } as Record<string, unknown>\n commonConditions.forEach((_, key) => {\n delete newWhere[key]\n })\n return {\n where: newWhere as WhereConditions<TableRow<T>>,\n is: condition.is,\n wherein: condition.wherein,\n }\n }),\n )\n }\n\n // Apply common conditions first\n const queryWithCommon = Array.from(commonConditions.entries()).reduce((query, [key, value]) => {\n if (value === null) {\n return query.is(key, null)\n } else {\n return query.eq(key, value)\n }\n }, baseQuery)\n\n // If no varying conditions remain, we're done\n if (varyingConditions.every((condition) => Object.keys(condition.where).length === 0)) {\n return queryWithCommon\n }\n\n // Build OR conditions from the varying parts only\n const orConditions = varyingConditions\n .map((condition) => {\n const parts: string[] = []\n\n // Add WHERE conditions (only the varying ones)\n Object.entries(condition.where).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.eq.\"${value}\"`)\n }\n })\n\n // Add IS conditions\n if (condition.is) {\n Object.entries(condition.is).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.is.${value}`)\n }\n })\n }\n\n // Add WHERE IN conditions\n if (condition.wherein) {\n Object.entries(condition.wherein).forEach(([key, values]) => {\n if (values && Array.isArray(values) && values.length > 0) {\n const valueList = values.map((v: unknown) => `\"${v}\"`).join(\",\")\n parts.push(`${key}.in.(${valueList})`)\n }\n })\n }\n\n // Add comparison operators\n if (condition.gt) {\n Object.entries(condition.gt).forEach(([key, value]) => {\n parts.push(`${key}.gt.${value}`)\n })\n }\n if (condition.gte) {\n Object.entries(condition.gte).forEach(([key, value]) => {\n parts.push(`${key}.gte.${value}`)\n })\n }\n if (condition.lt) {\n Object.entries(condition.lt).forEach(([key, value]) => {\n parts.push(`${key}.lt.${value}`)\n })\n }\n if (condition.lte) {\n Object.entries(condition.lte).forEach(([key, value]) => {\n parts.push(`${key}.lte.${value}`)\n })\n }\n if (condition.neq) {\n Object.entries(condition.neq).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.not.is.null`)\n } else {\n parts.push(`${key}.neq.\"${value}\"`)\n }\n })\n }\n\n // Add pattern matching\n if (condition.like) {\n Object.entries(condition.like).forEach(([key, pattern]) => {\n parts.push(`${key}.like.\"${pattern}\"`)\n })\n }\n if (condition.ilike) {\n Object.entries(condition.ilike).forEach(([key, pattern]) => {\n parts.push(`${key}.ilike.\"${pattern}\"`)\n })\n }\n\n return parts.join(\",\")\n })\n .filter((condition) => condition.length > 0)\n\n // Apply OR conditions if any remain\n\n const finalQuery = orConditions.length > 0 ? queryWithCommon.or(orConditions.join(\",\")) : queryWithCommon\n\n return finalQuery\n }\n\n // Return the Query interface implementation\n return {\n /**\n * Add OR condition to the query\n */\n or: (where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T> => {\n const newConditions = [...config.conditions, { where, is }]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Filter by branded ID with type safety\n */\n whereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n const newConditions = [\n ...config.conditions,\n {\n where: { id: id as unknown } as unknown as WhereConditions<TableRow<T>>,\n },\n ]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Add OR condition with branded ID\n */\n orWhereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n return QueryBuilder(client, config).or({\n id: id as unknown,\n } as unknown as WhereConditions<TableRow<T>>)\n },\n\n /**\n * Apply mapping function to query results\n */\n map: <U>(fn: (item: TableRow<T>) => U): MappedQuery<U> => {\n return createMappedQuery(QueryBuilder(client, config), fn)\n },\n\n /**\n * Apply filter function to query results\n */\n filter: (predicate: (item: TableRow<T>) => boolean): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n filterFn: config.filterFn ? (item: TableRow<T>) => config.filterFn!(item) && predicate(item) : predicate,\n })\n },\n\n /**\n * Limit the number of results\n */\n limit: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n limit: count,\n })\n },\n\n /**\n * Offset the results for pagination\n */\n offset: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n offset: count,\n })\n },\n\n /**\n * Include all records (no soft delete filter)\n */\n includeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"include\") {\n log.warn(`[${config.table}] includeDeleted() called but already including deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"include\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Exclude soft-deleted records (apply deleted IS NULL filter)\n */\n excludeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"exclude\") {\n log.warn(`[${config.table}] excludeDeleted() called but already excluding deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"exclude\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Query only soft-deleted records (apply deleted IS NOT NULL filter)\n */\n onlyDeleted: (): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"only\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Execute query expecting exactly one result\n */\n one: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query.single()\n\n if (error) {\n log.error(`Error getting ${config.table} item: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n\n const result = data as TableRow<T>\n const filteredResult = config.filterFn ? config.filterFn(result) : true\n\n if (!filteredResult) {\n return Ok(Option.none<TableRow<T>>())\n }\n\n return Ok(Option(result))\n } catch (error) {\n log.error(`Error executing single query on ${config.table}: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting zero or more results\n */\n many: (): FPromise<TaskOutcome<List<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query\n\n if (error) {\n log.error(`Error getting ${config.table} items: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n const rawResults = data as TableRow<T>[]\n\n // Apply filter if present\n const results = config.filterFn ? rawResults.filter(config.filterFn) : rawResults\n\n return Ok(List(results))\n } catch (error) {\n log.error(`Error executing multi query on ${config.table}: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting first result from potentially multiple\n */\n first: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n const manyResult = await QueryBuilder(client, config).many()\n const list = manyResult.orThrow()\n if (list.isEmpty) {\n return Ok(Option.none<TableRow<T>>())\n }\n return Ok(Option(list.head))\n })\n },\n\n /**\n * Execute query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found in ${config.table}`))\n },\n\n /**\n * Execute query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<TableRow<T>>> => {\n const result = await QueryBuilder(client, config).many()\n return result.orThrow()\n },\n\n /**\n * Execute query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found in ${config.table}`))\n },\n }\n}\n\n/**\n * Functional MappedQuery implementation\n */\nconst createMappedQuery = <T extends TableNames, U>(\n sourceQuery: Query<T>,\n mapFn: (item: TableRow<T>) => U,\n): MappedQuery<U> => {\n return {\n map: <V>(fn: (item: U) => V): MappedQuery<V> => {\n return createMappedQuery(sourceQuery, (item: TableRow<T>) => fn(mapFn(item)))\n },\n\n filter: (predicate: (item: U) => boolean): MappedQuery<U> => {\n const filteredQuery = sourceQuery.filter((item: TableRow<T>) => predicate(mapFn(item)))\n return createMappedQuery(filteredQuery, mapFn)\n },\n\n one: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.one()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n many: (): FPromise<TaskOutcome<List<U>>> => {\n return wrapAsync(async () => {\n const itemsResult = await sourceQuery.many()\n const items = itemsResult.orThrow()\n return Ok(items.map(mapFn))\n })\n },\n\n first: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.first()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n /**\n * Execute mapped query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found`))\n },\n\n /**\n * Execute mapped query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<U>> => {\n const result = await createMappedQuery(sourceQuery, mapFn).many()\n return result.orThrow()\n },\n\n /**\n * Execute mapped query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found`))\n },\n }\n}\n\n/**\n * Factory function to create new functional QueryBuilder instances\n */\nexport const createQuery = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditions<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n softDeleteConfig?: { mode?: \"include\" | \"exclude\" | \"only\"; appliedByDefault?: boolean },\n): Query<T> => {\n const config: QueryBuilderConfig<T> = {\n table,\n conditions: [{ where, is, wherein }],\n order,\n softDeleteMode: softDeleteConfig?.mode,\n softDeleteAppliedByDefault: softDeleteConfig?.appliedByDefault,\n }\n return QueryBuilder(client, config)\n}\n","import type { EmptyObject, TableNames, TableRow } from \"@/types\"\n\nimport type { Brand, FPromise, List, Option, TaskOutcome } from \"functype\"\n\n// Comparison operators for advanced queries\nexport type ComparisonOperators<V> = {\n gte?: V // Greater than or equal\n gt?: V // Greater than\n lte?: V // Less than or equal\n lt?: V // Less than\n neq?: V // Not equal\n like?: string // LIKE pattern (for string fields)\n ilike?: string // Case-insensitive LIKE\n in?: V[] // IN array\n is?: null | boolean // IS NULL/TRUE/FALSE\n}\n\n// Type-safe WHERE conditions that provide IntelliSense for table columns\n// Supports both direct values and operator objects for advanced queries\nexport type WhereConditions<T extends object> = Partial<{\n [K in keyof T]: T[K] | null | ComparisonOperators<T[K]>\n}> & {\n // Special operators that work across columns with type-safe values\n gte?: Partial<{ [K in keyof T]?: T[K] }>\n gt?: Partial<{ [K in keyof T]?: T[K] }>\n lte?: Partial<{ [K in keyof T]?: T[K] }>\n lt?: Partial<{ [K in keyof T]?: T[K] }>\n neq?: Partial<{ [K in keyof T]?: T[K] }>\n like?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n ilike?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n}\n\n// Enhanced type for IS conditions with field-level type safety\nexport type IsConditions<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Soft delete mode for controlling how deleted records are handled\nexport type SoftDeleteMode = \"include\" | \"exclude\" | \"only\"\n\n// =============================================================================\n// Standard Execution Interfaces for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Base execution interface that all database operations implement\n */\nexport interface ExecutableQuery<T> {\n // TaskOutcome version (for explicit error handling)\n execute(): FPromise<TaskOutcome<T>>\n\n // OrThrow version (for simple error handling)\n executeOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return a single result\n */\nexport interface SingleExecution<T> extends ExecutableQuery<Option<T>> {\n one(): FPromise<TaskOutcome<Option<T>>>\n oneOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return multiple results\n */\nexport interface MultiExecution<T> extends ExecutableQuery<List<T>> {\n many(): FPromise<TaskOutcome<List<T>>>\n manyOrThrow(): Promise<List<T>>\n}\n\n// Branded type support for query conditions\nexport type BrandedWhereParams<T extends object = EmptyObject> = {\n [K in keyof T]?: T[K] | unknown // Simplified to avoid complex conditional types\n}\n\n// Helper type for branded field values\nexport type BrandedFieldValue<T> = T extends Brand<string, infer BaseType> ? T | BaseType : T\n\n// Core Query interface with branded type support\nexport interface Query<T extends TableNames> {\n // Execution methods - explicit about expected results\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<TableRow<T>>\n manyOrThrow(): Promise<List<TableRow<T>>>\n firstOrThrow(): Promise<TableRow<T>>\n\n // Query composition - chainable OR logic with type-safe where conditions\n or(where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T>\n\n // Branded type-aware query methods (simplified)\n whereId<ID extends Brand<string, string>>(id: ID): Query<T>\n orWhereId<ID extends Brand<string, string>>(id: ID): Query<T>\n\n // Functional operations - maintain composability\n map<U>(fn: (item: TableRow<T>) => U): MappedQuery<U>\n filter(predicate: (item: TableRow<T>) => boolean): Query<T>\n\n // Pagination\n limit(count: number): Query<T>\n offset(count: number): Query<T>\n\n // Soft delete filtering\n includeDeleted(): Query<T>\n excludeDeleted(): Query<T>\n onlyDeleted(): Query<T>\n}\n\n// Mapped query for transformed results\nexport interface MappedQuery<U> {\n one(): FPromise<TaskOutcome<Option<U>>>\n many(): FPromise<TaskOutcome<List<U>>>\n first(): FPromise<TaskOutcome<Option<U>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<U>\n manyOrThrow(): Promise<List<U>>\n firstOrThrow(): Promise<U>\n\n // Continue chaining\n map<V>(fn: (item: U) => V): MappedQuery<V>\n filter(predicate: (item: U) => boolean): MappedQuery<U>\n}\n\n// Query condition for internal state management with type-safe where\nexport interface QueryCondition<T extends TableNames> {\n where: WhereConditions<TableRow<T>>\n is?: IsConditions<TableRow<T>>\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>\n // Comparison operators\n gt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n gte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n neq?: Partial<Record<keyof TableRow<T>, unknown>>\n // Pattern matching\n like?: Partial<Record<keyof TableRow<T>, string>>\n ilike?: Partial<Record<keyof TableRow<T>, string>>\n}\n\n// Entity-specific query interfaces for better type safety\nexport interface EntityQuery<T extends TableNames> extends Query<T> {\n // Entity-specific methods can be added here\n normalize(): NormalizedQuery<T>\n}\n\nexport interface NormalizedQuery<T extends TableNames> {\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n}\n\n// Type guards for runtime type checking\nexport const isQuery = <T extends TableNames>(obj: unknown): obj is Query<T> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"or\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\nexport const isMappedQuery = <U>(obj: unknown): obj is MappedQuery<U> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\n// Utility types for query parameters with type safety\nexport type QueryWhereParams<T extends TableNames> = WhereConditions<TableRow<T>>\nexport type QueryIsParams<T extends TableNames> = IsConditions<TableRow<T>>\nexport type QueryWhereinParams<T extends TableNames> = Partial<Record<keyof TableRow<T>, unknown[]>>\nexport type QueryOrderParams<T extends TableNames> = [\n keyof TableRow<T> & string,\n { ascending?: boolean; nullsFirst?: boolean },\n]\n\n// Builder configuration for query construction\nexport interface QueryBuilderConfig<T extends TableNames> {\n table: T\n conditions: QueryCondition<T>[]\n order?: QueryOrderParams<T>\n mapFn?: (item: TableRow<T>) => unknown\n filterFn?: (item: TableRow<T>) => boolean\n limit?: number\n offset?: number\n softDeleteMode?: SoftDeleteMode\n softDeleteAppliedByDefault?: boolean\n}\n","import type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok } from \"functype\"\n\nimport type { Query, WhereConditions } from \"./Query\"\nimport { createQuery } from \"./QueryBuilder\"\n\n// Re-export query types\nexport type {\n ComparisonOperators,\n EntityQuery,\n ExecutableQuery,\n IsConditions,\n MappedQuery,\n MultiExecution,\n Query,\n QueryBuilderConfig,\n QueryCondition,\n QueryIsParams,\n QueryOrderParams,\n QueryWhereinParams,\n QueryWhereParams,\n SingleExecution,\n SoftDeleteMode,\n WhereConditions,\n} from \"./Query\"\n\n// Re-export type guards\nexport { isMappedQuery, isQuery } from \"./Query\"\n\n// Local type for IS conditions\ntype IsConditionsLocal<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\n/**\n * Retrieves a single entity from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @returns A promise resolving to the entity if found\n */\nexport const getEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(baseQuery)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : baseQuery\n\n const { data, error } = await queryWithIs.single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Retrieves multiple entities from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A promise resolving to the entities if found\n */\nexport const getEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }] = [\n \"id\" as keyof TableRow<T> & string,\n { ascending: true },\n ],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const queryOrderBy = queryWithIs.order(order[0], order[1])\n\n const { data, error } = await queryOrderBy\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Adds multiple entities to the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to insert into\n * @param entities - The entities to add\n * @returns A promise resolving to the added entities\n */\nexport const addEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableInsert<T>[],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const { data, error } = await client\n .from(table)\n .insert(entities as never)\n .select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as unknown as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Updates a single entity in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entity data to update\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entity\n */\nexport const updateEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client\n .from(table)\n .update(entities as never)\n .match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select().single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Updates multiple entities in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entities to update\n * @param identity - The column(s) to use as the identity\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entities\n */\nexport const updateEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>[],\n identity: (keyof TableRow<T> & string) | (keyof TableRow<T> & string)[] = \"id\" as keyof TableRow<T> & string,\n where?: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const onConflict = Array.isArray(identity) ? identity.join(\",\") : identity\n\n const baseQuery = client\n .from(table)\n .upsert(entities as never, { onConflict })\n .match(where ?? {})\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Creates a new Query for the specified table with initial conditions.\n * This is the new Query-based API that supports OR chaining and functional operations.\n *\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Initial WHERE conditions to filter by\n * @param is - Initial IS conditions to filter by\n * @param wherein - Initial WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A Query<T> instance that supports chaining and lazy evaluation\n *\n * @example\n * // Simple query\n * const user = await query(client, \"users\", { id: \"123\" }).one()\n *\n * @example\n * // Query with OR logic\n * const users = await query(client, \"users\", { role: \"admin\" })\n * .or({ role: \"moderator\" })\n * .many()\n *\n * @example\n * // Query with functional operations\n * const names = await query(client, \"users\", { active: true })\n * .map(user => user.name)\n * .filter(name => name.startsWith('A'))\n * .many()\n */\nexport const query = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n): Query<T> => {\n return createQuery(client, table, where, is, wherein, order)\n}\n","import { addEntities, updateEntities, updateEntity } from \"@/query\"\nimport type { MultiExecution, Query, SingleExecution, WhereConditions } from \"@/query/Query\"\nimport { createQuery } from \"@/query/QueryBuilder\"\nimport type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\n\nimport type { FPromise, List, TaskOutcome } from \"functype\"\nimport { Option } from \"functype\"\n\n// Field-level type safety for queries\nexport type TypedRecord<T, V> = Partial<Record<keyof T, V>>\n\n// Entity configuration\nexport type EntityConfig = {\n /** Soft delete filtering. true = exclude deleted items, false = include deleted items */\n softDelete: boolean\n /** Partition key for multi-tenant isolation. e.g., { tenant_id: \"123\" } */\n partitionKey?: Record<string, unknown>\n}\n\n// Base parameter types with field-level type safety\nexport type WhereParams<T extends object = EmptyObject> = {\n where?: WhereConditions<T>\n}\n\nexport type IsParams<T extends object = EmptyObject> = {\n is?: TypedRecord<T, null | boolean>\n}\n\nexport type WhereinParams<T extends object = EmptyObject> = {\n wherein?: TypedRecord<T, unknown[]>\n}\n\nexport type OrderParams<T extends object = EmptyObject> = {\n order?: [keyof T & string, { ascending?: boolean; nullsFirst?: boolean }]\n}\n\nexport type IdParam = {\n id: string\n}\n\n// Composable parameter types with field-level type safety\nexport type GetItemParams<T extends object = EmptyObject> = IdParam & WhereParams<T> & IsParams<T>\n\nexport type GetItemsParams<T extends object = EmptyObject> = WhereParams<T> &\n IsParams<T> &\n WhereinParams<T> &\n OrderParams<T>\n\nexport type AddItemsParams<T extends TableNames> = {\n items: TableInsert<T>[]\n}\n\nexport type UpdateItemParams<T extends TableNames, Row extends object = EmptyObject> = IdParam & {\n item: TableUpdate<T>\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\nexport type UpdateItemsParams<T extends TableNames, Row extends object = EmptyObject> = {\n items: TableUpdate<T>[]\n identity?: (keyof Row & string) | (keyof Row & string)[]\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\n// =============================================================================\n// Mutation Query Wrappers for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Wrapper type for multi-result mutation operations that implements standard execution interface\n */\nexport type MutationMultiExecution<T> = FPromise<TaskOutcome<List<T>>> & MultiExecution<T>\n\n/**\n * Wrapper type for single-result mutation operations that implements standard execution interface\n */\nexport type MutationSingleExecution<T> = FPromise<TaskOutcome<T>> & SingleExecution<T>\n\n/**\n * Creates a multi-result mutation query that implements the standard execution interface\n */\nexport function MultiMutationQuery<T>(promise: FPromise<TaskOutcome<List<T>>>): MutationMultiExecution<T> {\n const result = Object.assign(promise, {\n // Standard MultiExecution interface\n many: () => promise,\n manyOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise,\n executeOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n })\n return result as MutationMultiExecution<T>\n}\n\n/**\n * Creates a single-result mutation query that implements the standard execution interface\n */\nexport function SingleMutationQuery<T>(promise: FPromise<TaskOutcome<T>>): MutationSingleExecution<T> {\n const result = Object.assign(promise, {\n // Standard SingleExecution interface\n one: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n oneOrThrow: async (): Promise<T> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n executeOrThrow: async (): Promise<Option<T>> => {\n const taskResult = await promise\n const value = taskResult.orThrow()\n return Option(value)\n },\n })\n return result as MutationSingleExecution<T>\n}\n\n/**\n * Base interface for Entity instances\n */\nexport type IEntity<T extends TableNames> = {\n getItem(params: GetItemParams<TableRow<T>>): Query<T>\n getItems(params?: GetItemsParams<TableRow<T>>): Query<T>\n addItems(params: AddItemsParams<T>): MutationMultiExecution<TableRow<T>>\n updateItem(params: UpdateItemParams<T, TableRow<T>>): MutationSingleExecution<TableRow<T>>\n updateItems(params: UpdateItemsParams<T, TableRow<T>>): MutationMultiExecution<TableRow<T>>\n}\n\n/**\n * Creates an entity interface with methods for interacting with the given table.\n * @param client The Supabase client instance to use for queries.\n * @param name The name of the table to interact with.\n * @param config Configuration for entity behavior (required).\n * @returns An object with methods for interacting with the table.\n */\nexport const Entity = <T extends TableNames>(client: SupabaseClientType, name: T, config: EntityConfig): IEntity<T> => {\n type ROW = TableRow<T>\n\n const softDeleteMode = config.softDelete ? \"exclude\" : \"include\"\n\n /**\n * Retrieve a single item from the given table by ID.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemParams<ROW>} params Parameters.\n * @param {string} params.id The ID of the item to retrieve.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItem({ id, where, is }: GetItemParams<ROW>): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where, id } : { ...where, id }\n return createQuery(\n client,\n name,\n whereWithPartition as unknown as WhereConditions<TableRow<T>>,\n is,\n undefined,\n undefined,\n { mode: softDeleteMode, appliedByDefault: true },\n )\n }\n\n /**\n * Get a list of items from the given table filtered by the given conditions.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemsParams<ROW>} params Optional parameters.\n * @param {TypedRecord<ROW, unknown>} [params.where] Conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @param {[keyof ROW & string, { ascending?: boolean; nullsFirst?: boolean }]} [params.order] Optional ordering parameters.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItems({ where, is, wherein, order }: GetItemsParams<ROW> = {}): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where } : where\n return createQuery(client, name, whereWithPartition as WhereConditions<TableRow<T>>, is, wherein, order, {\n mode: softDeleteMode,\n appliedByDefault: true,\n })\n }\n\n /**\n * Adds multiple items to the given table.\n * @param {AddItemsParams<T>} params Parameters.\n * @param {TableInsert<T>[]} params.items The items to add.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function addItems({ items }: AddItemsParams<T>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(addEntities(client, name, items))\n }\n\n /**\n * Update a single item in the given table.\n * @param {UpdateItemParams<T, ROW>} params Parameters.\n * @param {string} params.id The ID of the item to update.\n * @param {Partial<TableUpdate<T>>} params.item The item to update.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationSingleExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItem({ id, item, where, is, wherein }: UpdateItemParams<T, ROW>): MutationSingleExecution<ROW> {\n return SingleMutationQuery(\n updateEntity(client, name, item, { ...where, id } as unknown as WhereConditions<TableRow<T>>, is, wherein),\n )\n }\n\n /**\n * Update multiple items in the given table.\n * @param {UpdateItemsParams<T, ROW>} params Parameters.\n * @param {TableUpdate<T>[]} params.items The items to update.\n * @param {keyof ROW & string | (keyof ROW & string)[]} [params.identity=\"id\"] The column(s) to use as the identity.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItems({\n items,\n identity = \"id\" as keyof ROW & string,\n where,\n is,\n wherein,\n }: UpdateItemsParams<T, ROW>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(updateEntities(client, name, items, identity, where, is, wherein))\n }\n\n return {\n getItem,\n getItems,\n addItems,\n updateItem,\n updateItems,\n }\n}\n\n/**\n * Type for an entity instance for a specific table\n * @deprecated Use IEntity<T> instead\n */\nexport type EntityType<T extends TableNames> = IEntity<T>\n"],"names":["wrapAsync","query","List","Err","Ok","Option"],"mappings":";;;AAaO,MAAM,sBAAsB,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,OAAsC;AAGhD,QAAI,iBAAiB,OAAO;AAC1B,YAAM,MAAM,OAAO;AACnB,WAAK,OAAO,MAAM;AAClB,WAAK,QAAQ,MAAM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;AACzD,WAAO,mBAAmB,eAAe,QAAQ,MAAM,OAAO,UAAU,OAAO,IAAI,OAAO,CAAC;AAAA,EAC7F;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.mjs CHANGED
@@ -41,9 +41,9 @@ const toError = (error) => {
41
41
  return new SupabaseError(error);
42
42
  };
43
43
  const log = {
44
- error: (msg) => console.error(`[supabase-typed-query] ${msg}`),
45
- warn: (msg) => console.warn(`[supabase-typed-query] ${msg}`),
46
- info: (msg) => console.info(`[supabase-typed-query] ${msg}`)
44
+ error: (msg) => process.env.NODE_ENV !== "test" && console.error(`[supabase-typed-query] ${msg}`),
45
+ warn: (msg) => process.env.NODE_ENV !== "test" && console.warn(`[supabase-typed-query] ${msg}`),
46
+ info: (msg) => process.env.NODE_ENV !== "test" && console.info(`[supabase-typed-query] ${msg}`)
47
47
  };
48
48
  const TABLES_WITHOUT_DELETED = /* @__PURE__ */ new Set([]);
49
49
  const wrapAsync$1 = (fn) => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/utils/errors.ts","../src/query/QueryBuilder.ts","../src/query/Query.ts","../src/query/index.ts","../src/entity/Entity.ts"],"sourcesContent":["/**\n * Supabase/Postgrest error structure\n */\nexport type SupabaseErrorObject = {\n message: string\n code?: string\n details?: string\n hint?: string\n}\n\n/**\n * Custom Error class that preserves Supabase error details\n */\nexport class SupabaseError extends Error {\n readonly code?: string\n readonly details?: string\n readonly hint?: string\n\n constructor(error: SupabaseErrorObject | unknown) {\n // Check for Error instances FIRST before checking for Supabase error objects\n // because Error instances also have a message property\n if (error instanceof Error) {\n super(error.message)\n this.name = error.name\n this.stack = error.stack\n } else if (isSupabaseError(error)) {\n super(error.message)\n this.name = \"SupabaseError\"\n this.code = error.code\n this.details = error.details\n this.hint = error.hint\n } else {\n super(String(error))\n this.name = \"SupabaseError\"\n }\n }\n\n /**\n * Override toString to include all error details\n */\n override toString(): string {\n const parts = [this.message]\n if (this.code) parts.push(`[Code: ${this.code}]`)\n if (this.details) parts.push(`Details: ${this.details}`)\n if (this.hint) parts.push(`Hint: ${this.hint}`)\n return parts.join(\" | \")\n }\n}\n\n/**\n * Type guard for Supabase error objects\n */\nfunction isSupabaseError(error: unknown): error is SupabaseErrorObject {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as SupabaseErrorObject).message === \"string\"\n )\n}\n\n/**\n * Convert any error to a proper Error instance\n */\nexport const toError = (error: unknown): Error => {\n if (error instanceof Error) {\n return error\n }\n return new SupabaseError(error)\n}\n","import type { SupabaseClientType, TableNames, TableRow } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { Brand, FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok, Option } from \"functype\"\n\nimport type { IsConditions, MappedQuery, Query, QueryBuilderConfig, QueryCondition, WhereConditions } from \"./Query\"\n\n// Simple console logging for open source version\nconst log = {\n error: (msg: string) => console.error(`[supabase-typed-query] ${msg}`),\n warn: (msg: string) => console.warn(`[supabase-typed-query] ${msg}`),\n info: (msg: string) => console.info(`[supabase-typed-query] ${msg}`),\n}\n\n// Tables that don't have a deleted field (like version tracking tables)\n// Tables that don't have a deleted field - consumers can override this\nconst TABLES_WITHOUT_DELETED = new Set<string>([])\n\n/**\n * Functional QueryBuilder implementation using closures instead of classes\n */\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n // FPromise in newer functype versions is just a promise with additional methods\n // We can use the FPromise constructor if available, or cast it\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\nexport const QueryBuilder = <T extends TableNames>(\n client: SupabaseClientType,\n config: QueryBuilderConfig<T>,\n): Query<T> => {\n /**\n * Build the Supabase query from accumulated conditions\n */\n const buildSupabaseQuery = () => {\n const { table, conditions, order, limit, offset } = config\n\n // Start with base query (just the table reference)\n const baseQuery = client.from(table)\n\n // Handle multiple conditions with OR logic\n const queryWithConditions =\n conditions.length === 1 ? applyCondition(baseQuery, conditions[0]) : applyOrConditions(baseQuery, conditions)\n\n // Apply ordering if specified\n const queryWithOrder = order ? queryWithConditions.order(order[0], order[1]) : queryWithConditions\n\n // Apply pagination\n const finalQuery = (() => {\n if (limit && offset !== undefined) {\n // Use range for offset + limit\n return queryWithOrder.range(offset, offset + limit - 1)\n } else if (limit) {\n // Just limit\n return queryWithOrder.limit(limit)\n } else if (offset !== undefined) {\n // Just offset (need to use a large upper bound)\n return queryWithOrder.range(offset, Number.MAX_SAFE_INTEGER)\n }\n return queryWithOrder\n })()\n\n return finalQuery\n }\n\n /**\n * Apply a single condition to the query\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyCondition = (query: any, condition: QueryCondition<T>): any => {\n const { where, is, wherein, gt, gte, lt, lte, neq, like, ilike } = condition\n\n // Process WHERE conditions, extracting operators from the where object\n const processedWhere: Record<string, unknown> = {}\n const extractedOperators: {\n gt?: Record<string, unknown>\n gte?: Record<string, unknown>\n lt?: Record<string, unknown>\n lte?: Record<string, unknown>\n neq?: Record<string, unknown>\n like?: Record<string, string>\n ilike?: Record<string, string>\n } = {}\n\n if (where) {\n // Extract top-level operators from where object\n const {\n gt: whereGt,\n gte: whereGte,\n lt: whereLt,\n lte: whereLte,\n neq: whereNeq,\n like: whereLike,\n ilike: whereIlike,\n ...rest\n } = where as Record<string, unknown>\n\n // Store extracted operators\n if (whereGt) extractedOperators.gt = whereGt as Record<string, unknown>\n if (whereGte) extractedOperators.gte = whereGte as Record<string, unknown>\n if (whereLt) extractedOperators.lt = whereLt as Record<string, unknown>\n if (whereLte) extractedOperators.lte = whereLte as Record<string, unknown>\n if (whereNeq) extractedOperators.neq = whereNeq as Record<string, unknown>\n if (whereLike) extractedOperators.like = whereLike as Record<string, string>\n if (whereIlike) extractedOperators.ilike = whereIlike as Record<string, string>\n\n // Process remaining fields\n for (const [key, value] of Object.entries(rest)) {\n if (value && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Date)) {\n // Check if it's an operator object\n const ops = value as Record<string, unknown>\n if (ops.gte !== undefined) {\n extractedOperators.gte = {\n ...extractedOperators.gte,\n [key]: ops.gte,\n }\n }\n if (ops.gt !== undefined) {\n extractedOperators.gt = { ...extractedOperators.gt, [key]: ops.gt }\n }\n if (ops.lte !== undefined) {\n extractedOperators.lte = {\n ...extractedOperators.lte,\n [key]: ops.lte,\n }\n }\n if (ops.lt !== undefined) {\n extractedOperators.lt = { ...extractedOperators.lt, [key]: ops.lt }\n }\n if (ops.neq !== undefined) {\n extractedOperators.neq = {\n ...extractedOperators.neq,\n [key]: ops.neq,\n }\n }\n if (ops.like !== undefined) {\n extractedOperators.like = {\n ...extractedOperators.like,\n [key]: ops.like as string,\n }\n }\n if (ops.ilike !== undefined) {\n extractedOperators.ilike = {\n ...extractedOperators.ilike,\n [key]: ops.ilike as string,\n }\n }\n if (ops.in !== undefined) {\n // Handle IN operator\n if (!wherein) {\n const cond = condition as unknown as Record<string, unknown>\n cond.wherein = {}\n }\n const whereinObj = condition.wherein as Record<string, unknown>\n whereinObj[key] = ops.in\n }\n if (ops.is !== undefined) {\n // Handle IS operator\n if (!is) {\n const cond = condition as unknown as Record<string, unknown>\n cond.is = {}\n }\n const isObj = condition.is as Record<string, unknown>\n isObj[key] = ops.is\n }\n // If no operators found, treat as regular value\n if (!ops.gte && !ops.gt && !ops.lte && !ops.lt && !ops.neq && !ops.like && !ops.ilike && !ops.in && !ops.is) {\n processedWhere[key] = value\n }\n } else {\n // Regular value\n processedWhere[key] = value\n }\n }\n }\n\n // Merge extracted operators with explicitly passed operators\n const mergedGt = { ...gt, ...extractedOperators.gt }\n const mergedGte = { ...gte, ...extractedOperators.gte }\n const mergedLt = { ...lt, ...extractedOperators.lt }\n const mergedLte = { ...lte, ...extractedOperators.lte }\n const mergedNeq = { ...neq, ...extractedOperators.neq }\n const mergedLike = { ...like, ...extractedOperators.like }\n const mergedIlike = { ...ilike, ...extractedOperators.ilike }\n\n // Apply WHERE conditions\n const baseQuery = query.select(\"*\").match(processedWhere)\n\n // Apply soft delete filter based on softDeleteMode\n const queryWithSoftDelete = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return baseQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return baseQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return baseQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return baseQuery\n })()\n\n // Apply WHERE IN conditions\n const queryWithWhereIn = wherein\n ? List(Object.entries(wherein)).foldLeft(queryWithSoftDelete)((q, [column, values]) =>\n q.in(column, values as never),\n )\n : queryWithSoftDelete\n\n // Apply IS conditions\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithWhereIn)((q, [column, value]) =>\n q.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithWhereIn\n\n // Apply comparison operators using merged values\n const queryWithGt =\n Object.keys(mergedGt).length > 0\n ? Object.entries(mergedGt).reduce((q, [key, value]) => q.gt(key, value), queryWithIs)\n : queryWithIs\n\n const queryWithGte =\n Object.keys(mergedGte).length > 0\n ? Object.entries(mergedGte).reduce((q, [key, value]) => q.gte(key, value), queryWithGt)\n : queryWithGt\n\n const queryWithLt =\n Object.keys(mergedLt).length > 0\n ? Object.entries(mergedLt).reduce((q, [key, value]) => q.lt(key, value), queryWithGte)\n : queryWithGte\n\n const queryWithLte =\n Object.keys(mergedLte).length > 0\n ? Object.entries(mergedLte).reduce((q, [key, value]) => q.lte(key, value), queryWithLt)\n : queryWithLt\n\n const queryWithNeq =\n Object.keys(mergedNeq).length > 0\n ? Object.entries(mergedNeq).reduce((q, [key, value]) => q.neq(key, value), queryWithLte)\n : queryWithLte\n\n // Apply pattern matching using merged values\n const queryWithLike =\n Object.keys(mergedLike).length > 0\n ? Object.entries(mergedLike).reduce((q, [key, pattern]) => q.like(key, pattern as string), queryWithNeq)\n : queryWithNeq\n\n const queryWithIlike =\n Object.keys(mergedIlike).length > 0\n ? Object.entries(mergedIlike).reduce((q, [key, pattern]) => q.ilike(key, pattern as string), queryWithLike)\n : queryWithLike\n\n return queryWithIlike\n }\n\n /**\n * Apply multiple conditions with OR logic\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyOrConditions = (query: any, conditions: QueryCondition<T>[]): any => {\n // Start with select\n const selectQuery = query.select(\"*\")\n\n // Apply soft delete filter based on softDeleteMode\n const baseQuery = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return selectQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return selectQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return selectQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return selectQuery\n })()\n\n // Separate common conditions from varying conditions\n const commonConditions = new Map<string, unknown>()\n const varyingConditions: QueryCondition<T>[] = []\n\n // Find conditions that are common across all OR branches\n if (conditions.length > 0) {\n const firstCondition = conditions[0]\n\n // Check each key-value pair in the first condition\n Object.entries(firstCondition.where).forEach(([key, value]) => {\n // If this key-value pair exists in ALL conditions, it's common\n const isCommonCondition = conditions.every(\n (condition) => (condition.where as Record<string, unknown>)[key] === value,\n )\n\n if (isCommonCondition) {\n commonConditions.set(key, value)\n }\n })\n\n // Create new conditions with common parts removed\n varyingConditions.push(\n ...conditions.map((condition) => {\n const newWhere = { ...condition.where } as Record<string, unknown>\n commonConditions.forEach((_, key) => {\n delete newWhere[key]\n })\n return {\n where: newWhere as WhereConditions<TableRow<T>>,\n is: condition.is,\n wherein: condition.wherein,\n }\n }),\n )\n }\n\n // Apply common conditions first\n const queryWithCommon = Array.from(commonConditions.entries()).reduce((query, [key, value]) => {\n if (value === null) {\n return query.is(key, null)\n } else {\n return query.eq(key, value)\n }\n }, baseQuery)\n\n // If no varying conditions remain, we're done\n if (varyingConditions.every((condition) => Object.keys(condition.where).length === 0)) {\n return queryWithCommon\n }\n\n // Build OR conditions from the varying parts only\n const orConditions = varyingConditions\n .map((condition) => {\n const parts: string[] = []\n\n // Add WHERE conditions (only the varying ones)\n Object.entries(condition.where).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.eq.\"${value}\"`)\n }\n })\n\n // Add IS conditions\n if (condition.is) {\n Object.entries(condition.is).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.is.${value}`)\n }\n })\n }\n\n // Add WHERE IN conditions\n if (condition.wherein) {\n Object.entries(condition.wherein).forEach(([key, values]) => {\n if (values && Array.isArray(values) && values.length > 0) {\n const valueList = values.map((v: unknown) => `\"${v}\"`).join(\",\")\n parts.push(`${key}.in.(${valueList})`)\n }\n })\n }\n\n // Add comparison operators\n if (condition.gt) {\n Object.entries(condition.gt).forEach(([key, value]) => {\n parts.push(`${key}.gt.${value}`)\n })\n }\n if (condition.gte) {\n Object.entries(condition.gte).forEach(([key, value]) => {\n parts.push(`${key}.gte.${value}`)\n })\n }\n if (condition.lt) {\n Object.entries(condition.lt).forEach(([key, value]) => {\n parts.push(`${key}.lt.${value}`)\n })\n }\n if (condition.lte) {\n Object.entries(condition.lte).forEach(([key, value]) => {\n parts.push(`${key}.lte.${value}`)\n })\n }\n if (condition.neq) {\n Object.entries(condition.neq).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.not.is.null`)\n } else {\n parts.push(`${key}.neq.\"${value}\"`)\n }\n })\n }\n\n // Add pattern matching\n if (condition.like) {\n Object.entries(condition.like).forEach(([key, pattern]) => {\n parts.push(`${key}.like.\"${pattern}\"`)\n })\n }\n if (condition.ilike) {\n Object.entries(condition.ilike).forEach(([key, pattern]) => {\n parts.push(`${key}.ilike.\"${pattern}\"`)\n })\n }\n\n return parts.join(\",\")\n })\n .filter((condition) => condition.length > 0)\n\n // Apply OR conditions if any remain\n\n const finalQuery = orConditions.length > 0 ? queryWithCommon.or(orConditions.join(\",\")) : queryWithCommon\n\n return finalQuery\n }\n\n // Return the Query interface implementation\n return {\n /**\n * Add OR condition to the query\n */\n or: (where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T> => {\n const newConditions = [...config.conditions, { where, is }]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Filter by branded ID with type safety\n */\n whereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n const newConditions = [\n ...config.conditions,\n {\n where: { id: id as unknown } as unknown as WhereConditions<TableRow<T>>,\n },\n ]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Add OR condition with branded ID\n */\n orWhereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n return QueryBuilder(client, config).or({\n id: id as unknown,\n } as unknown as WhereConditions<TableRow<T>>)\n },\n\n /**\n * Apply mapping function to query results\n */\n map: <U>(fn: (item: TableRow<T>) => U): MappedQuery<U> => {\n return createMappedQuery(QueryBuilder(client, config), fn)\n },\n\n /**\n * Apply filter function to query results\n */\n filter: (predicate: (item: TableRow<T>) => boolean): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n filterFn: config.filterFn ? (item: TableRow<T>) => config.filterFn!(item) && predicate(item) : predicate,\n })\n },\n\n /**\n * Limit the number of results\n */\n limit: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n limit: count,\n })\n },\n\n /**\n * Offset the results for pagination\n */\n offset: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n offset: count,\n })\n },\n\n /**\n * Include all records (no soft delete filter)\n */\n includeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"include\") {\n log.warn(`[${config.table}] includeDeleted() called but already including deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"include\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Exclude soft-deleted records (apply deleted IS NULL filter)\n */\n excludeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"exclude\") {\n log.warn(`[${config.table}] excludeDeleted() called but already excluding deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"exclude\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Query only soft-deleted records (apply deleted IS NOT NULL filter)\n */\n onlyDeleted: (): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"only\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Execute query expecting exactly one result\n */\n one: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query.single()\n\n if (error) {\n log.error(`Error getting ${config.table} item: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n\n const result = data as TableRow<T>\n const filteredResult = config.filterFn ? config.filterFn(result) : true\n\n if (!filteredResult) {\n return Ok(Option.none<TableRow<T>>())\n }\n\n return Ok(Option(result))\n } catch (error) {\n log.error(`Error executing single query on ${config.table}: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting zero or more results\n */\n many: (): FPromise<TaskOutcome<List<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query\n\n if (error) {\n log.error(`Error getting ${config.table} items: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n const rawResults = data as TableRow<T>[]\n\n // Apply filter if present\n const results = config.filterFn ? rawResults.filter(config.filterFn) : rawResults\n\n return Ok(List(results))\n } catch (error) {\n log.error(`Error executing multi query on ${config.table}: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting first result from potentially multiple\n */\n first: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n const manyResult = await QueryBuilder(client, config).many()\n const list = manyResult.orThrow()\n if (list.isEmpty) {\n return Ok(Option.none<TableRow<T>>())\n }\n return Ok(Option(list.head))\n })\n },\n\n /**\n * Execute query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found in ${config.table}`))\n },\n\n /**\n * Execute query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<TableRow<T>>> => {\n const result = await QueryBuilder(client, config).many()\n return result.orThrow()\n },\n\n /**\n * Execute query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found in ${config.table}`))\n },\n }\n}\n\n/**\n * Functional MappedQuery implementation\n */\nconst createMappedQuery = <T extends TableNames, U>(\n sourceQuery: Query<T>,\n mapFn: (item: TableRow<T>) => U,\n): MappedQuery<U> => {\n return {\n map: <V>(fn: (item: U) => V): MappedQuery<V> => {\n return createMappedQuery(sourceQuery, (item: TableRow<T>) => fn(mapFn(item)))\n },\n\n filter: (predicate: (item: U) => boolean): MappedQuery<U> => {\n const filteredQuery = sourceQuery.filter((item: TableRow<T>) => predicate(mapFn(item)))\n return createMappedQuery(filteredQuery, mapFn)\n },\n\n one: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.one()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n many: (): FPromise<TaskOutcome<List<U>>> => {\n return wrapAsync(async () => {\n const itemsResult = await sourceQuery.many()\n const items = itemsResult.orThrow()\n return Ok(items.map(mapFn))\n })\n },\n\n first: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.first()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n /**\n * Execute mapped query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found`))\n },\n\n /**\n * Execute mapped query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<U>> => {\n const result = await createMappedQuery(sourceQuery, mapFn).many()\n return result.orThrow()\n },\n\n /**\n * Execute mapped query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found`))\n },\n }\n}\n\n/**\n * Factory function to create new functional QueryBuilder instances\n */\nexport const createQuery = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditions<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n softDeleteConfig?: { mode?: \"include\" | \"exclude\" | \"only\"; appliedByDefault?: boolean },\n): Query<T> => {\n const config: QueryBuilderConfig<T> = {\n table,\n conditions: [{ where, is, wherein }],\n order,\n softDeleteMode: softDeleteConfig?.mode,\n softDeleteAppliedByDefault: softDeleteConfig?.appliedByDefault,\n }\n return QueryBuilder(client, config)\n}\n","import type { EmptyObject, TableNames, TableRow } from \"@/types\"\n\nimport type { Brand, FPromise, List, Option, TaskOutcome } from \"functype\"\n\n// Comparison operators for advanced queries\nexport type ComparisonOperators<V> = {\n gte?: V // Greater than or equal\n gt?: V // Greater than\n lte?: V // Less than or equal\n lt?: V // Less than\n neq?: V // Not equal\n like?: string // LIKE pattern (for string fields)\n ilike?: string // Case-insensitive LIKE\n in?: V[] // IN array\n is?: null | boolean // IS NULL/TRUE/FALSE\n}\n\n// Type-safe WHERE conditions that provide IntelliSense for table columns\n// Supports both direct values and operator objects for advanced queries\nexport type WhereConditions<T extends object> = Partial<{\n [K in keyof T]: T[K] | null | ComparisonOperators<T[K]>\n}> & {\n // Special operators that work across columns with type-safe values\n gte?: Partial<{ [K in keyof T]?: T[K] }>\n gt?: Partial<{ [K in keyof T]?: T[K] }>\n lte?: Partial<{ [K in keyof T]?: T[K] }>\n lt?: Partial<{ [K in keyof T]?: T[K] }>\n neq?: Partial<{ [K in keyof T]?: T[K] }>\n like?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n ilike?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n}\n\n// Enhanced type for IS conditions with field-level type safety\nexport type IsConditions<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Soft delete mode for controlling how deleted records are handled\nexport type SoftDeleteMode = \"include\" | \"exclude\" | \"only\"\n\n// =============================================================================\n// Standard Execution Interfaces for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Base execution interface that all database operations implement\n */\nexport interface ExecutableQuery<T> {\n // TaskOutcome version (for explicit error handling)\n execute(): FPromise<TaskOutcome<T>>\n\n // OrThrow version (for simple error handling)\n executeOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return a single result\n */\nexport interface SingleExecution<T> extends ExecutableQuery<Option<T>> {\n one(): FPromise<TaskOutcome<Option<T>>>\n oneOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return multiple results\n */\nexport interface MultiExecution<T> extends ExecutableQuery<List<T>> {\n many(): FPromise<TaskOutcome<List<T>>>\n manyOrThrow(): Promise<List<T>>\n}\n\n// Branded type support for query conditions\nexport type BrandedWhereParams<T extends object = EmptyObject> = {\n [K in keyof T]?: T[K] | unknown // Simplified to avoid complex conditional types\n}\n\n// Helper type for branded field values\nexport type BrandedFieldValue<T> = T extends Brand<string, infer BaseType> ? T | BaseType : T\n\n// Core Query interface with branded type support\nexport interface Query<T extends TableNames> {\n // Execution methods - explicit about expected results\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<TableRow<T>>\n manyOrThrow(): Promise<List<TableRow<T>>>\n firstOrThrow(): Promise<TableRow<T>>\n\n // Query composition - chainable OR logic with type-safe where conditions\n or(where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T>\n\n // Branded type-aware query methods (simplified)\n whereId<ID extends Brand<string, string>>(id: ID): Query<T>\n orWhereId<ID extends Brand<string, string>>(id: ID): Query<T>\n\n // Functional operations - maintain composability\n map<U>(fn: (item: TableRow<T>) => U): MappedQuery<U>\n filter(predicate: (item: TableRow<T>) => boolean): Query<T>\n\n // Pagination\n limit(count: number): Query<T>\n offset(count: number): Query<T>\n\n // Soft delete filtering\n includeDeleted(): Query<T>\n excludeDeleted(): Query<T>\n onlyDeleted(): Query<T>\n}\n\n// Mapped query for transformed results\nexport interface MappedQuery<U> {\n one(): FPromise<TaskOutcome<Option<U>>>\n many(): FPromise<TaskOutcome<List<U>>>\n first(): FPromise<TaskOutcome<Option<U>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<U>\n manyOrThrow(): Promise<List<U>>\n firstOrThrow(): Promise<U>\n\n // Continue chaining\n map<V>(fn: (item: U) => V): MappedQuery<V>\n filter(predicate: (item: U) => boolean): MappedQuery<U>\n}\n\n// Query condition for internal state management with type-safe where\nexport interface QueryCondition<T extends TableNames> {\n where: WhereConditions<TableRow<T>>\n is?: IsConditions<TableRow<T>>\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>\n // Comparison operators\n gt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n gte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n neq?: Partial<Record<keyof TableRow<T>, unknown>>\n // Pattern matching\n like?: Partial<Record<keyof TableRow<T>, string>>\n ilike?: Partial<Record<keyof TableRow<T>, string>>\n}\n\n// Entity-specific query interfaces for better type safety\nexport interface EntityQuery<T extends TableNames> extends Query<T> {\n // Entity-specific methods can be added here\n normalize(): NormalizedQuery<T>\n}\n\nexport interface NormalizedQuery<T extends TableNames> {\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n}\n\n// Type guards for runtime type checking\nexport const isQuery = <T extends TableNames>(obj: unknown): obj is Query<T> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"or\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\nexport const isMappedQuery = <U>(obj: unknown): obj is MappedQuery<U> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\n// Utility types for query parameters with type safety\nexport type QueryWhereParams<T extends TableNames> = WhereConditions<TableRow<T>>\nexport type QueryIsParams<T extends TableNames> = IsConditions<TableRow<T>>\nexport type QueryWhereinParams<T extends TableNames> = Partial<Record<keyof TableRow<T>, unknown[]>>\nexport type QueryOrderParams<T extends TableNames> = [\n keyof TableRow<T> & string,\n { ascending?: boolean; nullsFirst?: boolean },\n]\n\n// Builder configuration for query construction\nexport interface QueryBuilderConfig<T extends TableNames> {\n table: T\n conditions: QueryCondition<T>[]\n order?: QueryOrderParams<T>\n mapFn?: (item: TableRow<T>) => unknown\n filterFn?: (item: TableRow<T>) => boolean\n limit?: number\n offset?: number\n softDeleteMode?: SoftDeleteMode\n softDeleteAppliedByDefault?: boolean\n}\n","import type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok } from \"functype\"\n\nimport type { Query, WhereConditions } from \"./Query\"\nimport { createQuery } from \"./QueryBuilder\"\n\n// Re-export query types\nexport type {\n ComparisonOperators,\n EntityQuery,\n ExecutableQuery,\n IsConditions,\n MappedQuery,\n MultiExecution,\n Query,\n QueryBuilderConfig,\n QueryCondition,\n QueryIsParams,\n QueryOrderParams,\n QueryWhereinParams,\n QueryWhereParams,\n SingleExecution,\n SoftDeleteMode,\n WhereConditions,\n} from \"./Query\"\n\n// Re-export type guards\nexport { isMappedQuery, isQuery } from \"./Query\"\n\n// Local type for IS conditions\ntype IsConditionsLocal<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\n/**\n * Retrieves a single entity from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @returns A promise resolving to the entity if found\n */\nexport const getEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(baseQuery)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : baseQuery\n\n const { data, error } = await queryWithIs.single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Retrieves multiple entities from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A promise resolving to the entities if found\n */\nexport const getEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }] = [\n \"id\" as keyof TableRow<T> & string,\n { ascending: true },\n ],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const queryOrderBy = queryWithIs.order(order[0], order[1])\n\n const { data, error } = await queryOrderBy\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Adds multiple entities to the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to insert into\n * @param entities - The entities to add\n * @returns A promise resolving to the added entities\n */\nexport const addEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableInsert<T>[],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const { data, error } = await client\n .from(table)\n .insert(entities as never)\n .select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as unknown as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Updates a single entity in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entity data to update\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entity\n */\nexport const updateEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client\n .from(table)\n .update(entities as never)\n .match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select().single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Updates multiple entities in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entities to update\n * @param identity - The column(s) to use as the identity\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entities\n */\nexport const updateEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>[],\n identity: (keyof TableRow<T> & string) | (keyof TableRow<T> & string)[] = \"id\" as keyof TableRow<T> & string,\n where?: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const onConflict = Array.isArray(identity) ? identity.join(\",\") : identity\n\n const baseQuery = client\n .from(table)\n .upsert(entities as never, { onConflict })\n .match(where ?? {})\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Creates a new Query for the specified table with initial conditions.\n * This is the new Query-based API that supports OR chaining and functional operations.\n *\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Initial WHERE conditions to filter by\n * @param is - Initial IS conditions to filter by\n * @param wherein - Initial WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A Query<T> instance that supports chaining and lazy evaluation\n *\n * @example\n * // Simple query\n * const user = await query(client, \"users\", { id: \"123\" }).one()\n *\n * @example\n * // Query with OR logic\n * const users = await query(client, \"users\", { role: \"admin\" })\n * .or({ role: \"moderator\" })\n * .many()\n *\n * @example\n * // Query with functional operations\n * const names = await query(client, \"users\", { active: true })\n * .map(user => user.name)\n * .filter(name => name.startsWith('A'))\n * .many()\n */\nexport const query = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n): Query<T> => {\n return createQuery(client, table, where, is, wherein, order)\n}\n","import { addEntities, updateEntities, updateEntity } from \"@/query\"\nimport type { MultiExecution, Query, SingleExecution, WhereConditions } from \"@/query/Query\"\nimport { createQuery } from \"@/query/QueryBuilder\"\nimport type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\n\nimport type { FPromise, List, TaskOutcome } from \"functype\"\nimport { Option } from \"functype\"\n\n// Field-level type safety for queries\nexport type TypedRecord<T, V> = Partial<Record<keyof T, V>>\n\n// Entity configuration\nexport type EntityConfig = {\n /** Soft delete filtering. true = exclude deleted items, false = include deleted items */\n softDelete: boolean\n /** Partition key for multi-tenant isolation. e.g., { tenant_id: \"123\" } */\n partitionKey?: Record<string, unknown>\n}\n\n// Base parameter types with field-level type safety\nexport type WhereParams<T extends object = EmptyObject> = {\n where?: WhereConditions<T>\n}\n\nexport type IsParams<T extends object = EmptyObject> = {\n is?: TypedRecord<T, null | boolean>\n}\n\nexport type WhereinParams<T extends object = EmptyObject> = {\n wherein?: TypedRecord<T, unknown[]>\n}\n\nexport type OrderParams<T extends object = EmptyObject> = {\n order?: [keyof T & string, { ascending?: boolean; nullsFirst?: boolean }]\n}\n\nexport type IdParam = {\n id: string\n}\n\n// Composable parameter types with field-level type safety\nexport type GetItemParams<T extends object = EmptyObject> = IdParam & WhereParams<T> & IsParams<T>\n\nexport type GetItemsParams<T extends object = EmptyObject> = WhereParams<T> &\n IsParams<T> &\n WhereinParams<T> &\n OrderParams<T>\n\nexport type AddItemsParams<T extends TableNames> = {\n items: TableInsert<T>[]\n}\n\nexport type UpdateItemParams<T extends TableNames, Row extends object = EmptyObject> = IdParam & {\n item: TableUpdate<T>\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\nexport type UpdateItemsParams<T extends TableNames, Row extends object = EmptyObject> = {\n items: TableUpdate<T>[]\n identity?: (keyof Row & string) | (keyof Row & string)[]\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\n// =============================================================================\n// Mutation Query Wrappers for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Wrapper type for multi-result mutation operations that implements standard execution interface\n */\nexport type MutationMultiExecution<T> = FPromise<TaskOutcome<List<T>>> & MultiExecution<T>\n\n/**\n * Wrapper type for single-result mutation operations that implements standard execution interface\n */\nexport type MutationSingleExecution<T> = FPromise<TaskOutcome<T>> & SingleExecution<T>\n\n/**\n * Creates a multi-result mutation query that implements the standard execution interface\n */\nexport function MultiMutationQuery<T>(promise: FPromise<TaskOutcome<List<T>>>): MutationMultiExecution<T> {\n const result = Object.assign(promise, {\n // Standard MultiExecution interface\n many: () => promise,\n manyOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise,\n executeOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n })\n return result as MutationMultiExecution<T>\n}\n\n/**\n * Creates a single-result mutation query that implements the standard execution interface\n */\nexport function SingleMutationQuery<T>(promise: FPromise<TaskOutcome<T>>): MutationSingleExecution<T> {\n const result = Object.assign(promise, {\n // Standard SingleExecution interface\n one: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n oneOrThrow: async (): Promise<T> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n executeOrThrow: async (): Promise<Option<T>> => {\n const taskResult = await promise\n const value = taskResult.orThrow()\n return Option(value)\n },\n })\n return result as MutationSingleExecution<T>\n}\n\n/**\n * Base interface for Entity instances\n */\nexport type IEntity<T extends TableNames> = {\n getItem(params: GetItemParams<TableRow<T>>): Query<T>\n getItems(params?: GetItemsParams<TableRow<T>>): Query<T>\n addItems(params: AddItemsParams<T>): MutationMultiExecution<TableRow<T>>\n updateItem(params: UpdateItemParams<T, TableRow<T>>): MutationSingleExecution<TableRow<T>>\n updateItems(params: UpdateItemsParams<T, TableRow<T>>): MutationMultiExecution<TableRow<T>>\n}\n\n/**\n * Creates an entity interface with methods for interacting with the given table.\n * @param client The Supabase client instance to use for queries.\n * @param name The name of the table to interact with.\n * @param config Configuration for entity behavior (required).\n * @returns An object with methods for interacting with the table.\n */\nexport const Entity = <T extends TableNames>(client: SupabaseClientType, name: T, config: EntityConfig): IEntity<T> => {\n type ROW = TableRow<T>\n\n const softDeleteMode = config.softDelete ? \"exclude\" : \"include\"\n\n /**\n * Retrieve a single item from the given table by ID.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemParams<ROW>} params Parameters.\n * @param {string} params.id The ID of the item to retrieve.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItem({ id, where, is }: GetItemParams<ROW>): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where, id } : { ...where, id }\n return createQuery(\n client,\n name,\n whereWithPartition as unknown as WhereConditions<TableRow<T>>,\n is,\n undefined,\n undefined,\n { mode: softDeleteMode, appliedByDefault: true },\n )\n }\n\n /**\n * Get a list of items from the given table filtered by the given conditions.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemsParams<ROW>} params Optional parameters.\n * @param {TypedRecord<ROW, unknown>} [params.where] Conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @param {[keyof ROW & string, { ascending?: boolean; nullsFirst?: boolean }]} [params.order] Optional ordering parameters.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItems({ where, is, wherein, order }: GetItemsParams<ROW> = {}): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where } : where\n return createQuery(client, name, whereWithPartition as WhereConditions<TableRow<T>>, is, wherein, order, {\n mode: softDeleteMode,\n appliedByDefault: true,\n })\n }\n\n /**\n * Adds multiple items to the given table.\n * @param {AddItemsParams<T>} params Parameters.\n * @param {TableInsert<T>[]} params.items The items to add.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function addItems({ items }: AddItemsParams<T>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(addEntities(client, name, items))\n }\n\n /**\n * Update a single item in the given table.\n * @param {UpdateItemParams<T, ROW>} params Parameters.\n * @param {string} params.id The ID of the item to update.\n * @param {Partial<TableUpdate<T>>} params.item The item to update.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationSingleExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItem({ id, item, where, is, wherein }: UpdateItemParams<T, ROW>): MutationSingleExecution<ROW> {\n return SingleMutationQuery(\n updateEntity(client, name, item, { ...where, id } as unknown as WhereConditions<TableRow<T>>, is, wherein),\n )\n }\n\n /**\n * Update multiple items in the given table.\n * @param {UpdateItemsParams<T, ROW>} params Parameters.\n * @param {TableUpdate<T>[]} params.items The items to update.\n * @param {keyof ROW & string | (keyof ROW & string)[]} [params.identity=\"id\"] The column(s) to use as the identity.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItems({\n items,\n identity = \"id\" as keyof ROW & string,\n where,\n is,\n wherein,\n }: UpdateItemsParams<T, ROW>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(updateEntities(client, name, items, identity, where, is, wherein))\n }\n\n return {\n getItem,\n getItems,\n addItems,\n updateItem,\n updateItems,\n }\n}\n\n/**\n * Type for an entity instance for a specific table\n * @deprecated Use IEntity<T> instead\n */\nexport type EntityType<T extends TableNames> = IEntity<T>\n"],"names":["wrapAsync","query"],"mappings":";;AAaO,MAAM,sBAAsB,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,OAAsC;AAGhD,QAAI,iBAAiB,OAAO;AAC1B,YAAM,MAAM,OAAO;AACnB,WAAK,OAAO,MAAM;AAClB,WAAK,QAAQ,MAAM;AAAA,IACrB,WAAW,gBAAgB,KAAK,GAAG;AACjC,YAAM,MAAM,OAAO;AACnB,WAAK,OAAO;AACZ,WAAK,OAAO,MAAM;AAClB,WAAK,UAAU,MAAM;AACrB,WAAK,OAAO,MAAM;AAAA,IACpB,OAAO;AACL,YAAM,OAAO,KAAK,CAAC;AACnB,WAAK,OAAO;AAAA,IACd;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKS,WAAmB;AAC1B,UAAM,QAAQ,CAAC,KAAK,OAAO;AAC3B,QAAI,KAAK,KAAM,OAAM,KAAK,UAAU,KAAK,IAAI,GAAG;AAChD,QAAI,KAAK,QAAS,OAAM,KAAK,YAAY,KAAK,OAAO,EAAE;AACvD,QAAI,KAAK,KAAM,OAAM,KAAK,SAAS,KAAK,IAAI,EAAE;AAC9C,WAAO,MAAM,KAAK,KAAK;AAAA,EACzB;AACF;AAKA,SAAS,gBAAgB,OAA8C;AACrE,SACE,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,OAAQ,MAA8B,YAAY;AAEtD;AAKO,MAAM,UAAU,CAAC,UAA0B;AAChD,MAAI,iBAAiB,OAAO;AAC1B,WAAO;AAAA,EACT;AACA,SAAO,IAAI,cAAc,KAAK;AAChC;AC5DA,MAAM,MAAM;AAAA,EACV,OAAO,CAAC,QAAgB,QAAQ,MAAM,0BAA0B,GAAG,EAAE;AAAA,EACrE,MAAM,CAAC,QAAg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AC7F;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/utils/errors.ts","../src/query/QueryBuilder.ts","../src/query/Query.ts","../src/query/index.ts","../src/entity/Entity.ts"],"sourcesContent":["/**\n * Supabase/Postgrest error structure\n */\nexport type SupabaseErrorObject = {\n message: string\n code?: string\n details?: string\n hint?: string\n}\n\n/**\n * Custom Error class that preserves Supabase error details\n */\nexport class SupabaseError extends Error {\n readonly code?: string\n readonly details?: string\n readonly hint?: string\n\n constructor(error: SupabaseErrorObject | unknown) {\n // Check for Error instances FIRST before checking for Supabase error objects\n // because Error instances also have a message property\n if (error instanceof Error) {\n super(error.message)\n this.name = error.name\n this.stack = error.stack\n } else if (isSupabaseError(error)) {\n super(error.message)\n this.name = \"SupabaseError\"\n this.code = error.code\n this.details = error.details\n this.hint = error.hint\n } else {\n super(String(error))\n this.name = \"SupabaseError\"\n }\n }\n\n /**\n * Override toString to include all error details\n */\n override toString(): string {\n const parts = [this.message]\n if (this.code) parts.push(`[Code: ${this.code}]`)\n if (this.details) parts.push(`Details: ${this.details}`)\n if (this.hint) parts.push(`Hint: ${this.hint}`)\n return parts.join(\" | \")\n }\n}\n\n/**\n * Type guard for Supabase error objects\n */\nfunction isSupabaseError(error: unknown): error is SupabaseErrorObject {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"message\" in error &&\n typeof (error as SupabaseErrorObject).message === \"string\"\n )\n}\n\n/**\n * Convert any error to a proper Error instance\n */\nexport const toError = (error: unknown): Error => {\n if (error instanceof Error) {\n return error\n }\n return new SupabaseError(error)\n}\n","import type { SupabaseClientType, TableNames, TableRow } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { Brand, FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok, Option } from \"functype\"\n\nimport type { IsConditions, MappedQuery, Query, QueryBuilderConfig, QueryCondition, WhereConditions } from \"./Query\"\n\n// Simple console logging for open source version\n// Suppress logs during tests to avoid stderr noise in test output\nconst log = {\n error: (msg: string) => process.env.NODE_ENV !== \"test\" && console.error(`[supabase-typed-query] ${msg}`),\n warn: (msg: string) => process.env.NODE_ENV !== \"test\" && console.warn(`[supabase-typed-query] ${msg}`),\n info: (msg: string) => process.env.NODE_ENV !== \"test\" && console.info(`[supabase-typed-query] ${msg}`),\n}\n\n// Tables that don't have a deleted field (like version tracking tables)\n// Tables that don't have a deleted field - consumers can override this\nconst TABLES_WITHOUT_DELETED = new Set<string>([])\n\n/**\n * Functional QueryBuilder implementation using closures instead of classes\n */\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n // FPromise in newer functype versions is just a promise with additional methods\n // We can use the FPromise constructor if available, or cast it\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\nexport const QueryBuilder = <T extends TableNames>(\n client: SupabaseClientType,\n config: QueryBuilderConfig<T>,\n): Query<T> => {\n /**\n * Build the Supabase query from accumulated conditions\n */\n const buildSupabaseQuery = () => {\n const { table, conditions, order, limit, offset } = config\n\n // Start with base query (just the table reference)\n const baseQuery = client.from(table)\n\n // Handle multiple conditions with OR logic\n const queryWithConditions =\n conditions.length === 1 ? applyCondition(baseQuery, conditions[0]) : applyOrConditions(baseQuery, conditions)\n\n // Apply ordering if specified\n const queryWithOrder = order ? queryWithConditions.order(order[0], order[1]) : queryWithConditions\n\n // Apply pagination\n const finalQuery = (() => {\n if (limit && offset !== undefined) {\n // Use range for offset + limit\n return queryWithOrder.range(offset, offset + limit - 1)\n } else if (limit) {\n // Just limit\n return queryWithOrder.limit(limit)\n } else if (offset !== undefined) {\n // Just offset (need to use a large upper bound)\n return queryWithOrder.range(offset, Number.MAX_SAFE_INTEGER)\n }\n return queryWithOrder\n })()\n\n return finalQuery\n }\n\n /**\n * Apply a single condition to the query\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyCondition = (query: any, condition: QueryCondition<T>): any => {\n const { where, is, wherein, gt, gte, lt, lte, neq, like, ilike } = condition\n\n // Process WHERE conditions, extracting operators from the where object\n const processedWhere: Record<string, unknown> = {}\n const extractedOperators: {\n gt?: Record<string, unknown>\n gte?: Record<string, unknown>\n lt?: Record<string, unknown>\n lte?: Record<string, unknown>\n neq?: Record<string, unknown>\n like?: Record<string, string>\n ilike?: Record<string, string>\n } = {}\n\n if (where) {\n // Extract top-level operators from where object\n const {\n gt: whereGt,\n gte: whereGte,\n lt: whereLt,\n lte: whereLte,\n neq: whereNeq,\n like: whereLike,\n ilike: whereIlike,\n ...rest\n } = where as Record<string, unknown>\n\n // Store extracted operators\n if (whereGt) extractedOperators.gt = whereGt as Record<string, unknown>\n if (whereGte) extractedOperators.gte = whereGte as Record<string, unknown>\n if (whereLt) extractedOperators.lt = whereLt as Record<string, unknown>\n if (whereLte) extractedOperators.lte = whereLte as Record<string, unknown>\n if (whereNeq) extractedOperators.neq = whereNeq as Record<string, unknown>\n if (whereLike) extractedOperators.like = whereLike as Record<string, string>\n if (whereIlike) extractedOperators.ilike = whereIlike as Record<string, string>\n\n // Process remaining fields\n for (const [key, value] of Object.entries(rest)) {\n if (value && typeof value === \"object\" && !Array.isArray(value) && !(value instanceof Date)) {\n // Check if it's an operator object\n const ops = value as Record<string, unknown>\n if (ops.gte !== undefined) {\n extractedOperators.gte = {\n ...extractedOperators.gte,\n [key]: ops.gte,\n }\n }\n if (ops.gt !== undefined) {\n extractedOperators.gt = { ...extractedOperators.gt, [key]: ops.gt }\n }\n if (ops.lte !== undefined) {\n extractedOperators.lte = {\n ...extractedOperators.lte,\n [key]: ops.lte,\n }\n }\n if (ops.lt !== undefined) {\n extractedOperators.lt = { ...extractedOperators.lt, [key]: ops.lt }\n }\n if (ops.neq !== undefined) {\n extractedOperators.neq = {\n ...extractedOperators.neq,\n [key]: ops.neq,\n }\n }\n if (ops.like !== undefined) {\n extractedOperators.like = {\n ...extractedOperators.like,\n [key]: ops.like as string,\n }\n }\n if (ops.ilike !== undefined) {\n extractedOperators.ilike = {\n ...extractedOperators.ilike,\n [key]: ops.ilike as string,\n }\n }\n if (ops.in !== undefined) {\n // Handle IN operator\n if (!wherein) {\n const cond = condition as unknown as Record<string, unknown>\n cond.wherein = {}\n }\n const whereinObj = condition.wherein as Record<string, unknown>\n whereinObj[key] = ops.in\n }\n if (ops.is !== undefined) {\n // Handle IS operator\n if (!is) {\n const cond = condition as unknown as Record<string, unknown>\n cond.is = {}\n }\n const isObj = condition.is as Record<string, unknown>\n isObj[key] = ops.is\n }\n // If no operators found, treat as regular value\n if (!ops.gte && !ops.gt && !ops.lte && !ops.lt && !ops.neq && !ops.like && !ops.ilike && !ops.in && !ops.is) {\n processedWhere[key] = value\n }\n } else {\n // Regular value\n processedWhere[key] = value\n }\n }\n }\n\n // Merge extracted operators with explicitly passed operators\n const mergedGt = { ...gt, ...extractedOperators.gt }\n const mergedGte = { ...gte, ...extractedOperators.gte }\n const mergedLt = { ...lt, ...extractedOperators.lt }\n const mergedLte = { ...lte, ...extractedOperators.lte }\n const mergedNeq = { ...neq, ...extractedOperators.neq }\n const mergedLike = { ...like, ...extractedOperators.like }\n const mergedIlike = { ...ilike, ...extractedOperators.ilike }\n\n // Apply WHERE conditions\n const baseQuery = query.select(\"*\").match(processedWhere)\n\n // Apply soft delete filter based on softDeleteMode\n const queryWithSoftDelete = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return baseQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return baseQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return baseQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return baseQuery\n })()\n\n // Apply WHERE IN conditions\n const queryWithWhereIn = wherein\n ? List(Object.entries(wherein)).foldLeft(queryWithSoftDelete)((q, [column, values]) =>\n q.in(column, values as never),\n )\n : queryWithSoftDelete\n\n // Apply IS conditions\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithWhereIn)((q, [column, value]) =>\n q.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithWhereIn\n\n // Apply comparison operators using merged values\n const queryWithGt =\n Object.keys(mergedGt).length > 0\n ? Object.entries(mergedGt).reduce((q, [key, value]) => q.gt(key, value), queryWithIs)\n : queryWithIs\n\n const queryWithGte =\n Object.keys(mergedGte).length > 0\n ? Object.entries(mergedGte).reduce((q, [key, value]) => q.gte(key, value), queryWithGt)\n : queryWithGt\n\n const queryWithLt =\n Object.keys(mergedLt).length > 0\n ? Object.entries(mergedLt).reduce((q, [key, value]) => q.lt(key, value), queryWithGte)\n : queryWithGte\n\n const queryWithLte =\n Object.keys(mergedLte).length > 0\n ? Object.entries(mergedLte).reduce((q, [key, value]) => q.lte(key, value), queryWithLt)\n : queryWithLt\n\n const queryWithNeq =\n Object.keys(mergedNeq).length > 0\n ? Object.entries(mergedNeq).reduce((q, [key, value]) => q.neq(key, value), queryWithLte)\n : queryWithLte\n\n // Apply pattern matching using merged values\n const queryWithLike =\n Object.keys(mergedLike).length > 0\n ? Object.entries(mergedLike).reduce((q, [key, pattern]) => q.like(key, pattern as string), queryWithNeq)\n : queryWithNeq\n\n const queryWithIlike =\n Object.keys(mergedIlike).length > 0\n ? Object.entries(mergedIlike).reduce((q, [key, pattern]) => q.ilike(key, pattern as string), queryWithLike)\n : queryWithLike\n\n return queryWithIlike\n }\n\n /**\n * Apply multiple conditions with OR logic\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const applyOrConditions = (query: any, conditions: QueryCondition<T>[]): any => {\n // Start with select\n const selectQuery = query.select(\"*\")\n\n // Apply soft delete filter based on softDeleteMode\n const baseQuery = (() => {\n if (TABLES_WITHOUT_DELETED.has(config.table)) {\n return selectQuery\n }\n if (config.softDeleteMode === \"exclude\") {\n return selectQuery.is(\"deleted\", null)\n }\n if (config.softDeleteMode === \"only\") {\n return selectQuery.not(\"deleted\", \"is\", null)\n }\n // Default: \"include\" - no filter\n return selectQuery\n })()\n\n // Separate common conditions from varying conditions\n const commonConditions = new Map<string, unknown>()\n const varyingConditions: QueryCondition<T>[] = []\n\n // Find conditions that are common across all OR branches\n if (conditions.length > 0) {\n const firstCondition = conditions[0]\n\n // Check each key-value pair in the first condition\n Object.entries(firstCondition.where).forEach(([key, value]) => {\n // If this key-value pair exists in ALL conditions, it's common\n const isCommonCondition = conditions.every(\n (condition) => (condition.where as Record<string, unknown>)[key] === value,\n )\n\n if (isCommonCondition) {\n commonConditions.set(key, value)\n }\n })\n\n // Create new conditions with common parts removed\n varyingConditions.push(\n ...conditions.map((condition) => {\n const newWhere = { ...condition.where } as Record<string, unknown>\n commonConditions.forEach((_, key) => {\n delete newWhere[key]\n })\n return {\n where: newWhere as WhereConditions<TableRow<T>>,\n is: condition.is,\n wherein: condition.wherein,\n }\n }),\n )\n }\n\n // Apply common conditions first\n const queryWithCommon = Array.from(commonConditions.entries()).reduce((query, [key, value]) => {\n if (value === null) {\n return query.is(key, null)\n } else {\n return query.eq(key, value)\n }\n }, baseQuery)\n\n // If no varying conditions remain, we're done\n if (varyingConditions.every((condition) => Object.keys(condition.where).length === 0)) {\n return queryWithCommon\n }\n\n // Build OR conditions from the varying parts only\n const orConditions = varyingConditions\n .map((condition) => {\n const parts: string[] = []\n\n // Add WHERE conditions (only the varying ones)\n Object.entries(condition.where).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.eq.\"${value}\"`)\n }\n })\n\n // Add IS conditions\n if (condition.is) {\n Object.entries(condition.is).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.is.null`)\n } else {\n parts.push(`${key}.is.${value}`)\n }\n })\n }\n\n // Add WHERE IN conditions\n if (condition.wherein) {\n Object.entries(condition.wherein).forEach(([key, values]) => {\n if (values && Array.isArray(values) && values.length > 0) {\n const valueList = values.map((v: unknown) => `\"${v}\"`).join(\",\")\n parts.push(`${key}.in.(${valueList})`)\n }\n })\n }\n\n // Add comparison operators\n if (condition.gt) {\n Object.entries(condition.gt).forEach(([key, value]) => {\n parts.push(`${key}.gt.${value}`)\n })\n }\n if (condition.gte) {\n Object.entries(condition.gte).forEach(([key, value]) => {\n parts.push(`${key}.gte.${value}`)\n })\n }\n if (condition.lt) {\n Object.entries(condition.lt).forEach(([key, value]) => {\n parts.push(`${key}.lt.${value}`)\n })\n }\n if (condition.lte) {\n Object.entries(condition.lte).forEach(([key, value]) => {\n parts.push(`${key}.lte.${value}`)\n })\n }\n if (condition.neq) {\n Object.entries(condition.neq).forEach(([key, value]) => {\n if (value === null) {\n parts.push(`${key}.not.is.null`)\n } else {\n parts.push(`${key}.neq.\"${value}\"`)\n }\n })\n }\n\n // Add pattern matching\n if (condition.like) {\n Object.entries(condition.like).forEach(([key, pattern]) => {\n parts.push(`${key}.like.\"${pattern}\"`)\n })\n }\n if (condition.ilike) {\n Object.entries(condition.ilike).forEach(([key, pattern]) => {\n parts.push(`${key}.ilike.\"${pattern}\"`)\n })\n }\n\n return parts.join(\",\")\n })\n .filter((condition) => condition.length > 0)\n\n // Apply OR conditions if any remain\n\n const finalQuery = orConditions.length > 0 ? queryWithCommon.or(orConditions.join(\",\")) : queryWithCommon\n\n return finalQuery\n }\n\n // Return the Query interface implementation\n return {\n /**\n * Add OR condition to the query\n */\n or: (where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T> => {\n const newConditions = [...config.conditions, { where, is }]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Filter by branded ID with type safety\n */\n whereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n const newConditions = [\n ...config.conditions,\n {\n where: { id: id as unknown } as unknown as WhereConditions<TableRow<T>>,\n },\n ]\n return QueryBuilder(client, {\n ...config,\n conditions: newConditions,\n })\n },\n\n /**\n * Add OR condition with branded ID\n */\n orWhereId: <ID extends Brand<string, string>>(id: ID): Query<T> => {\n return QueryBuilder(client, config).or({\n id: id as unknown,\n } as unknown as WhereConditions<TableRow<T>>)\n },\n\n /**\n * Apply mapping function to query results\n */\n map: <U>(fn: (item: TableRow<T>) => U): MappedQuery<U> => {\n return createMappedQuery(QueryBuilder(client, config), fn)\n },\n\n /**\n * Apply filter function to query results\n */\n filter: (predicate: (item: TableRow<T>) => boolean): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n filterFn: config.filterFn ? (item: TableRow<T>) => config.filterFn!(item) && predicate(item) : predicate,\n })\n },\n\n /**\n * Limit the number of results\n */\n limit: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n limit: count,\n })\n },\n\n /**\n * Offset the results for pagination\n */\n offset: (count: number): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n offset: count,\n })\n },\n\n /**\n * Include all records (no soft delete filter)\n */\n includeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"include\") {\n log.warn(`[${config.table}] includeDeleted() called but already including deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"include\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Exclude soft-deleted records (apply deleted IS NULL filter)\n */\n excludeDeleted: (): Query<T> => {\n if (config.softDeleteAppliedByDefault && config.softDeleteMode === \"exclude\") {\n log.warn(`[${config.table}] excludeDeleted() called but already excluding deleted by default`)\n }\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"exclude\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Query only soft-deleted records (apply deleted IS NOT NULL filter)\n */\n onlyDeleted: (): Query<T> => {\n return QueryBuilder(client, {\n ...config,\n softDeleteMode: \"only\",\n softDeleteAppliedByDefault: false,\n })\n },\n\n /**\n * Execute query expecting exactly one result\n */\n one: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query.single()\n\n if (error) {\n log.error(`Error getting ${config.table} item: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n\n const result = data as TableRow<T>\n const filteredResult = config.filterFn ? config.filterFn(result) : true\n\n if (!filteredResult) {\n return Ok(Option.none<TableRow<T>>())\n }\n\n return Ok(Option(result))\n } catch (error) {\n log.error(`Error executing single query on ${config.table}: ${toError(error).toString()}`)\n return Err<Option<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting zero or more results\n */\n many: (): FPromise<TaskOutcome<List<TableRow<T>>>> => {\n return wrapAsync(async () => {\n try {\n const query = buildSupabaseQuery()\n const { data, error } = await query\n\n if (error) {\n log.error(`Error getting ${config.table} items: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n const rawResults = data as TableRow<T>[]\n\n // Apply filter if present\n const results = config.filterFn ? rawResults.filter(config.filterFn) : rawResults\n\n return Ok(List(results))\n } catch (error) {\n log.error(`Error executing multi query on ${config.table}: ${toError(error).toString()}`)\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n },\n\n /**\n * Execute query expecting first result from potentially multiple\n */\n first: (): FPromise<TaskOutcome<Option<TableRow<T>>>> => {\n return wrapAsync(async () => {\n const manyResult = await QueryBuilder(client, config).many()\n const list = manyResult.orThrow()\n if (list.isEmpty) {\n return Ok(Option.none<TableRow<T>>())\n }\n return Ok(Option(list.head))\n })\n },\n\n /**\n * Execute query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found in ${config.table}`))\n },\n\n /**\n * Execute query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<TableRow<T>>> => {\n const result = await QueryBuilder(client, config).many()\n return result.orThrow()\n },\n\n /**\n * Execute query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<TableRow<T>> => {\n const result = await QueryBuilder(client, config).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found in ${config.table}`))\n },\n }\n}\n\n/**\n * Functional MappedQuery implementation\n */\nconst createMappedQuery = <T extends TableNames, U>(\n sourceQuery: Query<T>,\n mapFn: (item: TableRow<T>) => U,\n): MappedQuery<U> => {\n return {\n map: <V>(fn: (item: U) => V): MappedQuery<V> => {\n return createMappedQuery(sourceQuery, (item: TableRow<T>) => fn(mapFn(item)))\n },\n\n filter: (predicate: (item: U) => boolean): MappedQuery<U> => {\n const filteredQuery = sourceQuery.filter((item: TableRow<T>) => predicate(mapFn(item)))\n return createMappedQuery(filteredQuery, mapFn)\n },\n\n one: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.one()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n many: (): FPromise<TaskOutcome<List<U>>> => {\n return wrapAsync(async () => {\n const itemsResult = await sourceQuery.many()\n const items = itemsResult.orThrow()\n return Ok(items.map(mapFn))\n })\n },\n\n first: (): FPromise<TaskOutcome<Option<U>>> => {\n return wrapAsync(async () => {\n const maybeItemResult = await sourceQuery.first()\n const maybeItem = maybeItemResult.orThrow()\n return maybeItem.fold(\n () => Ok(Option.none<U>()),\n (item) => Ok(Option(mapFn(item))),\n )\n })\n },\n\n /**\n * Execute mapped query expecting exactly one result, throw if error or not found\n */\n oneOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).one()\n const option = result.orThrow()\n return option.orThrow(new Error(`No record found`))\n },\n\n /**\n * Execute mapped query expecting zero or more results, throw if error\n */\n manyOrThrow: async (): Promise<List<U>> => {\n const result = await createMappedQuery(sourceQuery, mapFn).many()\n return result.orThrow()\n },\n\n /**\n * Execute mapped query expecting first result, throw if error or empty\n */\n firstOrThrow: async (): Promise<U> => {\n const result = await createMappedQuery(sourceQuery, mapFn).first()\n const option = result.orThrow()\n return option.orThrow(new Error(`No records found`))\n },\n }\n}\n\n/**\n * Factory function to create new functional QueryBuilder instances\n */\nexport const createQuery = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditions<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n softDeleteConfig?: { mode?: \"include\" | \"exclude\" | \"only\"; appliedByDefault?: boolean },\n): Query<T> => {\n const config: QueryBuilderConfig<T> = {\n table,\n conditions: [{ where, is, wherein }],\n order,\n softDeleteMode: softDeleteConfig?.mode,\n softDeleteAppliedByDefault: softDeleteConfig?.appliedByDefault,\n }\n return QueryBuilder(client, config)\n}\n","import type { EmptyObject, TableNames, TableRow } from \"@/types\"\n\nimport type { Brand, FPromise, List, Option, TaskOutcome } from \"functype\"\n\n// Comparison operators for advanced queries\nexport type ComparisonOperators<V> = {\n gte?: V // Greater than or equal\n gt?: V // Greater than\n lte?: V // Less than or equal\n lt?: V // Less than\n neq?: V // Not equal\n like?: string // LIKE pattern (for string fields)\n ilike?: string // Case-insensitive LIKE\n in?: V[] // IN array\n is?: null | boolean // IS NULL/TRUE/FALSE\n}\n\n// Type-safe WHERE conditions that provide IntelliSense for table columns\n// Supports both direct values and operator objects for advanced queries\nexport type WhereConditions<T extends object> = Partial<{\n [K in keyof T]: T[K] | null | ComparisonOperators<T[K]>\n}> & {\n // Special operators that work across columns with type-safe values\n gte?: Partial<{ [K in keyof T]?: T[K] }>\n gt?: Partial<{ [K in keyof T]?: T[K] }>\n lte?: Partial<{ [K in keyof T]?: T[K] }>\n lt?: Partial<{ [K in keyof T]?: T[K] }>\n neq?: Partial<{ [K in keyof T]?: T[K] }>\n like?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n ilike?: Partial<{ [K in keyof T]?: Extract<T[K], string> }>\n}\n\n// Enhanced type for IS conditions with field-level type safety\nexport type IsConditions<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Soft delete mode for controlling how deleted records are handled\nexport type SoftDeleteMode = \"include\" | \"exclude\" | \"only\"\n\n// =============================================================================\n// Standard Execution Interfaces for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Base execution interface that all database operations implement\n */\nexport interface ExecutableQuery<T> {\n // TaskOutcome version (for explicit error handling)\n execute(): FPromise<TaskOutcome<T>>\n\n // OrThrow version (for simple error handling)\n executeOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return a single result\n */\nexport interface SingleExecution<T> extends ExecutableQuery<Option<T>> {\n one(): FPromise<TaskOutcome<Option<T>>>\n oneOrThrow(): Promise<T>\n}\n\n/**\n * Standard interface for operations that return multiple results\n */\nexport interface MultiExecution<T> extends ExecutableQuery<List<T>> {\n many(): FPromise<TaskOutcome<List<T>>>\n manyOrThrow(): Promise<List<T>>\n}\n\n// Branded type support for query conditions\nexport type BrandedWhereParams<T extends object = EmptyObject> = {\n [K in keyof T]?: T[K] | unknown // Simplified to avoid complex conditional types\n}\n\n// Helper type for branded field values\nexport type BrandedFieldValue<T> = T extends Brand<string, infer BaseType> ? T | BaseType : T\n\n// Core Query interface with branded type support\nexport interface Query<T extends TableNames> {\n // Execution methods - explicit about expected results\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<TableRow<T>>\n manyOrThrow(): Promise<List<TableRow<T>>>\n firstOrThrow(): Promise<TableRow<T>>\n\n // Query composition - chainable OR logic with type-safe where conditions\n or(where: WhereConditions<TableRow<T>>, is?: IsConditions<TableRow<T>>): Query<T>\n\n // Branded type-aware query methods (simplified)\n whereId<ID extends Brand<string, string>>(id: ID): Query<T>\n orWhereId<ID extends Brand<string, string>>(id: ID): Query<T>\n\n // Functional operations - maintain composability\n map<U>(fn: (item: TableRow<T>) => U): MappedQuery<U>\n filter(predicate: (item: TableRow<T>) => boolean): Query<T>\n\n // Pagination\n limit(count: number): Query<T>\n offset(count: number): Query<T>\n\n // Soft delete filtering\n includeDeleted(): Query<T>\n excludeDeleted(): Query<T>\n onlyDeleted(): Query<T>\n}\n\n// Mapped query for transformed results\nexport interface MappedQuery<U> {\n one(): FPromise<TaskOutcome<Option<U>>>\n many(): FPromise<TaskOutcome<List<U>>>\n first(): FPromise<TaskOutcome<Option<U>>>\n\n // OrThrow methods - throw errors instead of returning TaskOutcome (v0.8.0+)\n oneOrThrow(): Promise<U>\n manyOrThrow(): Promise<List<U>>\n firstOrThrow(): Promise<U>\n\n // Continue chaining\n map<V>(fn: (item: U) => V): MappedQuery<V>\n filter(predicate: (item: U) => boolean): MappedQuery<U>\n}\n\n// Query condition for internal state management with type-safe where\nexport interface QueryCondition<T extends TableNames> {\n where: WhereConditions<TableRow<T>>\n is?: IsConditions<TableRow<T>>\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>\n // Comparison operators\n gt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n gte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lt?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n lte?: Partial<Record<keyof TableRow<T>, number | string | Date>>\n neq?: Partial<Record<keyof TableRow<T>, unknown>>\n // Pattern matching\n like?: Partial<Record<keyof TableRow<T>, string>>\n ilike?: Partial<Record<keyof TableRow<T>, string>>\n}\n\n// Entity-specific query interfaces for better type safety\nexport interface EntityQuery<T extends TableNames> extends Query<T> {\n // Entity-specific methods can be added here\n normalize(): NormalizedQuery<T>\n}\n\nexport interface NormalizedQuery<T extends TableNames> {\n one(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n many(): FPromise<TaskOutcome<List<TableRow<T>>>>\n first(): FPromise<TaskOutcome<Option<TableRow<T>>>>\n}\n\n// Type guards for runtime type checking\nexport const isQuery = <T extends TableNames>(obj: unknown): obj is Query<T> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"or\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\nexport const isMappedQuery = <U>(obj: unknown): obj is MappedQuery<U> => {\n return (\n typeof obj === \"object\" &&\n obj !== null &&\n \"one\" in obj &&\n \"many\" in obj &&\n \"first\" in obj &&\n \"map\" in obj &&\n \"filter\" in obj\n )\n}\n\n// Utility types for query parameters with type safety\nexport type QueryWhereParams<T extends TableNames> = WhereConditions<TableRow<T>>\nexport type QueryIsParams<T extends TableNames> = IsConditions<TableRow<T>>\nexport type QueryWhereinParams<T extends TableNames> = Partial<Record<keyof TableRow<T>, unknown[]>>\nexport type QueryOrderParams<T extends TableNames> = [\n keyof TableRow<T> & string,\n { ascending?: boolean; nullsFirst?: boolean },\n]\n\n// Builder configuration for query construction\nexport interface QueryBuilderConfig<T extends TableNames> {\n table: T\n conditions: QueryCondition<T>[]\n order?: QueryOrderParams<T>\n mapFn?: (item: TableRow<T>) => unknown\n filterFn?: (item: TableRow<T>) => boolean\n limit?: number\n offset?: number\n softDeleteMode?: SoftDeleteMode\n softDeleteAppliedByDefault?: boolean\n}\n","import type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\nimport { toError } from \"@/utils/errors\"\n\nimport type { FPromise, TaskOutcome } from \"functype\"\nimport { Err, List, Ok } from \"functype\"\n\nimport type { Query, WhereConditions } from \"./Query\"\nimport { createQuery } from \"./QueryBuilder\"\n\n// Re-export query types\nexport type {\n ComparisonOperators,\n EntityQuery,\n ExecutableQuery,\n IsConditions,\n MappedQuery,\n MultiExecution,\n Query,\n QueryBuilderConfig,\n QueryCondition,\n QueryIsParams,\n QueryOrderParams,\n QueryWhereinParams,\n QueryWhereParams,\n SingleExecution,\n SoftDeleteMode,\n WhereConditions,\n} from \"./Query\"\n\n// Re-export type guards\nexport { isMappedQuery, isQuery } from \"./Query\"\n\n// Local type for IS conditions\ntype IsConditionsLocal<T extends object = EmptyObject> = Partial<Record<keyof T, null | boolean>>\n\n// Helper to wrap async operations with error handling\nconst wrapAsync = <T>(fn: () => Promise<TaskOutcome<T>>): FPromise<TaskOutcome<T>> => {\n return fn() as unknown as FPromise<TaskOutcome<T>>\n}\n\n/**\n * Retrieves a single entity from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @returns A promise resolving to the entity if found\n */\nexport const getEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(baseQuery)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : baseQuery\n\n const { data, error } = await queryWithIs.single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Retrieves multiple entities from the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A promise resolving to the entities if found\n */\nexport const getEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }] = [\n \"id\" as keyof TableRow<T> & string,\n { ascending: true },\n ],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client.from(table).select(\"*\").match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const queryOrderBy = queryWithIs.order(order[0], order[1])\n\n const { data, error } = await queryOrderBy\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Adds multiple entities to the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to insert into\n * @param entities - The entities to add\n * @returns A promise resolving to the added entities\n */\nexport const addEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableInsert<T>[],\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const { data, error } = await client\n .from(table)\n .insert(entities as never)\n .select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as unknown as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Updates a single entity in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entity data to update\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entity\n */\nexport const updateEntity = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>,\n where: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<TableRow<T>>> =>\n wrapAsync(async () => {\n try {\n const baseQuery = client\n .from(table)\n .update(entities as never)\n .match(where)\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select().single()\n\n if (error) {\n return Err<TableRow<T>>(toError(error))\n }\n\n return Ok(data as TableRow<T>)\n } catch (error) {\n return Err<TableRow<T>>(toError(error))\n }\n })\n\n/**\n * Updates multiple entities in the specified table.\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to update\n * @param entities - The entities to update\n * @param identity - The column(s) to use as the identity\n * @param where - Conditions to filter by\n * @param is - IS conditions to filter by\n * @param wherein - WHERE IN conditions to filter by\n * @returns A promise resolving to the updated entities\n */\nexport const updateEntities = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n entities: TableUpdate<T>[],\n identity: (keyof TableRow<T> & string) | (keyof TableRow<T> & string)[] = \"id\" as keyof TableRow<T> & string,\n where?: WhereConditions<TableRow<T>>,\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n): FPromise<TaskOutcome<List<TableRow<T>>>> =>\n wrapAsync(async () => {\n try {\n const onConflict = Array.isArray(identity) ? identity.join(\",\") : identity\n\n const baseQuery = client\n .from(table)\n .upsert(entities as never, { onConflict })\n .match(where ?? {})\n\n const queryWithIn = wherein\n ? List(Object.entries(wherein)).foldLeft(baseQuery)((query, [column, values]) =>\n query.in(column, values as never),\n )\n : baseQuery\n\n const queryWithIs = is\n ? List(Object.entries(is)).foldLeft(queryWithIn)((query, [column, value]) =>\n query.is(column as keyof TableRow<T> & string, value as boolean | null),\n )\n : queryWithIn\n\n const { data, error } = await queryWithIs.select()\n\n if (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n\n return Ok(List(data as TableRow<T>[]))\n } catch (error) {\n return Err<List<TableRow<T>>>(toError(error))\n }\n })\n\n/**\n * Creates a new Query for the specified table with initial conditions.\n * This is the new Query-based API that supports OR chaining and functional operations.\n *\n * @template T - The table name\n * @param client - The Supabase client instance\n * @param table - The table to query\n * @param where - Initial WHERE conditions to filter by\n * @param is - Initial IS conditions to filter by\n * @param wherein - Initial WHERE IN conditions to filter by\n * @param order - Optional ordering parameters\n * @returns A Query<T> instance that supports chaining and lazy evaluation\n *\n * @example\n * // Simple query\n * const user = await query(client, \"users\", { id: \"123\" }).one()\n *\n * @example\n * // Query with OR logic\n * const users = await query(client, \"users\", { role: \"admin\" })\n * .or({ role: \"moderator\" })\n * .many()\n *\n * @example\n * // Query with functional operations\n * const names = await query(client, \"users\", { active: true })\n * .map(user => user.name)\n * .filter(name => name.startsWith('A'))\n * .many()\n */\nexport const query = <T extends TableNames>(\n client: SupabaseClientType,\n table: T,\n where: WhereConditions<TableRow<T>> = {},\n is?: IsConditionsLocal<TableRow<T>>,\n wherein?: Partial<Record<keyof TableRow<T>, unknown[]>>,\n order?: [keyof TableRow<T> & string, { ascending?: boolean; nullsFirst?: boolean }],\n): Query<T> => {\n return createQuery(client, table, where, is, wherein, order)\n}\n","import { addEntities, updateEntities, updateEntity } from \"@/query\"\nimport type { MultiExecution, Query, SingleExecution, WhereConditions } from \"@/query/Query\"\nimport { createQuery } from \"@/query/QueryBuilder\"\nimport type { EmptyObject, SupabaseClientType, TableInsert, TableNames, TableRow, TableUpdate } from \"@/types\"\n\nimport type { FPromise, List, TaskOutcome } from \"functype\"\nimport { Option } from \"functype\"\n\n// Field-level type safety for queries\nexport type TypedRecord<T, V> = Partial<Record<keyof T, V>>\n\n// Entity configuration\nexport type EntityConfig = {\n /** Soft delete filtering. true = exclude deleted items, false = include deleted items */\n softDelete: boolean\n /** Partition key for multi-tenant isolation. e.g., { tenant_id: \"123\" } */\n partitionKey?: Record<string, unknown>\n}\n\n// Base parameter types with field-level type safety\nexport type WhereParams<T extends object = EmptyObject> = {\n where?: WhereConditions<T>\n}\n\nexport type IsParams<T extends object = EmptyObject> = {\n is?: TypedRecord<T, null | boolean>\n}\n\nexport type WhereinParams<T extends object = EmptyObject> = {\n wherein?: TypedRecord<T, unknown[]>\n}\n\nexport type OrderParams<T extends object = EmptyObject> = {\n order?: [keyof T & string, { ascending?: boolean; nullsFirst?: boolean }]\n}\n\nexport type IdParam = {\n id: string\n}\n\n// Composable parameter types with field-level type safety\nexport type GetItemParams<T extends object = EmptyObject> = IdParam & WhereParams<T> & IsParams<T>\n\nexport type GetItemsParams<T extends object = EmptyObject> = WhereParams<T> &\n IsParams<T> &\n WhereinParams<T> &\n OrderParams<T>\n\nexport type AddItemsParams<T extends TableNames> = {\n items: TableInsert<T>[]\n}\n\nexport type UpdateItemParams<T extends TableNames, Row extends object = EmptyObject> = IdParam & {\n item: TableUpdate<T>\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\nexport type UpdateItemsParams<T extends TableNames, Row extends object = EmptyObject> = {\n items: TableUpdate<T>[]\n identity?: (keyof Row & string) | (keyof Row & string)[]\n} & WhereParams<Row> &\n IsParams<Row> &\n WhereinParams<Row>\n\n// =============================================================================\n// Mutation Query Wrappers for Consistent OrThrow Pattern\n// =============================================================================\n\n/**\n * Wrapper type for multi-result mutation operations that implements standard execution interface\n */\nexport type MutationMultiExecution<T> = FPromise<TaskOutcome<List<T>>> & MultiExecution<T>\n\n/**\n * Wrapper type for single-result mutation operations that implements standard execution interface\n */\nexport type MutationSingleExecution<T> = FPromise<TaskOutcome<T>> & SingleExecution<T>\n\n/**\n * Creates a multi-result mutation query that implements the standard execution interface\n */\nexport function MultiMutationQuery<T>(promise: FPromise<TaskOutcome<List<T>>>): MutationMultiExecution<T> {\n const result = Object.assign(promise, {\n // Standard MultiExecution interface\n many: () => promise,\n manyOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise,\n executeOrThrow: async (): Promise<List<T>> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n })\n return result as MutationMultiExecution<T>\n}\n\n/**\n * Creates a single-result mutation query that implements the standard execution interface\n */\nexport function SingleMutationQuery<T>(promise: FPromise<TaskOutcome<T>>): MutationSingleExecution<T> {\n const result = Object.assign(promise, {\n // Standard SingleExecution interface\n one: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n oneOrThrow: async (): Promise<T> => {\n const taskResult = await promise\n return taskResult.orThrow()\n },\n\n // Standard ExecutableQuery interface\n execute: () => promise.then((outcome: TaskOutcome<T>) => outcome.map((value: T) => Option(value))),\n executeOrThrow: async (): Promise<Option<T>> => {\n const taskResult = await promise\n const value = taskResult.orThrow()\n return Option(value)\n },\n })\n return result as MutationSingleExecution<T>\n}\n\n/**\n * Base interface for Entity instances\n */\nexport type IEntity<T extends TableNames> = {\n getItem(params: GetItemParams<TableRow<T>>): Query<T>\n getItems(params?: GetItemsParams<TableRow<T>>): Query<T>\n addItems(params: AddItemsParams<T>): MutationMultiExecution<TableRow<T>>\n updateItem(params: UpdateItemParams<T, TableRow<T>>): MutationSingleExecution<TableRow<T>>\n updateItems(params: UpdateItemsParams<T, TableRow<T>>): MutationMultiExecution<TableRow<T>>\n}\n\n/**\n * Creates an entity interface with methods for interacting with the given table.\n * @param client The Supabase client instance to use for queries.\n * @param name The name of the table to interact with.\n * @param config Configuration for entity behavior (required).\n * @returns An object with methods for interacting with the table.\n */\nexport const Entity = <T extends TableNames>(client: SupabaseClientType, name: T, config: EntityConfig): IEntity<T> => {\n type ROW = TableRow<T>\n\n const softDeleteMode = config.softDelete ? \"exclude\" : \"include\"\n\n /**\n * Retrieve a single item from the given table by ID.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemParams<ROW>} params Parameters.\n * @param {string} params.id The ID of the item to retrieve.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItem({ id, where, is }: GetItemParams<ROW>): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where, id } : { ...where, id }\n return createQuery(\n client,\n name,\n whereWithPartition as unknown as WhereConditions<TableRow<T>>,\n is,\n undefined,\n undefined,\n { mode: softDeleteMode, appliedByDefault: true },\n )\n }\n\n /**\n * Get a list of items from the given table filtered by the given conditions.\n * Returns a Query<T> that can be chained with OR conditions and functional operations.\n * @param {GetItemsParams<ROW>} params Optional parameters.\n * @param {TypedRecord<ROW, unknown>} [params.where] Conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @param {[keyof ROW & string, { ascending?: boolean; nullsFirst?: boolean }]} [params.order] Optional ordering parameters.\n * @returns {Query<T>} A chainable query that can be executed with .one(), .many(), or .first()\n */\n function getItems({ where, is, wherein, order }: GetItemsParams<ROW> = {}): Query<T> {\n const whereWithPartition = config.partitionKey ? { ...config.partitionKey, ...where } : where\n return createQuery(client, name, whereWithPartition as WhereConditions<TableRow<T>>, is, wherein, order, {\n mode: softDeleteMode,\n appliedByDefault: true,\n })\n }\n\n /**\n * Adds multiple items to the given table.\n * @param {AddItemsParams<T>} params Parameters.\n * @param {TableInsert<T>[]} params.items The items to add.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function addItems({ items }: AddItemsParams<T>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(addEntities(client, name, items))\n }\n\n /**\n * Update a single item in the given table.\n * @param {UpdateItemParams<T, ROW>} params Parameters.\n * @param {string} params.id The ID of the item to update.\n * @param {Partial<TableUpdate<T>>} params.item The item to update.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationSingleExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItem({ id, item, where, is, wherein }: UpdateItemParams<T, ROW>): MutationSingleExecution<ROW> {\n return SingleMutationQuery(\n updateEntity(client, name, item, { ...where, id } as unknown as WhereConditions<TableRow<T>>, is, wherein),\n )\n }\n\n /**\n * Update multiple items in the given table.\n * @param {UpdateItemsParams<T, ROW>} params Parameters.\n * @param {TableUpdate<T>[]} params.items The items to update.\n * @param {keyof ROW & string | (keyof ROW & string)[]} [params.identity=\"id\"] The column(s) to use as the identity.\n * @param {TypedRecord<ROW, unknown>} [params.where] Additional conditions to filter by.\n * @param {TypedRecord<ROW, null | boolean>} [params.is] IS conditions to filter by.\n * @param {TypedRecord<ROW, unknown[]>} [params.wherein] WHERE IN conditions to filter by.\n * @returns {MutationMultiExecution<ROW>} A mutation query with consistent OrThrow methods.\n */\n function updateItems({\n items,\n identity = \"id\" as keyof ROW & string,\n where,\n is,\n wherein,\n }: UpdateItemsParams<T, ROW>): MutationMultiExecution<ROW> {\n return MultiMutationQuery(updateEntities(client, name, items, identity, where, is, wherein))\n }\n\n return {\n getItem,\n getItems,\n addItems,\n updateItem,\n updateItems,\n }\n}\n\n/**\n * Type for an entity instance for a specific table\n * @deprecated Use IEntity<T> instead\n */\nexport type EntityType<T extends TableNames> = IEntity<T>\n"],"names":["wrapAsync","query"],"mappings":";;AAaO,MAAM,sBAAsB,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,OAAsC;AAGhD,QAAI,iBAAiB,OAAO;AAC1B,YAAM,MAAM,OAAO;AACnB,WAAK,OAAO,MAAM;AAClB,WAAK,QAAQ,MAAM;AAAA,IACrB,WAAW,gBAAgB,KAAK,GAAG;AACjC,YAAM,MAAM,OAAO;AACnB,WAAK,OAAO;AACZ,WAAK,OAAO,MAAM;AAClB,WAAK,UAAU,MAAM;AACrB,WAAK,OAAO,MAAM;AAAA,IACpB,OA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,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAM,EACxC,KAAK,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAC9B,UAAU,OAAO,CAAC,MAAM,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,EACvD,QAAQ,CAAC,MAAM,QAAQ,CAAC,CAAC,CAAC,GAAG,MAAM,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,EACnF,mBAAmB;IAAE,IAAI,CAAC,EAAE,SAAS,GAAG,SAAS,GAAG,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAE,KACvF,KAAK,CAAC,CAAC,CAST,CAAA"}
@@ -8,6 +8,15 @@ export interface Database {
8
8
  Insert: Record<string, unknown>;
9
9
  Update: Record<string, unknown>;
10
10
  }>;
11
+ Views: Record<string, {
12
+ Row: Record<string, unknown>;
13
+ }>;
14
+ Functions: Record<string, {
15
+ Args: Record<string, unknown>;
16
+ Returns: unknown;
17
+ }>;
18
+ Enums: Record<string, unknown>;
19
+ CompositeTypes: Record<string, unknown>;
11
20
  };
12
21
  }
13
22
  export type TableNames = keyof Database["public"]["Tables"];
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,MAAM,WAAW,QAAQ;IACvB,MAAM,EAAE;QACN,MAAM,EAAE,MAAM,CACZ,MAAM,EACN;YACE,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;YAC5B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;YAC/B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;SAChC,CACF,CAAA;KACF,CAAA;CACF;AAGD,MAAM,MAAM,UAAU,GAAG,MAAM,QAAQ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AE,MAAM,KAAK,YAAY,CAAA;IACxD,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,KAAK,YAAY,CAAA;IAC3D,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,YAAY,CAAA;IACvD,EAAE,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,YAAY,CAAA;IACrC,MAAM,EAAE,MAAM,YAAY,CAAA;IAC1B,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,YAAY,CAAA;IACtC,KAAK,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,YAAY,CAAA;CAC3E;AAGD,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,YAAY,CAAA;CACtC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "supabase-typed-query",
3
- "version": "0.2.0",
3
+ "version": "0.2.3",
4
4
  "description": "Type-safe query builder and entity pattern for Supabase with TypeScript",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -45,23 +45,25 @@
45
45
  },
46
46
  "devDependencies": {
47
47
  "@eslint/eslintrc": "^3.3.1",
48
- "@eslint/js": "^9.38.0",
49
- "@supabase/supabase-js": "^2.76.1",
50
- "@types/node": "^22.18.12",
51
- "@typescript-eslint/eslint-plugin": "^8.46.2",
52
- "@typescript-eslint/parser": "^8.46.2",
53
- "eslint": "^9.38.0",
48
+ "@eslint/js": "^9.39.1",
49
+ "@supabase/supabase-js": "^2.84.0",
50
+ "@types/node": "^22.19.1",
51
+ "@typescript-eslint/eslint-plugin": "^8.47.0",
52
+ "@typescript-eslint/parser": "^8.47.0",
53
+ "@vitest/coverage-v8": "4.0.4",
54
+ "dotenv": "^17.2.3",
55
+ "eslint": "^9.39.1",
54
56
  "eslint-config-prettier": "^10.1.8",
55
57
  "eslint-plugin-functional": "^9.0.2",
56
58
  "eslint-plugin-prettier": "^5.5.4",
57
59
  "eslint-plugin-simple-import-sort": "^12.1.1",
58
- "functype": "^0.17.0",
59
- "globals": "^16.4.0",
60
+ "functype": "^0.18.0",
61
+ "globals": "^16.5.0",
60
62
  "prettier": "^3.6.2",
61
63
  "typescript": "^5.9.3",
62
- "vite": "^7.1.12",
64
+ "vite": "^7.2.4",
63
65
  "vite-plugin-dts": "^4.5.4",
64
- "vitest": "^3.2.4"
66
+ "vitest": "^4.0.12"
65
67
  },
66
68
  "engines": {
67
69
  "node": ">=18"
@@ -70,7 +72,7 @@
70
72
  "eslint-config-functype": "^1.3.0"
71
73
  },
72
74
  "scripts": {
73
- "validate": "pnpm format && pnpm lint && pnpm typecheck && pnpm test && pnpm build",
75
+ "validate": "pnpm format && pnpm lint && pnpm typecheck && pnpm test:unit && pnpm build",
74
76
  "format": "prettier --log-level warn --write \"./**/*.{ts,tsx,css,md,json}\"",
75
77
  "format:check": "prettier --log-level warn --check \"./**/*.{ts,tsx,css,md,json}\"",
76
78
  "lint": "eslint --quiet --fix \"**/*.{ts,tsx}\"",
@@ -78,10 +80,21 @@
78
80
  "typecheck": "tsc --noEmit",
79
81
  "test": "vitest run",
80
82
  "test:watch": "vitest",
83
+ "test:unit": "vitest run --config vitest.config.ts",
84
+ "test:unit:watch": "vitest --config vitest.config.ts",
85
+ "test:unit:coverage": "vitest run --coverage --config vitest.config.ts",
86
+ "test:integration": "vitest run --config vitest.config.integration.ts",
87
+ "test:integration:watch": "vitest --config vitest.config.integration.ts",
88
+ "test:integration:coverage": "vitest run --coverage --config vitest.config.integration.ts",
89
+ "test:ci": "pnpm test:unit && pnpm test:integration",
81
90
  "test:coverage": "vitest run --coverage",
82
91
  "build": "vite build --emptyOutDir",
83
92
  "build:dev": "vite build --emptyOutDir",
84
93
  "build:dev:watch": "vite build --watch --emptyOutDir",
85
- "build:publish": "pnpm validate && pnpm publish --no-git-checks"
94
+ "build:publish": "pnpm validate && pnpm publish --no-git-checks",
95
+ "supabase:start": "supabase start",
96
+ "supabase:stop": "supabase stop",
97
+ "supabase:status": "supabase status",
98
+ "supabase:types": "supabase gen types typescript --local > test/integration/database.types.ts"
86
99
  }
87
100
  }