@proofkit/fmodata 0.1.0-alpha.13 → 0.1.0-alpha.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/README.md +489 -334
  2. package/dist/esm/client/batch-builder.d.ts +7 -4
  3. package/dist/esm/client/batch-builder.js +84 -25
  4. package/dist/esm/client/batch-builder.js.map +1 -1
  5. package/dist/esm/client/builders/default-select.d.ts +7 -0
  6. package/dist/esm/client/builders/default-select.js +42 -0
  7. package/dist/esm/client/builders/default-select.js.map +1 -0
  8. package/dist/esm/client/builders/expand-builder.d.ts +43 -0
  9. package/dist/esm/client/builders/expand-builder.js +173 -0
  10. package/dist/esm/client/builders/expand-builder.js.map +1 -0
  11. package/dist/esm/client/builders/index.d.ts +8 -0
  12. package/dist/esm/client/builders/query-string-builder.d.ts +15 -0
  13. package/dist/esm/client/builders/query-string-builder.js +25 -0
  14. package/dist/esm/client/builders/query-string-builder.js.map +1 -0
  15. package/dist/esm/client/builders/response-processor.d.ts +39 -0
  16. package/dist/esm/client/builders/response-processor.js +170 -0
  17. package/dist/esm/client/builders/response-processor.js.map +1 -0
  18. package/dist/esm/client/builders/select-mixin.d.ts +31 -0
  19. package/dist/esm/client/builders/select-mixin.js +30 -0
  20. package/dist/esm/client/builders/select-mixin.js.map +1 -0
  21. package/dist/esm/client/builders/select-utils.d.ts +8 -0
  22. package/dist/esm/client/builders/select-utils.js +15 -0
  23. package/dist/esm/client/builders/select-utils.js.map +1 -0
  24. package/dist/esm/client/builders/shared-types.d.ts +39 -0
  25. package/dist/esm/client/builders/table-utils.d.ts +35 -0
  26. package/dist/esm/client/builders/table-utils.js +45 -0
  27. package/dist/esm/client/builders/table-utils.js.map +1 -0
  28. package/dist/esm/client/database.d.ts +3 -22
  29. package/dist/esm/client/database.js +14 -76
  30. package/dist/esm/client/database.js.map +1 -1
  31. package/dist/esm/client/delete-builder.d.ts +11 -15
  32. package/dist/esm/client/delete-builder.js +26 -26
  33. package/dist/esm/client/delete-builder.js.map +1 -1
  34. package/dist/esm/client/entity-set.d.ts +32 -32
  35. package/dist/esm/client/entity-set.js +92 -69
  36. package/dist/esm/client/entity-set.js.map +1 -1
  37. package/dist/esm/client/error-parser.d.ts +12 -0
  38. package/dist/esm/client/error-parser.js +30 -0
  39. package/dist/esm/client/error-parser.js.map +1 -0
  40. package/dist/esm/client/filemaker-odata.d.ts +2 -4
  41. package/dist/esm/client/filemaker-odata.js +1 -5
  42. package/dist/esm/client/filemaker-odata.js.map +1 -1
  43. package/dist/esm/client/insert-builder.d.ts +7 -9
  44. package/dist/esm/client/insert-builder.js +70 -24
  45. package/dist/esm/client/insert-builder.js.map +1 -1
  46. package/dist/esm/client/query/expand-builder.d.ts +35 -0
  47. package/dist/esm/client/query/index.d.ts +3 -0
  48. package/dist/esm/client/query/query-builder.d.ts +134 -0
  49. package/dist/esm/client/query/query-builder.js +505 -0
  50. package/dist/esm/client/query/query-builder.js.map +1 -0
  51. package/dist/esm/client/query/response-processor.d.ts +22 -0
  52. package/dist/esm/client/query/types.d.ts +52 -0
  53. package/dist/esm/client/query/url-builder.d.ts +71 -0
  54. package/dist/esm/client/query/url-builder.js +107 -0
  55. package/dist/esm/client/query/url-builder.js.map +1 -0
  56. package/dist/esm/client/query-builder.d.ts +1 -111
  57. package/dist/esm/client/record-builder.d.ts +56 -63
  58. package/dist/esm/client/record-builder.js +158 -297
  59. package/dist/esm/client/record-builder.js.map +1 -1
  60. package/dist/esm/client/response-processor.d.ts +3 -3
  61. package/dist/esm/client/update-builder.d.ts +16 -21
  62. package/dist/esm/client/update-builder.js +56 -30
  63. package/dist/esm/client/update-builder.js.map +1 -1
  64. package/dist/esm/errors.d.ts +8 -1
  65. package/dist/esm/errors.js +17 -0
  66. package/dist/esm/errors.js.map +1 -1
  67. package/dist/esm/index.d.ts +3 -7
  68. package/dist/esm/index.js +37 -8
  69. package/dist/esm/index.js.map +1 -1
  70. package/dist/esm/orm/column.d.ts +45 -0
  71. package/dist/esm/orm/column.js +59 -0
  72. package/dist/esm/orm/column.js.map +1 -0
  73. package/dist/esm/orm/field-builders.d.ts +154 -0
  74. package/dist/esm/orm/field-builders.js +152 -0
  75. package/dist/esm/orm/field-builders.js.map +1 -0
  76. package/dist/esm/orm/index.d.ts +4 -0
  77. package/dist/esm/orm/operators.d.ts +175 -0
  78. package/dist/esm/orm/operators.js +221 -0
  79. package/dist/esm/orm/operators.js.map +1 -0
  80. package/dist/esm/orm/table.d.ts +341 -0
  81. package/dist/esm/orm/table.js +211 -0
  82. package/dist/esm/orm/table.js.map +1 -0
  83. package/dist/esm/transform.d.ts +20 -21
  84. package/dist/esm/transform.js +34 -34
  85. package/dist/esm/transform.js.map +1 -1
  86. package/dist/esm/types.d.ts +16 -13
  87. package/dist/esm/types.js.map +1 -1
  88. package/dist/esm/validation.d.ts +14 -4
  89. package/dist/esm/validation.js +45 -1
  90. package/dist/esm/validation.js.map +1 -1
  91. package/package.json +20 -17
  92. package/src/client/batch-builder.ts +100 -32
  93. package/src/client/builders/default-select.ts +69 -0
  94. package/src/client/builders/expand-builder.ts +236 -0
  95. package/src/client/builders/index.ts +11 -0
  96. package/src/client/builders/query-string-builder.ts +41 -0
  97. package/src/client/builders/response-processor.ts +273 -0
  98. package/src/client/builders/select-mixin.ts +74 -0
  99. package/src/client/builders/select-utils.ts +34 -0
  100. package/src/client/builders/shared-types.ts +41 -0
  101. package/src/client/builders/table-utils.ts +87 -0
  102. package/src/client/database.ts +19 -160
  103. package/src/client/delete-builder.ts +46 -51
  104. package/src/client/entity-set.ts +227 -302
  105. package/src/client/error-parser.ts +59 -0
  106. package/src/client/filemaker-odata.ts +3 -14
  107. package/src/client/insert-builder.ts +124 -43
  108. package/src/client/query/expand-builder.ts +164 -0
  109. package/src/client/query/index.ts +13 -0
  110. package/src/client/query/query-builder.ts +816 -0
  111. package/src/client/query/response-processor.ts +244 -0
  112. package/src/client/query/types.ts +102 -0
  113. package/src/client/query/url-builder.ts +179 -0
  114. package/src/client/query-builder.ts +8 -1454
  115. package/src/client/record-builder.ts +325 -585
  116. package/src/client/response-processor.ts +4 -5
  117. package/src/client/update-builder.ts +102 -73
  118. package/src/errors.ts +22 -1
  119. package/src/index.ts +55 -5
  120. package/src/orm/column.ts +78 -0
  121. package/src/orm/field-builders.ts +296 -0
  122. package/src/orm/index.ts +60 -0
  123. package/src/orm/operators.ts +428 -0
  124. package/src/orm/table.ts +759 -0
  125. package/src/transform.ts +62 -48
  126. package/src/types.ts +20 -63
  127. package/src/validation.ts +76 -4
  128. package/LICENSE.md +0 -21
  129. package/dist/esm/client/base-table.d.ts +0 -128
  130. package/dist/esm/client/base-table.js +0 -57
  131. package/dist/esm/client/base-table.js.map +0 -1
  132. package/dist/esm/client/build-occurrences.d.ts +0 -74
  133. package/dist/esm/client/build-occurrences.js +0 -31
  134. package/dist/esm/client/build-occurrences.js.map +0 -1
  135. package/dist/esm/client/query-builder.js +0 -900
  136. package/dist/esm/client/query-builder.js.map +0 -1
  137. package/dist/esm/client/table-occurrence.d.ts +0 -86
  138. package/dist/esm/client/table-occurrence.js +0 -58
  139. package/dist/esm/client/table-occurrence.js.map +0 -1
  140. package/src/client/base-table.ts +0 -178
  141. package/src/client/build-occurrences.ts +0 -155
  142. package/src/client/query-builder.ts.bak +0 -1457
  143. package/src/client/table-occurrence.ts +0 -156
@@ -0,0 +1,816 @@
1
+ import { QueryOptions } from "odata-query";
2
+ import buildQuery from "odata-query";
3
+ import type {
4
+ ExecutionContext,
5
+ ExecutableBuilder,
6
+ Result,
7
+ ExecuteOptions,
8
+ ConditionallyWithODataAnnotations,
9
+ ExtractSchemaFromOccurrence,
10
+ } from "../../types";
11
+ import type { Filter } from "../../filter-types";
12
+ import { RecordCountMismatchError } from "../../errors";
13
+ import { type FFetchOptions } from "@fetchkit/ffetch";
14
+ import {
15
+ transformFieldName,
16
+ transformFieldNamesArray,
17
+ transformOrderByField,
18
+ } from "../../transform";
19
+ import { safeJsonParse } from "../sanitize-json";
20
+ import { parseErrorResponse } from "../error-parser";
21
+ import { isColumn, type Column } from "../../orm/column";
22
+ import {
23
+ FilterExpression,
24
+ OrderByExpression,
25
+ isOrderByExpression,
26
+ } from "../../orm/operators";
27
+ import {
28
+ FMTable,
29
+ type InferSchemaOutputFromFMTable,
30
+ type ValidExpandTarget,
31
+ type ExtractTableName,
32
+ type ValidateNoContainerFields,
33
+ getTableName,
34
+ } from "../../orm/table";
35
+ import {
36
+ ExpandBuilder,
37
+ type ExpandConfig,
38
+ type ExpandedRelations,
39
+ resolveTableId,
40
+ mergeExecuteOptions,
41
+ formatSelectFields,
42
+ processQueryResponse,
43
+ processSelectWithRenames,
44
+ buildSelectExpandQueryString,
45
+ createODataRequest,
46
+ } from "../builders";
47
+ import { QueryUrlBuilder, type NavigationConfig } from "./url-builder";
48
+ import type { TypeSafeOrderBy, QueryReturnType } from "./types";
49
+
50
+ // Re-export QueryReturnType for backward compatibility
51
+ export type { QueryReturnType };
52
+
53
+ /**
54
+ * Default maximum number of records to return in a list query.
55
+ * This prevents stack overflow issues with large datasets while still
56
+ * allowing substantial data retrieval. Users can override with .top().
57
+ */
58
+ const DEFAULT_TOP = 1000;
59
+
60
+ export type { TypeSafeOrderBy, ExpandedRelations };
61
+
62
+ export class QueryBuilder<
63
+ Occ extends FMTable<any, any>,
64
+ Selected extends
65
+ | keyof InferSchemaOutputFromFMTable<Occ>
66
+ | Record<
67
+ string,
68
+ Column<any, ExtractTableName<Occ>>
69
+ > = keyof InferSchemaOutputFromFMTable<Occ>,
70
+ SingleMode extends "exact" | "maybe" | false = false,
71
+ IsCount extends boolean = false,
72
+ Expands extends ExpandedRelations = {},
73
+ > implements
74
+ ExecutableBuilder<
75
+ QueryReturnType<
76
+ InferSchemaOutputFromFMTable<Occ>,
77
+ Selected,
78
+ SingleMode,
79
+ IsCount,
80
+ Expands
81
+ >
82
+ >
83
+ {
84
+ private queryOptions: Partial<
85
+ QueryOptions<InferSchemaOutputFromFMTable<Occ>>
86
+ > = {};
87
+ private expandConfigs: ExpandConfig[] = [];
88
+ private singleMode: SingleMode = false as SingleMode;
89
+ private isCountMode = false as IsCount;
90
+ private occurrence: Occ;
91
+ private databaseName: string;
92
+ private context: ExecutionContext;
93
+ private navigation?: NavigationConfig;
94
+ private databaseUseEntityIds: boolean;
95
+ private expandBuilder: ExpandBuilder;
96
+ private urlBuilder: QueryUrlBuilder;
97
+ // Mapping from field names to output keys (for renamed fields in select)
98
+ private fieldMapping?: Record<string, string>;
99
+
100
+ constructor(config: {
101
+ occurrence: Occ;
102
+ databaseName: string;
103
+ context: ExecutionContext;
104
+ databaseUseEntityIds?: boolean;
105
+ }) {
106
+ this.occurrence = config.occurrence;
107
+ this.databaseName = config.databaseName;
108
+ this.context = config.context;
109
+ this.databaseUseEntityIds = config.databaseUseEntityIds ?? false;
110
+ this.expandBuilder = new ExpandBuilder(this.databaseUseEntityIds);
111
+ this.urlBuilder = new QueryUrlBuilder(
112
+ this.databaseName,
113
+ this.occurrence,
114
+ this.context,
115
+ );
116
+ }
117
+
118
+ /**
119
+ * Helper to merge database-level useEntityIds with per-request options
120
+ */
121
+ private mergeExecuteOptions(
122
+ options?: RequestInit & FFetchOptions & ExecuteOptions,
123
+ ): RequestInit & FFetchOptions & { useEntityIds?: boolean } {
124
+ return mergeExecuteOptions(options, this.databaseUseEntityIds);
125
+ }
126
+
127
+ /**
128
+ * Gets the FMTable instance
129
+ */
130
+ private getTable(): FMTable<any, any> | undefined {
131
+ return this.occurrence;
132
+ }
133
+
134
+ /**
135
+ * Gets the table ID (FMTID) if using entity IDs, otherwise returns the table name
136
+ * @param useEntityIds - Optional override for entity ID usage
137
+ */
138
+ private getTableIdOrName(useEntityIds?: boolean): string {
139
+ return resolveTableId(
140
+ this.occurrence,
141
+ getTableName(this.occurrence),
142
+ this.context,
143
+ useEntityIds,
144
+ );
145
+ }
146
+
147
+ /**
148
+ * Creates a new QueryBuilder with modified configuration.
149
+ * Used by single(), maybeSingle(), count(), and select() to create new instances.
150
+ */
151
+ private cloneWithChanges<
152
+ NewSelected extends
153
+ | keyof InferSchemaOutputFromFMTable<Occ>
154
+ | Record<string, Column<any, ExtractTableName<Occ>>> = Selected,
155
+ NewSingle extends "exact" | "maybe" | false = SingleMode,
156
+ NewCount extends boolean = IsCount,
157
+ >(changes: {
158
+ selectedFields?: NewSelected;
159
+ singleMode?: NewSingle;
160
+ isCountMode?: NewCount;
161
+ queryOptions?: Partial<QueryOptions<InferSchemaOutputFromFMTable<Occ>>>;
162
+ fieldMapping?: Record<string, string>;
163
+ }): QueryBuilder<Occ, NewSelected, NewSingle, NewCount, Expands> {
164
+ const newBuilder = new QueryBuilder<
165
+ Occ,
166
+ NewSelected,
167
+ NewSingle,
168
+ NewCount,
169
+ Expands
170
+ >({
171
+ occurrence: this.occurrence,
172
+ databaseName: this.databaseName,
173
+ context: this.context,
174
+ databaseUseEntityIds: this.databaseUseEntityIds,
175
+ });
176
+ newBuilder.queryOptions = {
177
+ ...this.queryOptions,
178
+ ...changes.queryOptions,
179
+ };
180
+ newBuilder.expandConfigs = [...this.expandConfigs];
181
+ newBuilder.singleMode = (changes.singleMode ?? this.singleMode) as any;
182
+ newBuilder.isCountMode = (changes.isCountMode ?? this.isCountMode) as any;
183
+ newBuilder.fieldMapping = changes.fieldMapping ?? this.fieldMapping;
184
+ // Copy navigation metadata
185
+ newBuilder.navigation = this.navigation;
186
+ newBuilder.urlBuilder = new QueryUrlBuilder(
187
+ this.databaseName,
188
+ this.occurrence,
189
+ this.context,
190
+ );
191
+ return newBuilder;
192
+ }
193
+
194
+ /**
195
+ * Select fields using column references.
196
+ * Allows renaming fields by using different keys in the object.
197
+ * Container fields cannot be selected and will cause a type error.
198
+ *
199
+ * @example
200
+ * db.from(users).list().select({
201
+ * name: users.name,
202
+ * userEmail: users.email // renamed!
203
+ * })
204
+ *
205
+ * @param fields - Object mapping output keys to column references (container fields excluded)
206
+ * @returns QueryBuilder with updated selected fields
207
+ */
208
+ select<
209
+ TSelect extends Record<string, Column<any, ExtractTableName<Occ>, false>>,
210
+ >(fields: TSelect): QueryBuilder<Occ, TSelect, SingleMode, IsCount, Expands> {
211
+ const tableName = getTableName(this.occurrence);
212
+ const { selectedFields, fieldMapping } = processSelectWithRenames(
213
+ fields,
214
+ tableName,
215
+ );
216
+
217
+ return this.cloneWithChanges({
218
+ selectedFields: fields as any,
219
+ queryOptions: {
220
+ select: selectedFields,
221
+ },
222
+ fieldMapping:
223
+ Object.keys(fieldMapping).length > 0 ? fieldMapping : undefined,
224
+ });
225
+ }
226
+
227
+ /**
228
+ * Transforms our filter format to odata-query's expected format
229
+ * - Arrays of operators are converted to AND conditions
230
+ * - Single operator objects pass through as-is
231
+ * - Shorthand values are handled by odata-query
232
+ */
233
+ private transformFilter(
234
+ filter: Filter<ExtractSchemaFromOccurrence<Occ>>,
235
+ ): QueryOptions<InferSchemaOutputFromFMTable<Occ>>["filter"] {
236
+ if (typeof filter === "string") {
237
+ // Raw string filters pass through
238
+ return filter;
239
+ }
240
+
241
+ if (Array.isArray(filter)) {
242
+ // Array of filters - odata-query handles this as implicit AND
243
+ return filter.map((f) => this.transformFilter(f as any)) as any;
244
+ }
245
+
246
+ // Check if it's a logical filter (and/or/not)
247
+ if ("and" in filter || "or" in filter || "not" in filter) {
248
+ const result: any = {};
249
+ if ("and" in filter && Array.isArray(filter.and)) {
250
+ result.and = filter.and.map((f: any) => this.transformFilter(f));
251
+ }
252
+ if ("or" in filter && Array.isArray(filter.or)) {
253
+ result.or = filter.or.map((f: any) => this.transformFilter(f));
254
+ }
255
+ if ("not" in filter && filter.not) {
256
+ result.not = this.transformFilter(filter.not as any);
257
+ }
258
+ return result;
259
+ }
260
+
261
+ // Transform field filters
262
+ const result: any = {};
263
+ const andConditions: any[] = [];
264
+
265
+ for (const [field, value] of Object.entries(filter)) {
266
+ // Transform field name to FMFID if using entity IDs AND the feature is enabled
267
+ const shouldTransform = this.occurrence && this.databaseUseEntityIds;
268
+ const fieldId = shouldTransform
269
+ ? transformFieldName(field, this.occurrence!)
270
+ : field;
271
+
272
+ if (Array.isArray(value)) {
273
+ // Array of operators - convert to AND conditions
274
+ if (value.length === 1) {
275
+ // Single operator in array - unwrap it
276
+ result[fieldId] = value[0];
277
+ } else {
278
+ // Multiple operators - combine with AND
279
+ // Create separate conditions for each operator
280
+ for (const op of value) {
281
+ andConditions.push({ [fieldId]: op });
282
+ }
283
+ }
284
+ } else if (
285
+ value &&
286
+ typeof value === "object" &&
287
+ !(value instanceof Date) &&
288
+ !Array.isArray(value)
289
+ ) {
290
+ // Check if it's an operator object (has operator keys like eq, gt, etc.)
291
+ const operatorKeys = [
292
+ "eq",
293
+ "ne",
294
+ "gt",
295
+ "ge",
296
+ "lt",
297
+ "le",
298
+ "contains",
299
+ "startswith",
300
+ "endswith",
301
+ "in",
302
+ ];
303
+ const isOperatorObject = operatorKeys.some((key) => key in value);
304
+
305
+ if (isOperatorObject) {
306
+ // Single operator object - pass through
307
+ result[fieldId] = value;
308
+ } else {
309
+ // Regular object - might be nested filter, pass through
310
+ result[fieldId] = value;
311
+ }
312
+ } else {
313
+ // Primitive value (shorthand) - pass through
314
+ result[fieldId] = value;
315
+ }
316
+ }
317
+
318
+ // If we have AND conditions from arrays, combine them
319
+ if (andConditions.length > 0) {
320
+ if (Object.keys(result).length > 0) {
321
+ // We have both regular fields and array-derived AND conditions
322
+ // Combine everything with AND
323
+ return { and: [...andConditions, result] };
324
+ } else {
325
+ // Only array-derived AND conditions
326
+ return { and: andConditions };
327
+ }
328
+ }
329
+
330
+ return result;
331
+ }
332
+
333
+ filter(
334
+ filter: Filter<ExtractSchemaFromOccurrence<Occ>>,
335
+ ): QueryBuilder<Occ, Selected, SingleMode, IsCount, Expands> {
336
+ // Transform our filter format to odata-query's expected format
337
+ this.queryOptions.filter = this.transformFilter(filter) as any;
338
+ return this;
339
+ }
340
+
341
+ /**
342
+ * Filter results using operator expressions (new ORM-style API).
343
+ * Supports eq, gt, lt, and, or, etc. operators with Column references.
344
+ *
345
+ * @example
346
+ * .where(eq(users.hobby, "reading"))
347
+ * .where(and(eq(users.active, true), gt(users.age, 18)))
348
+ */
349
+ where(
350
+ expression: FilterExpression,
351
+ ): QueryBuilder<Occ, Selected, SingleMode, IsCount, Expands> {
352
+ // Convert FilterExpression to OData filter string
353
+ const filterString = expression.toODataFilter(this.databaseUseEntityIds);
354
+ this.queryOptions.filter = filterString;
355
+ return this;
356
+ }
357
+
358
+ /**
359
+ * Specify the sort order for query results.
360
+ *
361
+ * @example Single field (ascending by default)
362
+ * ```ts
363
+ * .orderBy("name")
364
+ * .orderBy(users.name) // Column reference
365
+ * .orderBy(asc(users.name)) // Explicit ascending
366
+ * ```
367
+ *
368
+ * @example Single field with explicit direction
369
+ * ```ts
370
+ * .orderBy(["name", "desc"])
371
+ * .orderBy([users.name, "desc"]) // Column reference
372
+ * .orderBy(desc(users.name)) // Explicit descending
373
+ * ```
374
+ *
375
+ * @example Multiple fields with directions
376
+ * ```ts
377
+ * .orderBy([["name", "asc"], ["createdAt", "desc"]])
378
+ * .orderBy([[users.name, "asc"], [users.createdAt, "desc"]]) // Column references
379
+ * .orderBy(users.name, desc(users.age)) // Variadic with helpers
380
+ * ```
381
+ */
382
+ orderBy(
383
+ ...orderByArgs:
384
+ | [
385
+ | TypeSafeOrderBy<InferSchemaOutputFromFMTable<Occ>>
386
+ | Column<any, ExtractTableName<Occ>>
387
+ | OrderByExpression<ExtractTableName<Occ>>,
388
+ ]
389
+ | [
390
+ Column<any, ExtractTableName<Occ>>,
391
+ ...Array<
392
+ | Column<any, ExtractTableName<Occ>>
393
+ | OrderByExpression<ExtractTableName<Occ>>
394
+ >,
395
+ ]
396
+ ): QueryBuilder<Occ, Selected, SingleMode, IsCount, Expands> {
397
+ const tableName = getTableName(this.occurrence);
398
+
399
+ // Handle variadic arguments (multiple fields)
400
+ if (orderByArgs.length > 1) {
401
+ const orderByParts = orderByArgs.map((arg) => {
402
+ if (isOrderByExpression(arg)) {
403
+ // Validate table match
404
+ if (arg.column.tableName !== tableName) {
405
+ console.warn(
406
+ `Column ${arg.column.toString()} is from table "${arg.column.tableName}", but query is for table "${tableName}"`,
407
+ );
408
+ }
409
+ const fieldName = arg.column.fieldName;
410
+ const transformedField = this.occurrence
411
+ ? transformOrderByField(fieldName, this.occurrence)
412
+ : fieldName;
413
+ return `${transformedField} ${arg.direction}`;
414
+ } else if (isColumn(arg)) {
415
+ // Validate table match
416
+ if (arg.tableName !== tableName) {
417
+ console.warn(
418
+ `Column ${arg.toString()} is from table "${arg.tableName}", but query is for table "${tableName}"`,
419
+ );
420
+ }
421
+ const fieldName = arg.fieldName;
422
+ const transformedField = this.occurrence
423
+ ? transformOrderByField(fieldName, this.occurrence)
424
+ : fieldName;
425
+ return transformedField; // Default to ascending
426
+ } else {
427
+ throw new Error(
428
+ "Variadic orderBy() only accepts Column or OrderByExpression arguments",
429
+ );
430
+ }
431
+ });
432
+ this.queryOptions.orderBy = orderByParts;
433
+ return this;
434
+ }
435
+
436
+ // Handle single argument
437
+ const orderBy = orderByArgs[0];
438
+
439
+ // Handle OrderByExpression
440
+ if (isOrderByExpression(orderBy)) {
441
+ // Validate table match
442
+ if (orderBy.column.tableName !== tableName) {
443
+ console.warn(
444
+ `Column ${orderBy.column.toString()} is from table "${orderBy.column.tableName}", but query is for table "${tableName}"`,
445
+ );
446
+ }
447
+ const fieldName = orderBy.column.fieldName;
448
+ const transformedField = this.occurrence
449
+ ? transformOrderByField(fieldName, this.occurrence)
450
+ : fieldName;
451
+ this.queryOptions.orderBy = `${transformedField} ${orderBy.direction}`;
452
+ return this;
453
+ }
454
+
455
+ // Handle Column references
456
+ if (isColumn(orderBy)) {
457
+ // Validate table match
458
+ if (orderBy.tableName !== tableName) {
459
+ console.warn(
460
+ `Column ${orderBy.toString()} is from table "${orderBy.tableName}", but query is for table "${tableName}"`,
461
+ );
462
+ }
463
+ // Single Column reference without direction (defaults to ascending)
464
+ const fieldName = orderBy.fieldName;
465
+ this.queryOptions.orderBy = this.occurrence
466
+ ? transformOrderByField(fieldName, this.occurrence)
467
+ : fieldName;
468
+ return this;
469
+ }
470
+ // Transform field names to FMFIDs if using entity IDs
471
+ if (this.occurrence && orderBy) {
472
+ if (Array.isArray(orderBy)) {
473
+ // Check if it's a single tuple [field, direction] or array of tuples
474
+ if (
475
+ orderBy.length === 2 &&
476
+ (typeof orderBy[0] === "string" || isColumn(orderBy[0])) &&
477
+ (orderBy[1] === "asc" || orderBy[1] === "desc")
478
+ ) {
479
+ // Single tuple: [field, direction] or [column, direction]
480
+ const field = isColumn(orderBy[0])
481
+ ? orderBy[0].fieldName
482
+ : orderBy[0];
483
+ const direction = orderBy[1] as "asc" | "desc";
484
+ this.queryOptions.orderBy = `${transformOrderByField(field, this.occurrence)} ${direction}`;
485
+ } else {
486
+ // Array of tuples: [[field, dir], [field, dir], ...]
487
+ this.queryOptions.orderBy = (
488
+ orderBy as Array<[any, "asc" | "desc"]>
489
+ ).map(([fieldOrCol, direction]) => {
490
+ const field = isColumn(fieldOrCol)
491
+ ? fieldOrCol.fieldName
492
+ : String(fieldOrCol);
493
+ const transformedField = transformOrderByField(
494
+ field,
495
+ this.occurrence!,
496
+ );
497
+ return `${transformedField} ${direction}`;
498
+ });
499
+ }
500
+ } else {
501
+ // Single field name (string)
502
+ this.queryOptions.orderBy = transformOrderByField(
503
+ String(orderBy),
504
+ this.occurrence,
505
+ );
506
+ }
507
+ } else {
508
+ // No occurrence/baseTable - pass through as-is
509
+ if (Array.isArray(orderBy)) {
510
+ if (
511
+ orderBy.length === 2 &&
512
+ (typeof orderBy[0] === "string" || isColumn(orderBy[0])) &&
513
+ (orderBy[1] === "asc" || orderBy[1] === "desc")
514
+ ) {
515
+ // Single tuple: [field, direction] or [column, direction]
516
+ const field = isColumn(orderBy[0])
517
+ ? orderBy[0].fieldName
518
+ : orderBy[0];
519
+ const direction = orderBy[1] as "asc" | "desc";
520
+ this.queryOptions.orderBy = `${field} ${direction}`;
521
+ } else {
522
+ // Array of tuples
523
+ this.queryOptions.orderBy = (
524
+ orderBy as Array<[any, "asc" | "desc"]>
525
+ ).map(([fieldOrCol, direction]) => {
526
+ const field = isColumn(fieldOrCol)
527
+ ? fieldOrCol.fieldName
528
+ : String(fieldOrCol);
529
+ return `${field} ${direction}`;
530
+ });
531
+ }
532
+ } else {
533
+ this.queryOptions.orderBy = orderBy;
534
+ }
535
+ }
536
+ return this;
537
+ }
538
+
539
+ top(
540
+ count: number,
541
+ ): QueryBuilder<Occ, Selected, SingleMode, IsCount, Expands> {
542
+ this.queryOptions.top = count;
543
+ return this;
544
+ }
545
+
546
+ skip(
547
+ count: number,
548
+ ): QueryBuilder<Occ, Selected, SingleMode, IsCount, Expands> {
549
+ this.queryOptions.skip = count;
550
+ return this;
551
+ }
552
+
553
+ expand<TargetTable extends FMTable<any, any>>(
554
+ targetTable: ValidExpandTarget<Occ, TargetTable>,
555
+ callback?: (
556
+ builder: QueryBuilder<
557
+ TargetTable,
558
+ keyof InferSchemaOutputFromFMTable<TargetTable>,
559
+ false,
560
+ false
561
+ >,
562
+ ) => QueryBuilder<TargetTable, any, any, any, any>,
563
+ ): QueryBuilder<
564
+ Occ,
565
+ Selected,
566
+ SingleMode,
567
+ IsCount,
568
+ Expands & {
569
+ [K in ExtractTableName<TargetTable>]: {
570
+ schema: InferSchemaOutputFromFMTable<TargetTable>;
571
+ selected: keyof InferSchemaOutputFromFMTable<TargetTable>;
572
+ };
573
+ }
574
+ > {
575
+ // Use ExpandBuilder.processExpand to handle the expand logic
576
+ const expandConfig = this.expandBuilder.processExpand(
577
+ targetTable,
578
+ this.occurrence,
579
+ callback,
580
+ () =>
581
+ new QueryBuilder<TargetTable>({
582
+ occurrence: targetTable,
583
+ databaseName: this.databaseName,
584
+ context: this.context,
585
+ databaseUseEntityIds: this.databaseUseEntityIds,
586
+ }),
587
+ );
588
+
589
+ this.expandConfigs.push(expandConfig);
590
+ return this as any;
591
+ }
592
+
593
+ single(): QueryBuilder<Occ, Selected, "exact", IsCount, Expands> {
594
+ return this.cloneWithChanges({ singleMode: "exact" as const });
595
+ }
596
+
597
+ maybeSingle(): QueryBuilder<Occ, Selected, "maybe", IsCount, Expands> {
598
+ return this.cloneWithChanges({ singleMode: "maybe" as const });
599
+ }
600
+
601
+ count(): QueryBuilder<Occ, Selected, SingleMode, true, Expands> {
602
+ return this.cloneWithChanges({
603
+ isCountMode: true as const,
604
+ queryOptions: { count: true },
605
+ });
606
+ }
607
+
608
+ /**
609
+ * Builds the OData query string from current query options and expand configs.
610
+ */
611
+ private buildQueryString(): string {
612
+ // Build query without expand and select (we'll add them manually if using entity IDs)
613
+ const queryOptionsWithoutExpandAndSelect = { ...this.queryOptions };
614
+ const originalSelect = queryOptionsWithoutExpandAndSelect.select;
615
+ delete queryOptionsWithoutExpandAndSelect.expand;
616
+ delete queryOptionsWithoutExpandAndSelect.select;
617
+
618
+ let queryString = buildQuery(queryOptionsWithoutExpandAndSelect);
619
+
620
+ // Use shared helper for select/expand portion
621
+ const selectArray = originalSelect
622
+ ? Array.isArray(originalSelect)
623
+ ? originalSelect.map(String)
624
+ : [String(originalSelect)]
625
+ : undefined;
626
+
627
+ const selectExpandString = buildSelectExpandQueryString({
628
+ selectedFields: selectArray,
629
+ expandConfigs: this.expandConfigs,
630
+ table: this.occurrence,
631
+ useEntityIds: this.databaseUseEntityIds,
632
+ });
633
+
634
+ // Append select/expand to existing query string
635
+ if (selectExpandString) {
636
+ // Strip leading ? from helper result and append with appropriate separator
637
+ const params = selectExpandString.startsWith("?")
638
+ ? selectExpandString.slice(1)
639
+ : selectExpandString;
640
+ const separator = queryString.includes("?") ? "&" : "?";
641
+ queryString = `${queryString}${separator}${params}`;
642
+ }
643
+
644
+ return queryString;
645
+ }
646
+
647
+ async execute<EO extends ExecuteOptions>(
648
+ options?: RequestInit & FFetchOptions & EO,
649
+ ): Promise<
650
+ Result<
651
+ ConditionallyWithODataAnnotations<
652
+ QueryReturnType<
653
+ InferSchemaOutputFromFMTable<Occ>,
654
+ Selected,
655
+ SingleMode,
656
+ IsCount,
657
+ Expands
658
+ >,
659
+ EO["includeODataAnnotations"] extends true ? true : false
660
+ >
661
+ >
662
+ > {
663
+ const mergedOptions = this.mergeExecuteOptions(options);
664
+ const queryString = this.buildQueryString();
665
+
666
+ // Handle $count endpoint
667
+ if (this.isCountMode) {
668
+ const url = this.urlBuilder.build(queryString, {
669
+ isCount: true,
670
+ useEntityIds: mergedOptions.useEntityIds,
671
+ navigation: this.navigation,
672
+ });
673
+ const result = await this.context._makeRequest(url, mergedOptions);
674
+
675
+ if (result.error) {
676
+ return { data: undefined, error: result.error };
677
+ }
678
+
679
+ // OData returns count as a string, convert to number
680
+ const count =
681
+ typeof result.data === "string" ? Number(result.data) : result.data;
682
+ return { data: count as number, error: undefined } as any;
683
+ }
684
+
685
+ const url = this.urlBuilder.build(queryString, {
686
+ isCount: this.isCountMode,
687
+ useEntityIds: mergedOptions.useEntityIds,
688
+ navigation: this.navigation,
689
+ });
690
+
691
+ const result = await this.context._makeRequest(url, mergedOptions);
692
+
693
+ if (result.error) {
694
+ return { data: undefined, error: result.error };
695
+ }
696
+
697
+ return processQueryResponse(result.data, {
698
+ occurrence: this.occurrence,
699
+ singleMode: this.singleMode,
700
+ queryOptions: this.queryOptions as any,
701
+ expandConfigs: this.expandConfigs,
702
+ skipValidation: options?.skipValidation,
703
+ useEntityIds: mergedOptions.useEntityIds,
704
+ fieldMapping: this.fieldMapping,
705
+ });
706
+ }
707
+
708
+ getQueryString(): string {
709
+ const queryString = this.buildQueryString();
710
+ return this.urlBuilder.buildPath(queryString, {
711
+ useEntityIds: this.databaseUseEntityIds,
712
+ navigation: this.navigation,
713
+ });
714
+ }
715
+
716
+ getRequestConfig(): { method: string; url: string; body?: any } {
717
+ const queryString = this.buildQueryString();
718
+ const url = this.urlBuilder.build(queryString, {
719
+ isCount: this.isCountMode,
720
+ useEntityIds: this.databaseUseEntityIds,
721
+ navigation: this.navigation,
722
+ });
723
+
724
+ return {
725
+ method: "GET",
726
+ url,
727
+ };
728
+ }
729
+
730
+ toRequest(baseUrl: string, options?: ExecuteOptions): Request {
731
+ const config = this.getRequestConfig();
732
+ return createODataRequest(baseUrl, config, options);
733
+ }
734
+
735
+ async processResponse(
736
+ response: Response,
737
+ options?: ExecuteOptions,
738
+ ): Promise<
739
+ Result<
740
+ QueryReturnType<
741
+ InferSchemaOutputFromFMTable<Occ>,
742
+ Selected,
743
+ SingleMode,
744
+ IsCount,
745
+ Expands
746
+ >
747
+ >
748
+ > {
749
+ // Check for error responses (important for batch operations)
750
+ if (!response.ok) {
751
+ const error = await parseErrorResponse(
752
+ response,
753
+ response.url ||
754
+ `/${this.databaseName}/${getTableName(this.occurrence)}`,
755
+ );
756
+ return { data: undefined, error };
757
+ }
758
+
759
+ // Handle 204 No Content (shouldn't happen for queries, but handle it gracefully)
760
+ if (response.status === 204) {
761
+ // Return empty list for list queries, null for single queries
762
+ if (this.singleMode !== false) {
763
+ if (this.singleMode === "maybe") {
764
+ return { data: null as any, error: undefined };
765
+ }
766
+ return {
767
+ data: undefined,
768
+ error: new RecordCountMismatchError("one", 0),
769
+ };
770
+ }
771
+ return { data: [] as any, error: undefined };
772
+ }
773
+
774
+ // Parse the response body (using safeJsonParse to handle FileMaker's invalid JSON with unquoted ? values)
775
+ let rawData;
776
+ try {
777
+ rawData = await safeJsonParse(response);
778
+ } catch (err) {
779
+ // Check if it's an empty body error (common with 204 responses)
780
+ if (err instanceof SyntaxError && response.status === 204) {
781
+ // Handled above, but just in case
782
+ return { data: [] as any, error: undefined };
783
+ }
784
+ return {
785
+ data: undefined,
786
+ error: {
787
+ name: "ResponseParseError",
788
+ message: `Failed to parse response JSON: ${err instanceof Error ? err.message : "Unknown error"}`,
789
+ timestamp: new Date(),
790
+ } as any,
791
+ };
792
+ }
793
+
794
+ if (!rawData) {
795
+ return {
796
+ data: undefined,
797
+ error: {
798
+ name: "ResponseError",
799
+ message: "Response body was empty or null",
800
+ timestamp: new Date(),
801
+ } as any,
802
+ };
803
+ }
804
+
805
+ const mergedOptions = this.mergeExecuteOptions(options);
806
+ return processQueryResponse(rawData, {
807
+ occurrence: this.occurrence,
808
+ singleMode: this.singleMode,
809
+ queryOptions: this.queryOptions as any,
810
+ expandConfigs: this.expandConfigs,
811
+ skipValidation: options?.skipValidation,
812
+ useEntityIds: mergedOptions.useEntityIds,
813
+ fieldMapping: this.fieldMapping,
814
+ });
815
+ }
816
+ }