@burojs/hasura 0.2.0 → 0.4.0

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.
package/dist/index.cjs CHANGED
@@ -1,854 +1,915 @@
1
- 'use strict';
2
-
3
- var core = require('@burojs/core');
4
- var graphqlWs = require('graphql-ws');
5
-
6
- // src/data-provider.ts
7
-
8
- // src/endpoint.ts
9
- var DEFAULT_HASURA_ENDPOINT = "/gql/v1/graphql";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _burojs_core = require("@burojs/core");
3
+ let graphql_ws = require("graphql-ws");
4
+ //#region src/cursor.ts
5
+ const HASURA_CURSOR_CODES = Object.freeze({
6
+ unorderable: "cursor-unorderable",
7
+ backward: "cursor-backward-unsupported",
8
+ limit: "cursor-limit-invalid",
9
+ malformed: "cursor-malformed",
10
+ mismatch: "cursor-ordering-mismatch",
11
+ boundaryNull: "cursor-boundary-null"
12
+ });
13
+ const CURSOR_VERSION = 1;
14
+ function cursorError(code, kind, message) {
15
+ return {
16
+ kind,
17
+ code,
18
+ message
19
+ };
20
+ }
21
+ function orderingSignature(ordering) {
22
+ return ordering.map((column) => `${column.field}:${column.direction}`).join(",");
23
+ }
24
+ function effectiveCursorOrdering(sort, mapping) {
25
+ const pkField = mapping.pkField ?? "id";
26
+ const requested = (sort ?? []).filter((entry) => Boolean(entry.field));
27
+ const columns = requested.length > 0 ? requested.map((entry) => ({
28
+ field: entry.field,
29
+ direction: entry.direction
30
+ })) : [{
31
+ field: mapping.orderByField ?? pkField,
32
+ direction: "desc"
33
+ }];
34
+ if (columns.some((column) => column.field === pkField)) return columns;
35
+ const last = columns[columns.length - 1];
36
+ return [...columns, {
37
+ field: pkField,
38
+ direction: last?.direction ?? "asc"
39
+ }];
40
+ }
41
+ function assertCursorOrderable(ordering, sort, mapping) {
42
+ const nulled = (sort ?? []).find((entry) => entry.nulls !== void 0);
43
+ if (nulled !== void 0) throw cursorError(HASURA_CURSOR_CODES.unorderable, "capability", `@burojs/hasura cannot cursor-paginate '${mapping.table}' ordered by '${nulled.field}' with an explicit nulls placement: a keyset predicate over NULLs is not expressible here. Sort without \`nulls\`, or use offset pagination.`);
44
+ const selected = new Set(mapping.selectFields);
45
+ const missing = ordering.filter((column) => !selected.has(column.field));
46
+ if (missing.length > 0) throw cursorError(HASURA_CURSOR_CODES.unorderable, "capability", `@burojs/hasura cannot cursor-paginate '${mapping.table}': the ordering needs ${missing.map((column) => `'${column.field}'`).join(", ")}, which the mapping does not select, so no page can carry the value the next cursor is made of. Cursor pagination orders by the sort columns plus the primary key ('${ordering[ordering.length - 1]?.field ?? "id"}'), and every one of them must be in \`selectFields\`.`);
47
+ }
48
+ function assertCursorLimit(limit, table) {
49
+ if (typeof limit !== "number" || !Number.isInteger(limit) || limit <= 0) throw cursorError(HASURA_CURSOR_CODES.limit, "validation", `@burojs/hasura cursor pagination on '${table}' needs a positive integer \`limit\`, got ${JSON.stringify(limit)}.`);
50
+ }
51
+ function base64UrlEncode(text) {
52
+ const bytes = new TextEncoder().encode(text);
53
+ let binary = "";
54
+ for (const byte of bytes) binary += String.fromCharCode(byte);
55
+ return (typeof btoa === "function" ? btoa(binary) : Buffer.from(bytes).toString("base64")).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
56
+ }
57
+ function base64UrlDecode(text) {
58
+ const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
59
+ if (typeof atob === "function") {
60
+ const binary = atob(base64);
61
+ const bytes = new Uint8Array(binary.length);
62
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
63
+ return new TextDecoder().decode(bytes);
64
+ }
65
+ return Buffer.from(base64, "base64").toString("utf8");
66
+ }
67
+ function encodeCursor(ordering, row, table) {
68
+ const values = [];
69
+ for (const column of ordering) {
70
+ const value = row[column.field];
71
+ if (value === null || value === void 0) throw cursorError(HASURA_CURSOR_CODES.boundaryNull, "capability", `@burojs/hasura cannot mint a cursor for '${table}': the last row of the page has no value for the ordering column '${column.field}', and a keyset predicate over NULL matches nothing. Order by a non-null column, or use offset pagination.`);
72
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") throw cursorError(HASURA_CURSOR_CODES.boundaryNull, "capability", `@burojs/hasura cannot mint a cursor for '${table}': ordering column '${column.field}' holds ${typeof value}, which has no total order to seek on.`);
73
+ values.push(value);
74
+ }
75
+ const envelope = {
76
+ v: CURSOR_VERSION,
77
+ o: orderingSignature(ordering),
78
+ k: values
79
+ };
80
+ return base64UrlEncode(JSON.stringify(envelope));
81
+ }
82
+ function decodeCursor(raw, ordering, table) {
83
+ if (typeof raw !== "string" || raw.length === 0) throw cursorError(HASURA_CURSOR_CODES.malformed, "validation", `@burojs/hasura got a non-string cursor for '${table}': ${JSON.stringify(raw)}. A cursor is opaque — pass back exactly what \`pageInfo.nextCursor\` returned.`);
84
+ let envelope;
85
+ try {
86
+ envelope = JSON.parse(base64UrlDecode(raw));
87
+ } catch (cause) {
88
+ throw {
89
+ ...cursorError(HASURA_CURSOR_CODES.malformed, "validation", `@burojs/hasura could not decode the cursor for '${table}'. A cursor is opaque — pass back exactly what \`pageInfo.nextCursor\` returned.`),
90
+ cause
91
+ };
92
+ }
93
+ if (envelope === null || typeof envelope !== "object" || envelope.v !== CURSOR_VERSION || typeof envelope.o !== "string" || !Array.isArray(envelope.k)) throw cursorError(HASURA_CURSOR_CODES.malformed, "validation", `@burojs/hasura got a cursor for '${table}' it did not mint (envelope version ${String(envelope?.v)}).`);
94
+ const signature = orderingSignature(ordering);
95
+ if (envelope.o !== signature) throw cursorError(HASURA_CURSOR_CODES.mismatch, "validation", `@burojs/hasura refuses a cursor for '${table}' minted under ordering '${envelope.o}' against a request ordered '${signature}': the page it addressed no longer exists. Restart from the first page when the sort changes.`);
96
+ if (envelope.k.length !== ordering.length) throw cursorError(HASURA_CURSOR_CODES.malformed, "validation", `@burojs/hasura got a cursor for '${table}' carrying ${envelope.k.length} boundary values for ${ordering.length} ordering columns.`);
97
+ return envelope.k;
98
+ }
99
+ function keysetWhere(ordering, boundary, int64Fields) {
100
+ const int64 = new Set(int64Fields ?? []);
101
+ const value = (index, field) => {
102
+ const raw = boundary[index];
103
+ return int64.has(field) ? String(raw) : raw;
104
+ };
105
+ const branches = [];
106
+ for (let index = 0; index < ordering.length; index += 1) {
107
+ const column = ordering[index];
108
+ if (column === void 0) continue;
109
+ const strict = column.direction === "desc" ? "_lt" : "_gt";
110
+ const tail = { [column.field]: { [strict]: value(index, column.field) } };
111
+ if (index === 0) {
112
+ branches.push(tail);
113
+ continue;
114
+ }
115
+ const clauses = [];
116
+ for (let prior = 0; prior < index; prior += 1) {
117
+ const priorColumn = ordering[prior];
118
+ if (priorColumn === void 0) continue;
119
+ clauses.push({ [priorColumn.field]: { _eq: value(prior, priorColumn.field) } });
120
+ }
121
+ clauses.push(tail);
122
+ branches.push({ _and: clauses });
123
+ }
124
+ return { _or: branches };
125
+ }
126
+ //#endregion
127
+ //#region src/endpoint.ts
128
+ const DEFAULT_HASURA_ENDPOINT = "/gql/v1/graphql";
129
+ //#endregion
130
+ //#region src/live-provider.ts
10
131
  function hasuraWsUrl(endpoint) {
11
- if (typeof window === "undefined") return endpoint;
12
- const url = new URL(endpoint, window.location.origin);
13
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
14
- return url.toString();
132
+ if (typeof window === "undefined") return endpoint;
133
+ const url = new URL(endpoint, window.location.origin);
134
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
135
+ return url.toString();
15
136
  }
16
137
  function listSubscription(mapping) {
17
- const where = mapping.fixedFilter;
18
- return {
19
- query: where ? `subscription Live_${mapping.table}_list($where: ${mapping.table}_bool_exp) {
138
+ const where = mapping.fixedFilter;
139
+ return {
140
+ query: where ? `subscription Live_${mapping.table}_list($where: ${mapping.table}_bool_exp) {
20
141
  ${mapping.table}_aggregate(where: $where) { aggregate { count max { updated_at } } }
21
142
  }` : `subscription Live_${mapping.table}_list {
22
143
  ${mapping.table}_aggregate { aggregate { count max { updated_at } } }
23
144
  }`,
24
- ...where === void 0 ? {} : { variables: { where } }
25
- };
145
+ ...where === void 0 ? {} : { variables: { where } }
146
+ };
26
147
  }
27
148
  function oneSubscription(mapping, id) {
28
- const pkField = mapping.pkField ?? "id";
29
- const pkType = mapping.pkType ?? "bigint";
30
- const root = mapping.byPkRoot === false ? null : mapping.byPkRoot ?? `${mapping.table}_by_pk`;
31
- if (root === null) return null;
32
- return {
33
- query: `subscription Live_${mapping.table}_one($id: ${pkType}!) {
149
+ const pkField = mapping.pkField ?? "id";
150
+ const pkType = mapping.pkType ?? "bigint";
151
+ const root = mapping.byPkRoot === false ? null : mapping.byPkRoot ?? `${mapping.table}_by_pk`;
152
+ if (root === null) return null;
153
+ return {
154
+ query: `subscription Live_${mapping.table}_one($id: ${pkType}!) {
34
155
  ${root}(${pkField}: $id) { ${pkField} updated_at }
35
156
  }`,
36
- variables: { id }
37
- };
157
+ variables: { id }
158
+ };
38
159
  }
39
160
  function createHasuraLiveProvider(config) {
40
- const listeners = /* @__PURE__ */ new Set();
41
- const endpoint = config.endpoint ?? DEFAULT_HASURA_ENDPOINT;
42
- const role = config.role ?? null;
43
- let client;
44
- const status = (value) => {
45
- for (const listener of listeners) listener(value);
46
- };
47
- function getClient() {
48
- if (client !== void 0) return client;
49
- const options = {
50
- url: hasuraWsUrl(endpoint),
51
- lazy: true,
52
- keepAlive: 1e4,
53
- retryAttempts: Number.POSITIVE_INFINITY,
54
- shouldRetry: () => true,
55
- connectionParams: async () => {
56
- const token = await config.getToken();
57
- return {
58
- headers: {
59
- ...token ? { Authorization: `Bearer ${token}` } : {},
60
- ...role ? { "X-Hasura-Role": role } : {}
61
- }
62
- };
63
- },
64
- on: {
65
- connecting: () => status("connecting"),
66
- connected: () => status("connected"),
67
- closed: () => status("degraded")
68
- }
69
- };
70
- client = config.clientFactory?.(options) ?? graphqlWs.createClient(options);
71
- return client;
72
- }
73
- return {
74
- async open(descriptor, openContext) {
75
- if (openContext.signal.aborted) return null;
76
- const mapping = config.resources[descriptor.resource];
77
- if (mapping?.live !== true) return null;
78
- const payload = descriptor.kind === "list" ? listSubscription(mapping) : descriptor.kind === "one" ? oneSubscription(mapping, descriptor.id) : null;
79
- if (payload === null) return null;
80
- return {
81
- kind: "invalidate",
82
- initial: "query",
83
- subscribe(observer, subscribeContext) {
84
- if (openContext.signal.aborted || subscribeContext.signal.aborted) return () => void 0;
85
- let primed = false;
86
- let closed = false;
87
- let upstream = void 0;
88
- const close = () => {
89
- if (closed) return;
90
- closed = true;
91
- listeners.delete(onStatus);
92
- openContext.signal.removeEventListener("abort", close);
93
- subscribeContext.signal.removeEventListener("abort", close);
94
- upstream?.();
95
- };
96
- const onStatus = (value) => {
97
- if (!closed) observer.status(value);
98
- };
99
- const sink = {
100
- next: () => {
101
- if (closed) return;
102
- if (!primed) {
103
- primed = true;
104
- return;
105
- }
106
- observer.next(void 0);
107
- },
108
- error: (error) => {
109
- if (closed) return;
110
- observer.error(core.normalizeDataError(error));
111
- close();
112
- },
113
- complete: () => {
114
- if (!closed) observer.status("degraded");
115
- }
116
- };
117
- listeners.add(onStatus);
118
- openContext.signal.addEventListener("abort", close, { once: true });
119
- subscribeContext.signal.addEventListener("abort", close, { once: true });
120
- upstream = getClient().subscribe(payload, sink);
121
- if (closed) upstream();
122
- if (openContext.signal.aborted || subscribeContext.signal.aborted) close();
123
- return Promise.resolve(close);
124
- }
125
- };
126
- }
127
- };
161
+ const listeners = new Set();
162
+ const endpoint = config.endpoint ?? "/gql/v1/graphql";
163
+ const role = config.role ?? null;
164
+ let client;
165
+ const status = (value) => {
166
+ for (const listener of listeners) listener(value);
167
+ };
168
+ function getClient() {
169
+ if (client !== void 0) return client;
170
+ const options = {
171
+ url: hasuraWsUrl(endpoint),
172
+ lazy: true,
173
+ keepAlive: 1e4,
174
+ retryAttempts: Number.POSITIVE_INFINITY,
175
+ shouldRetry: () => true,
176
+ connectionParams: async () => {
177
+ const token = await config.getToken();
178
+ return { headers: {
179
+ ...token ? { Authorization: `Bearer ${token}` } : {},
180
+ ...role ? { "X-Hasura-Role": role } : {}
181
+ } };
182
+ },
183
+ on: {
184
+ connecting: () => status("connecting"),
185
+ connected: () => status("connected"),
186
+ closed: () => status("degraded")
187
+ }
188
+ };
189
+ client = config.clientFactory?.(options) ?? (0, graphql_ws.createClient)(options);
190
+ return client;
191
+ }
192
+ return {
193
+ declaredPushInvalidation() {
194
+ return Object.entries(config.resources).filter(([, mapping]) => mapping?.live === true).map(([resource]) => resource);
195
+ },
196
+ async open(descriptor, openContext) {
197
+ if (openContext.signal.aborted) return null;
198
+ const mapping = config.resources[descriptor.resource];
199
+ if (mapping?.live !== true) return null;
200
+ const payload = descriptor.kind === "list" ? listSubscription(mapping) : descriptor.kind === "one" ? oneSubscription(mapping, descriptor.id) : null;
201
+ if (payload === null) return null;
202
+ return {
203
+ kind: "invalidate",
204
+ initial: "query",
205
+ subscribe(observer, subscribeContext) {
206
+ if (openContext.signal.aborted || subscribeContext.signal.aborted) return () => void 0;
207
+ let primed = false;
208
+ let closed = false;
209
+ let upstream = void 0;
210
+ const close = () => {
211
+ if (closed) return;
212
+ closed = true;
213
+ listeners.delete(onStatus);
214
+ openContext.signal.removeEventListener("abort", close);
215
+ subscribeContext.signal.removeEventListener("abort", close);
216
+ upstream?.();
217
+ };
218
+ const onStatus = (value) => {
219
+ if (!closed) observer.status(value);
220
+ };
221
+ const sink = {
222
+ next: () => {
223
+ if (closed) return;
224
+ if (!primed) {
225
+ primed = true;
226
+ return;
227
+ }
228
+ observer.next(void 0);
229
+ },
230
+ error: (error) => {
231
+ if (closed) return;
232
+ observer.error((0, _burojs_core.normalizeDataError)(error));
233
+ close();
234
+ },
235
+ complete: () => {
236
+ if (!closed) observer.status("degraded");
237
+ }
238
+ };
239
+ listeners.add(onStatus);
240
+ openContext.signal.addEventListener("abort", close, { once: true });
241
+ subscribeContext.signal.addEventListener("abort", close, { once: true });
242
+ upstream = getClient().subscribe(payload, sink);
243
+ if (closed) upstream();
244
+ if (openContext.signal.aborted || subscribeContext.signal.aborted) close();
245
+ return Promise.resolve(close);
246
+ }
247
+ };
248
+ }
249
+ };
128
250
  }
129
-
130
- // src/data-provider.ts
251
+ //#endregion
252
+ //#region src/data-provider.ts
131
253
  function setNestedPath(obj, path, value) {
132
- const parts = path.split(".");
133
- const leaf = parts.pop();
134
- if (leaf === void 0) return;
135
- let cur = obj;
136
- for (const p of parts) {
137
- const next = cur[p];
138
- if (typeof next !== "object" || next === null) cur[p] = {};
139
- cur = cur[p];
140
- }
141
- cur[leaf] = value;
254
+ const parts = path.split(".");
255
+ const leaf = parts.pop();
256
+ if (leaf === void 0) return;
257
+ let cur = obj;
258
+ for (const p of parts) {
259
+ const next = cur[p];
260
+ if (typeof next !== "object" || next === null) cur[p] = {};
261
+ cur = cur[p];
262
+ }
263
+ cur[leaf] = value;
142
264
  }
143
265
  function getNestedPath(obj, path) {
144
- let cur = obj;
145
- for (const p of path.split(".")) {
146
- if (cur == null || typeof cur !== "object") return void 0;
147
- cur = cur[p];
148
- }
149
- return cur;
266
+ let cur = obj;
267
+ for (const p of path.split(".")) {
268
+ if (cur == null || typeof cur !== "object") return void 0;
269
+ cur = cur[p];
270
+ }
271
+ return cur;
150
272
  }
151
273
  function partitionDataBody(values, cfg) {
152
- const keySet = new Set(cfg.keys);
153
- const dataBody = {};
154
- const rest = {};
155
- let hasDataBody = false;
156
- for (const [key, value] of Object.entries(values)) {
157
- if (key === cfg.relationship) continue;
158
- if (keySet.has(key)) {
159
- if (value !== void 0) {
160
- dataBody[key] = value;
161
- hasDataBody = true;
162
- }
163
- } else {
164
- rest[key] = value;
165
- }
166
- }
167
- return { dataBody, rest, hasDataBody };
274
+ const keySet = new Set(cfg.keys);
275
+ const dataBody = {};
276
+ const rest = {};
277
+ let hasDataBody = false;
278
+ for (const [key, value] of Object.entries(values)) {
279
+ if (key === cfg.relationship) continue;
280
+ if (keySet.has(key)) {
281
+ if (value !== void 0) {
282
+ dataBody[key] = value;
283
+ hasDataBody = true;
284
+ }
285
+ } else rest[key] = value;
286
+ }
287
+ return {
288
+ dataBody,
289
+ rest,
290
+ hasDataBody
291
+ };
168
292
  }
169
293
  function partitionJsonbSpill(values, spill, baseColumns) {
170
- const baseSet = new Set(baseColumns);
171
- const metaSet = new Set(spill.metaKeys);
172
- const nestedKeys = spill.nestedKeys ?? {};
173
- const base = {};
174
- const headExplicit = {};
175
- const metaExplicit = {};
176
- const headSpill = {};
177
- const metaSpill = {};
178
- const nestedSpill = [];
179
- for (const [key, value] of Object.entries(values)) {
180
- if (value === void 0) continue;
181
- const nestedPath = nestedKeys[key];
182
- if (key === spill.column) {
183
- if (value && typeof value === "object")
184
- Object.assign(headExplicit, value);
185
- } else if (key === spill.metaColumn) {
186
- if (value && typeof value === "object")
187
- Object.assign(metaExplicit, value);
188
- } else if (metaSet.has(key)) {
189
- metaSpill[key] = value;
190
- } else if (nestedPath) {
191
- nestedSpill.push([nestedPath, value]);
192
- } else if (baseSet.has(key)) {
193
- base[key] = value;
194
- } else {
195
- headSpill[key] = value;
196
- }
197
- }
198
- const head = { ...headExplicit, ...headSpill };
199
- for (const [path, value] of nestedSpill) setNestedPath(head, path, value);
200
- const meta = { ...metaExplicit, ...metaSpill };
201
- const out = { ...base };
202
- if (Object.keys(head).length > 0) out[spill.column] = head;
203
- if (Object.keys(meta).length > 0) out[spill.metaColumn] = meta;
204
- return out;
294
+ const baseSet = new Set(baseColumns);
295
+ const metaSet = new Set(spill.metaKeys);
296
+ const nestedKeys = spill.nestedKeys ?? {};
297
+ const base = {};
298
+ const headExplicit = {};
299
+ const metaExplicit = {};
300
+ const headSpill = {};
301
+ const metaSpill = {};
302
+ const nestedSpill = [];
303
+ for (const [key, value] of Object.entries(values)) {
304
+ if (value === void 0) continue;
305
+ const nestedPath = nestedKeys[key];
306
+ if (key === spill.column) {
307
+ if (value && typeof value === "object") Object.assign(headExplicit, value);
308
+ } else if (key === spill.metaColumn) {
309
+ if (value && typeof value === "object") Object.assign(metaExplicit, value);
310
+ } else if (metaSet.has(key)) metaSpill[key] = value;
311
+ else if (nestedPath) nestedSpill.push([nestedPath, value]);
312
+ else if (baseSet.has(key)) base[key] = value;
313
+ else headSpill[key] = value;
314
+ }
315
+ const head = {
316
+ ...headExplicit,
317
+ ...headSpill
318
+ };
319
+ for (const [path, value] of nestedSpill) setNestedPath(head, path, value);
320
+ const meta = {
321
+ ...metaExplicit,
322
+ ...metaSpill
323
+ };
324
+ const out = { ...base };
325
+ if (Object.keys(head).length > 0) out[spill.column] = head;
326
+ if (Object.keys(meta).length > 0) out[spill.metaColumn] = meta;
327
+ return out;
205
328
  }
206
329
  function flattenJsonbSpill(item, spill) {
207
- if (!item || typeof item !== "object") return item;
208
- const rec = item;
209
- const headObj = rec[spill.column];
210
- const metaObj = rec[spill.metaColumn];
211
- const out = {
212
- ...headObj && typeof headObj === "object" ? headObj : {},
213
- ...metaObj && typeof metaObj === "object" ? metaObj : {},
214
- ...rec
215
- };
216
- if (spill.nestedKeys && headObj && typeof headObj === "object") {
217
- for (const [flatKey, path] of Object.entries(spill.nestedKeys)) {
218
- const v = getNestedPath(headObj, path);
219
- if (v !== void 0) out[flatKey] = v;
220
- }
221
- }
222
- return out;
223
- }
224
- var NOT_AUTHENTICATED_CODE = "not-authenticated";
225
- var OP_MAP = {
226
- eq: "_eq",
227
- neq: "_neq",
228
- ne: "_neq",
229
- lt: "_lt",
230
- lte: "_lte",
231
- gt: "_gt",
232
- gte: "_gte",
233
- in: "_in",
234
- notIn: "_nin",
235
- nin: "_nin",
236
- contains: "_ilike",
237
- containss: "_like",
238
- startsWith: "_ilike",
239
- endsWith: "_ilike",
240
- startswith: "_ilike",
241
- endswith: "_ilike",
242
- null: "_is_null"
330
+ if (!item || typeof item !== "object") return item;
331
+ const rec = item;
332
+ const headObj = rec[spill.column];
333
+ const metaObj = rec[spill.metaColumn];
334
+ const out = {
335
+ ...headObj && typeof headObj === "object" ? headObj : {},
336
+ ...metaObj && typeof metaObj === "object" ? metaObj : {},
337
+ ...rec
338
+ };
339
+ if (spill.nestedKeys && headObj && typeof headObj === "object") for (const [flatKey, path] of Object.entries(spill.nestedKeys)) {
340
+ const v = getNestedPath(headObj, path);
341
+ if (v !== void 0) out[flatKey] = v;
342
+ }
343
+ return out;
344
+ }
345
+ const NOT_AUTHENTICATED_CODE = "not-authenticated";
346
+ const LOCALE_REQUIRED_CODE = "locale-required";
347
+ function localeWhere(m, locale) {
348
+ if (m.localeField === void 0) return void 0;
349
+ if (typeof locale !== "string" || locale.length === 0) throw {
350
+ kind: "capability",
351
+ code: LOCALE_REQUIRED_CODE,
352
+ message: `@burojs/hasura: '${m.table}' maps a localeField ('${m.localeField}') but this read carries no locale. Declare \`data: { localeVarying: true }\` on the resource so @burojs/core puts the active locale on the descriptor, or drop the localeField. Serving the request anyway would return every language's rows at once.`
353
+ };
354
+ return { [m.localeField]: { _eq: locale } };
355
+ }
356
+ const OP_MAP = {
357
+ eq: "_eq",
358
+ neq: "_neq",
359
+ ne: "_neq",
360
+ lt: "_lt",
361
+ lte: "_lte",
362
+ gt: "_gt",
363
+ gte: "_gte",
364
+ in: "_in",
365
+ notIn: "_nin",
366
+ nin: "_nin",
367
+ contains: "_ilike",
368
+ containss: "_like",
369
+ startsWith: "_ilike",
370
+ endsWith: "_ilike",
371
+ startswith: "_ilike",
372
+ endswith: "_ilike",
373
+ null: "_is_null"
243
374
  };
244
- var FILTER_OPERATOR_UNSUPPORTED_CODE = "filter-operator-unsupported";
245
- var UNEXPRESSIBLE_OPS = {
246
- has: "a collection-membership test",
247
- hasAny: "a collection-membership test",
248
- hasAll: "a collection-membership test"
375
+ const FILTER_OPERATOR_UNSUPPORTED_CODE = "filter-operator-unsupported";
376
+ const UNEXPRESSIBLE_OPS = {
377
+ has: "a collection-membership test",
378
+ hasAny: "a collection-membership test",
379
+ hasAll: "a collection-membership test"
249
380
  };
250
381
  function unsupportedOperator(field, op) {
251
- const why = UNEXPRESSIBLE_OPS[op];
252
- return {
253
- kind: "capability",
254
- code: FILTER_OPERATOR_UNSUPPORTED_CODE,
255
- message: why ? `@burojs/hasura cannot express the '${op}' filter operator on '${field}': ${why}, whose Hasura encoding depends on whether the column is jsonb or a Postgres array \u2014 something no ResourceMapping field declares. Declare it and translate explicitly, or filter on a scalar column.` : `@burojs/hasura does not support the filter operator '${op}' (on '${field}').`
256
- };
382
+ const why = UNEXPRESSIBLE_OPS[op];
383
+ return {
384
+ kind: "capability",
385
+ code: FILTER_OPERATOR_UNSUPPORTED_CODE,
386
+ message: why ? `@burojs/hasura cannot express the '${op}' filter operator on '${field}': ${why}, whose Hasura encoding depends on whether the column is jsonb or a Postgres array — something no ResourceMapping field declares. Declare it and translate explicitly, or filter on a scalar column.` : `@burojs/hasura does not support the filter operator '${op}' (on '${field}').`
387
+ };
257
388
  }
258
389
  function scopeToWhere(scope, scopeFields) {
259
- const clauses = [];
260
- for (const key of scopeFields) {
261
- const v = scope[key];
262
- if (v == null || v === "") continue;
263
- clauses.push({ [key]: { _eq: v } });
264
- }
265
- if (clauses.length === 0) return void 0;
266
- if (clauses.length === 1) return clauses[0];
267
- return { _and: clauses };
390
+ const clauses = [];
391
+ for (const key of scopeFields) {
392
+ const v = scope[key];
393
+ if (v == null || v === "") continue;
394
+ clauses.push({ [key]: { _eq: v } });
395
+ }
396
+ if (clauses.length === 0) return void 0;
397
+ if (clauses.length === 1) return clauses[0];
398
+ return { _and: clauses };
268
399
  }
269
400
  function mergeWhere(a, b) {
270
- if (!a) return b;
271
- if (!b) return a;
272
- return { _and: [a, b] };
401
+ if (!a) return b;
402
+ if (!b) return a;
403
+ return { _and: [a, b] };
404
+ }
405
+ function atFieldPath(field, predicate) {
406
+ const parts = field.split(".");
407
+ let out = predicate;
408
+ for (let i = parts.length - 1; i >= 0; i -= 1) out = { [parts[i]]: out };
409
+ return out;
273
410
  }
274
411
  function filtersToWhere(filter) {
275
- if (!filter || typeof filter !== "object") return void 0;
276
- if ("and" in filter) {
277
- if (filter.and.length === 0) return { _and: [] };
278
- const clauses = filter.and.map(filtersToWhere).filter((item) => item !== void 0);
279
- if (clauses.length === 0) return void 0;
280
- return clauses.length === 1 ? clauses[0] : { _and: clauses };
281
- }
282
- if ("or" in filter) {
283
- if (filter.or.length === 0) return { _or: [] };
284
- const clauses = filter.or.map(filtersToWhere).filter((item) => item !== void 0);
285
- if (clauses.length === 0) return void 0;
286
- return clauses.length === 1 ? clauses[0] : { _or: clauses };
287
- }
288
- if ("not" in filter) {
289
- const clause = filtersToWhere(filter.not);
290
- return clause === void 0 ? void 0 : { _not: clause };
291
- }
292
- if (!("field" in filter) || typeof filter.field !== "string" || !("op" in filter))
293
- return void 0;
294
- const { field, op } = filter;
295
- if (op === "isNull") return { [field]: { _is_null: true } };
296
- if (op === "isNotNull") return { [field]: { _is_null: false } };
297
- if (!("value" in filter) || filter.value === void 0) return void 0;
298
- const operator = OP_MAP[op];
299
- if (operator === void 0) throw unsupportedOperator(field, op);
300
- let value = filter.value;
301
- if (operator === "_ilike" || operator === "_like") {
302
- const text = String(value);
303
- value = op === "startsWith" ? `${text}%` : op === "endsWith" ? `%${text}` : `%${text}%`;
304
- }
305
- return { [field]: { [operator]: value } };
412
+ if (!filter || typeof filter !== "object") return void 0;
413
+ if ("and" in filter) {
414
+ if (filter.and.length === 0) return { _and: [] };
415
+ const clauses = filter.and.map(filtersToWhere).filter((item) => item !== void 0);
416
+ if (clauses.length === 0) return void 0;
417
+ return clauses.length === 1 ? clauses[0] : { _and: clauses };
418
+ }
419
+ if ("or" in filter) {
420
+ if (filter.or.length === 0) return { _or: [] };
421
+ const clauses = filter.or.map(filtersToWhere).filter((item) => item !== void 0);
422
+ if (clauses.length === 0) return void 0;
423
+ return clauses.length === 1 ? clauses[0] : { _or: clauses };
424
+ }
425
+ if ("not" in filter) {
426
+ const clause = filtersToWhere(filter.not);
427
+ return clause === void 0 ? void 0 : { _not: clause };
428
+ }
429
+ if (!("field" in filter) || typeof filter.field !== "string" || !("op" in filter)) return void 0;
430
+ const { field, op } = filter;
431
+ if (op === "isNull") return atFieldPath(field, { _is_null: true });
432
+ if (op === "isNotNull") return atFieldPath(field, { _is_null: false });
433
+ if (!("value" in filter) || filter.value === void 0) return void 0;
434
+ const operator = OP_MAP[op];
435
+ if (operator === void 0) throw unsupportedOperator(field, op);
436
+ let value = filter.value;
437
+ if (operator === "_ilike" || operator === "_like") {
438
+ const text = String(value);
439
+ value = op === "startsWith" ? `${text}%` : op === "endsWith" ? `%${text}` : `%${text}%`;
440
+ }
441
+ return atFieldPath(field, { [operator]: value });
306
442
  }
307
443
  function coerceInt64Filter(filter, fields) {
308
- if (!filter || !fields?.length) return filter;
309
- if ("and" in filter)
310
- return {
311
- and: filter.and.map(
312
- (entry) => coerceInt64Filter(entry, fields)
313
- )
314
- };
315
- if ("or" in filter)
316
- return {
317
- or: filter.or.map(
318
- (entry) => coerceInt64Filter(entry, fields)
319
- )
320
- };
321
- if ("not" in filter)
322
- return { not: coerceInt64Filter(filter.not, fields) };
323
- if ("field" in filter && fields.includes(filter.field) && "value" in filter && filter.value != null) {
324
- const value = Array.isArray(filter.value) ? filter.value.map(String) : String(filter.value);
325
- return { ...filter, value };
326
- }
327
- return filter;
444
+ if (!filter || !fields?.length) return filter;
445
+ if ("and" in filter) return { and: filter.and.map((entry) => coerceInt64Filter(entry, fields)) };
446
+ if ("or" in filter) return { or: filter.or.map((entry) => coerceInt64Filter(entry, fields)) };
447
+ if ("not" in filter) return { not: coerceInt64Filter(filter.not, fields) };
448
+ if ("field" in filter && fields.includes(filter.field) && "value" in filter && filter.value != null) {
449
+ const value = Array.isArray(filter.value) ? filter.value.map(String) : String(filter.value);
450
+ return {
451
+ ...filter,
452
+ value
453
+ };
454
+ }
455
+ return filter;
328
456
  }
329
457
  function hasuraError(error, signal, fallback) {
330
- if (core.isDataError(error)) return error;
331
- if (signal.aborted)
332
- return {
333
- kind: "cancelled",
334
- code: "request-aborted",
335
- message: "Hasura request was aborted.",
336
- cause: error
337
- };
338
- return {
339
- kind: "transport",
340
- code: "hasura-request-failed",
341
- message: error instanceof Error && error.message ? error.message : fallback,
342
- cause: error
343
- };
458
+ if ((0, _burojs_core.isDataError)(error)) return error;
459
+ if (signal.aborted) return {
460
+ kind: "cancelled",
461
+ code: "request-aborted",
462
+ message: "Hasura request was aborted.",
463
+ cause: error
464
+ };
465
+ return {
466
+ kind: "transport",
467
+ code: "hasura-request-failed",
468
+ message: error instanceof Error && error.message ? error.message : fallback,
469
+ cause: error
470
+ };
344
471
  }
345
472
  function aggregateRoot(m) {
346
- if (m.aggregate === false) return null;
347
- return typeof m.aggregate === "string" ? m.aggregate : `${m.table}_aggregate`;
473
+ if (m.aggregate === false) return null;
474
+ return typeof m.aggregate === "string" ? m.aggregate : `${m.table}_aggregate`;
348
475
  }
349
476
  function byPkRoot(m) {
350
- if (m.byPkRoot === false) return null;
351
- return m.byPkRoot ?? `${m.table}_by_pk`;
477
+ if (m.byPkRoot === false) return null;
478
+ return m.byPkRoot ?? `${m.table}_by_pk`;
352
479
  }
353
480
  function snapshotOperationRegistry(source) {
354
- if (source === void 0) return Object.freeze({});
355
- const resources = {};
356
- for (const [resource, operations] of Object.entries(source)) {
357
- const entries = {};
358
- for (const [name, operation] of Object.entries(operations)) {
359
- entries[name] = Object.freeze({ ...operation });
360
- }
361
- resources[resource] = Object.freeze(entries);
362
- }
363
- return Object.freeze(resources);
481
+ if (source === void 0) return Object.freeze({});
482
+ const resources = {};
483
+ for (const [resource, operations] of Object.entries(source)) {
484
+ const entries = {};
485
+ for (const [name, operation] of Object.entries(operations)) entries[name] = Object.freeze({ ...operation });
486
+ resources[resource] = Object.freeze(entries);
487
+ }
488
+ return Object.freeze(resources);
364
489
  }
365
490
  function hasRegisteredOperationKind(operations, kind) {
366
- return Object.values(operations).some(
367
- (byName) => Object.values(byName).some((operation) => operation.kind === kind)
368
- );
491
+ return Object.values(operations).some((byName) => Object.values(byName).some((operation) => operation.kind === kind));
369
492
  }
370
493
  function normalizeRole(role) {
371
- return role === void 0 || role === null || role === "" ? null : role;
494
+ return role === void 0 || role === null || role === "" ? null : role;
372
495
  }
373
496
  function createHasuraDataProvider(config) {
374
- const endpoint = config.endpoint ?? DEFAULT_HASURA_ENDPOINT;
375
- const defaultRole = normalizeRole(config.defaultRole);
376
- const operations = snapshotOperationRegistry(config.operations);
377
- const hasCustomQueries = hasRegisteredOperationKind(operations, "query");
378
- const hasCustomMutations = hasRegisteredOperationKind(operations, "mutation");
379
- async function gql(query, variables, role, signal) {
380
- try {
381
- const request = async (token2) => {
382
- const headers = {
383
- "Content-Type": "application/json",
384
- Authorization: `Bearer ${token2}`
385
- };
386
- const effectiveRole = role === void 0 ? defaultRole : normalizeRole(role);
387
- if (effectiveRole !== null) headers["X-Hasura-Role"] = effectiveRole;
388
- const fetchImpl = config.fetchImpl ?? fetch;
389
- return fetchImpl(endpoint, {
390
- method: "POST",
391
- headers,
392
- body: JSON.stringify({ query, variables }),
393
- signal
394
- });
395
- };
396
- let token = await config.getToken();
397
- if (!token)
398
- throw {
399
- kind: "auth",
400
- code: NOT_AUTHENTICATED_CODE,
401
- message: "Not authenticated."
402
- };
403
- let res = await request(token);
404
- if (res.status === 401 && config.recoverAuth && await config.recoverAuth()) {
405
- token = await config.getToken();
406
- if (!token)
407
- throw {
408
- kind: "auth",
409
- code: NOT_AUTHENTICATED_CODE,
410
- message: "Not authenticated."
411
- };
412
- res = await request(token);
413
- }
414
- if (!res.ok)
415
- throw {
416
- kind: "transport",
417
- code: "graphql-http-error",
418
- message: `GraphQL HTTP ${res.status}`,
419
- status: res.status
420
- };
421
- const body = await res.json();
422
- if (body.errors?.length)
423
- throw {
424
- kind: "protocol",
425
- code: "graphql-error",
426
- message: body.errors.map((e) => e.message).join("; "),
427
- details: body.errors
428
- };
429
- if (body.data === void 0)
430
- throw {
431
- kind: "protocol",
432
- code: "empty-graphql-response",
433
- message: "Empty GraphQL response."
434
- };
435
- return body.data;
436
- } catch (error) {
437
- throw hasuraError(error, signal, "Hasura request failed.");
438
- }
439
- }
440
- function mapping(resource) {
441
- const m = config.resources[resource];
442
- if (!m)
443
- throw {
444
- kind: "configuration",
445
- code: "unknown-resource",
446
- message: `Unknown resource: ${resource}`
447
- };
448
- return m;
449
- }
450
- function registeredOperation(resource, operation, kind) {
451
- const registered = operations[resource]?.[operation];
452
- if (registered === void 0 || registered.kind !== kind) {
453
- throw {
454
- kind: "capability",
455
- code: "hasura-custom-operation-unsupported",
456
- message: `Hasura ${kind} operation '${operation}' is not declared for '${resource}'.`
457
- };
458
- }
459
- return registered;
460
- }
461
- async function executeCustomOperation(resource, operationName, input, kind, signal) {
462
- const operation = registeredOperation(resource, operationName, kind);
463
- const result = await gql(
464
- operation.document,
465
- operation.variables(input),
466
- operation.role ?? config.resources[resource]?.role,
467
- signal
468
- );
469
- return operation.mapResult?.(result) ?? result;
470
- }
471
- function composeListWhere(m, descriptor, context) {
472
- const userWhere = filtersToWhere(coerceInt64Filter(descriptor.filter, m.int64Fields));
473
- const ignoreScope = descriptor.providerOptions?.ignoreScope === true;
474
- const sessionScope = context.session.scopeKey !== null && typeof context.session.scopeKey === "object" && !Array.isArray(context.session.scopeKey) ? context.session.scopeKey : {};
475
- const scope = ignoreScope ? {} : { ...sessionScope, ...config.getScope?.(context) ?? {} };
476
- const scopeWhere = scopeToWhere(scope, m.scopeFields ?? []);
477
- return mergeWhere(mergeWhere(userWhere, scopeWhere), m.fixedFilter);
478
- }
479
- async function runAggregateCount(m, root, where, signal) {
480
- const aggWhereArg = where ? "($where: " + m.table + "_bool_exp)" : "";
481
- const aggWhereParam = where ? "(where: $where)" : "";
482
- const metaQuery = `query Count_${m.table} ${aggWhereArg} {
497
+ const endpoint = config.endpoint ?? "/gql/v1/graphql";
498
+ const defaultRole = normalizeRole(config.defaultRole);
499
+ const operations = snapshotOperationRegistry(config.operations);
500
+ const hasCustomQueries = hasRegisteredOperationKind(operations, "query");
501
+ const hasCustomMutations = hasRegisteredOperationKind(operations, "mutation");
502
+ async function gql(query, variables, role, signal) {
503
+ try {
504
+ const request = async (token) => {
505
+ const headers = {
506
+ "Content-Type": "application/json",
507
+ Authorization: `Bearer ${token}`
508
+ };
509
+ const effectiveRole = role === void 0 ? defaultRole : normalizeRole(role);
510
+ if (effectiveRole !== null) headers["X-Hasura-Role"] = effectiveRole;
511
+ return (config.fetchImpl ?? fetch)(endpoint, {
512
+ method: "POST",
513
+ headers,
514
+ body: JSON.stringify({
515
+ query,
516
+ variables
517
+ }),
518
+ signal
519
+ });
520
+ };
521
+ let token = await config.getToken();
522
+ if (!token) throw {
523
+ kind: "auth",
524
+ code: NOT_AUTHENTICATED_CODE,
525
+ message: "Not authenticated."
526
+ };
527
+ let res = await request(token);
528
+ if (res.status === 401 && config.recoverAuth && await config.recoverAuth()) {
529
+ token = await config.getToken();
530
+ if (!token) throw {
531
+ kind: "auth",
532
+ code: NOT_AUTHENTICATED_CODE,
533
+ message: "Not authenticated."
534
+ };
535
+ res = await request(token);
536
+ }
537
+ if (!res.ok) throw {
538
+ kind: "transport",
539
+ code: "graphql-http-error",
540
+ message: `GraphQL HTTP ${res.status}`,
541
+ status: res.status
542
+ };
543
+ const body = await res.json();
544
+ if (body.errors?.length) throw {
545
+ kind: "protocol",
546
+ code: "graphql-error",
547
+ message: body.errors.map((e) => e.message).join("; "),
548
+ details: body.errors
549
+ };
550
+ if (body.data === void 0) throw {
551
+ kind: "protocol",
552
+ code: "empty-graphql-response",
553
+ message: "Empty GraphQL response."
554
+ };
555
+ return body.data;
556
+ } catch (error) {
557
+ throw hasuraError(error, signal, "Hasura request failed.");
558
+ }
559
+ }
560
+ function mapping(resource) {
561
+ const m = config.resources[resource];
562
+ if (!m) throw {
563
+ kind: "configuration",
564
+ code: "unknown-resource",
565
+ message: `Unknown resource: ${resource}`
566
+ };
567
+ return m;
568
+ }
569
+ function registeredOperation(resource, operation, kind) {
570
+ const registered = operations[resource]?.[operation];
571
+ if (registered === void 0 || registered.kind !== kind) throw {
572
+ kind: "capability",
573
+ code: "hasura-custom-operation-unsupported",
574
+ message: `Hasura ${kind} operation '${operation}' is not declared for '${resource}'.`
575
+ };
576
+ return registered;
577
+ }
578
+ async function executeCustomOperation(resource, operationName, input, kind, signal) {
579
+ const operation = registeredOperation(resource, operationName, kind);
580
+ const result = await gql(operation.document, operation.variables(input), operation.role ?? config.resources[resource]?.role, signal);
581
+ return operation.mapResult?.(result) ?? result;
582
+ }
583
+ function composeListWhere(m, descriptor, context) {
584
+ const userWhere = filtersToWhere(coerceInt64Filter(descriptor.filter, m.int64Fields));
585
+ const ignoreScope = descriptor.providerOptions?.ignoreScope === true;
586
+ const sessionScope = context.session.scopeKey !== null && typeof context.session.scopeKey === "object" && !Array.isArray(context.session.scopeKey) ? context.session.scopeKey : {};
587
+ return mergeWhere(mergeWhere(mergeWhere(userWhere, scopeToWhere(ignoreScope ? {} : {
588
+ ...sessionScope,
589
+ ...config.getScope?.(context) ?? {}
590
+ }, m.scopeFields ?? [])), m.fixedFilter), localeWhere(m, descriptor.locale));
591
+ }
592
+ async function runAggregateCount(m, root, where, signal) {
593
+ const aggWhereArg = where ? `($where: ${m.table}_bool_exp)` : "";
594
+ const aggWhereParam = where ? "(where: $where)" : "";
595
+ const metaQuery = `query Count_${m.table} ${aggWhereArg} {
483
596
  meta: ${root} ${aggWhereParam} { aggregate { count } }
484
597
  }`;
485
- const aggVars = {};
486
- if (where) aggVars["where"] = where;
487
- const metaData = await gql(
488
- metaQuery,
489
- where ? aggVars : void 0,
490
- m.role,
491
- signal
492
- );
493
- return metaData.meta.aggregate.count;
494
- }
495
- async function upsertDataBody(db, parentId, body, role, signal) {
496
- const mutation = `mutation UpsertDataBody($object: ${db.table}_insert_input!) {
598
+ const aggVars = {};
599
+ if (where) aggVars.where = where;
600
+ return (await gql(metaQuery, where ? aggVars : void 0, m.role, signal)).meta.aggregate.count;
601
+ }
602
+ async function upsertDataBody(db, parentId, body, role, signal) {
603
+ await gql(`mutation UpsertDataBody($object: ${db.table}_insert_input!) {
497
604
  result: insert_${db.table}_one(
498
605
  object: $object,
499
606
  on_conflict: { constraint: ${db.constraint}, update_columns: [${db.column}] }
500
607
  ) { ${db.fk} }
501
- }`;
502
- await gql(mutation, { object: { [db.fk]: parentId, [db.column]: body } }, role, signal);
503
- }
504
- function mutationRecord(m, idField, item, resource, expectedId) {
505
- if (item === null || typeof item !== "object" || Array.isArray(item)) {
506
- throw {
507
- kind: "protocol",
508
- code: "record-not-found",
509
- message: `Not found: ${resource}`
510
- };
511
- }
512
- const record = item;
513
- const id = record[m.pkField ?? idField];
514
- if (typeof id !== "string" && (typeof id !== "number" || !Number.isFinite(id))) {
515
- throw {
516
- kind: "protocol",
517
- code: "mutation-record-id-missing",
518
- message: `Mutation for '${resource}' returned no valid '${m.pkField ?? idField}'.`
519
- };
520
- }
521
- if (expectedId !== void 0 && id !== expectedId) {
522
- throw {
523
- kind: "protocol",
524
- code: "unexpected-record-id",
525
- message: `Mutation for '${resource}' returned '${String(id)}' instead of '${String(expectedId)}'.`
526
- };
527
- }
528
- return { kind: "record", id, record: item, completeness: "partial" };
529
- }
530
- async function readMutationRecord(m, id, signal) {
531
- const fields = m.selectFields.join(" ");
532
- const pkType = m.pkType ?? "bigint";
533
- const pkField = m.pkField ?? "id";
534
- const root = byPkRoot(m);
535
- if (m.fixedFilter || root === null) {
536
- const where = mergeWhere({ [pkField]: { _eq: id } }, m.fixedFilter);
537
- const query2 = `query One_${m.table}($where: ${m.table}_bool_exp) {
608
+ }`, { object: {
609
+ [db.fk]: parentId,
610
+ [db.column]: body
611
+ } }, role, signal);
612
+ }
613
+ function mutationRecord(m, idField, item, resource, expectedId) {
614
+ if (item === null || typeof item !== "object" || Array.isArray(item)) throw {
615
+ kind: "protocol",
616
+ code: "record-not-found",
617
+ message: `Not found: ${resource}`
618
+ };
619
+ const id = item[m.pkField ?? idField];
620
+ if (typeof id !== "string" && (typeof id !== "number" || !Number.isFinite(id))) throw {
621
+ kind: "protocol",
622
+ code: "mutation-record-id-missing",
623
+ message: `Mutation for '${resource}' returned no valid '${m.pkField ?? idField}'.`
624
+ };
625
+ if (expectedId !== void 0 && id !== expectedId) throw {
626
+ kind: "protocol",
627
+ code: "unexpected-record-id",
628
+ message: `Mutation for '${resource}' returned '${String(id)}' instead of '${String(expectedId)}'.`
629
+ };
630
+ return {
631
+ kind: "record",
632
+ id,
633
+ record: item,
634
+ completeness: "partial"
635
+ };
636
+ }
637
+ async function readMutationRecord(m, id, signal) {
638
+ const fields = m.selectFields.join(" ");
639
+ const pkType = m.pkType ?? "bigint";
640
+ const pkField = m.pkField ?? "id";
641
+ const root = byPkRoot(m);
642
+ if (m.fixedFilter || root === null) {
643
+ const where = mergeWhere({ [pkField]: { _eq: id } }, m.fixedFilter);
644
+ return (await gql(`query One_${m.table}($where: ${m.table}_bool_exp) {
538
645
  items: ${m.table}(where: $where, limit: 1) { ${fields} }
539
- }`;
540
- const data2 = await gql(query2, { where }, m.role, signal);
541
- return data2.items?.[0] ?? null;
542
- }
543
- const query = `query One_${m.table}($id: ${pkType}!) {
646
+ }`, { where }, m.role, signal)).items?.[0] ?? null;
647
+ }
648
+ return (await gql(`query One_${m.table}($id: ${pkType}!) {
544
649
  item: ${root}(${pkField}: $id) { ${fields} }
545
- }`;
546
- const data = await gql(query, { id }, m.role, signal);
547
- return data.item;
548
- }
549
- return core.defineDataProvider({
550
- queries: {
551
- async list(descriptor, context) {
552
- const m = mapping(descriptor.resource);
553
- if (descriptor.pagination?.kind === "cursor") {
554
- throw {
555
- kind: "capability",
556
- code: "cursor-pagination-unsupported",
557
- message: "Hasura provider supports offset pagination only."
558
- };
559
- }
560
- const limit = descriptor.pagination?.kind === "offset" ? descriptor.pagination.pageSize : 25;
561
- const page = descriptor.pagination?.kind === "offset" ? descriptor.pagination.page : 1;
562
- const offset = (page - 1) * limit;
563
- const where = composeListWhere(m, descriptor, context);
564
- const sorters = descriptor.sort?.filter((s) => s.field);
565
- let orderByExpr;
566
- if (sorters && sorters.length > 0) {
567
- orderByExpr = `[${sorters.map((s) => `{${s.field}: ${s.direction}}`).join(", ")}]`;
568
- } else {
569
- const defaultField = m.orderByField ?? "id";
570
- orderByExpr = `{${defaultField}: desc}`;
571
- }
572
- const fields = m.selectFields.join(" ");
573
- const whereArg = where ? ", $where: " + m.table + "_bool_exp" : "";
574
- const whereParam = where ? ", where: $where" : "";
575
- const itemsQuery = `query List_${m.table}($limit: Int, $offset: Int${whereArg}) {
650
+ }`, { id }, m.role, signal)).item;
651
+ }
652
+ async function listByCursor(m, descriptor, pagination, context) {
653
+ if (pagination.before !== void 0) throw {
654
+ kind: "capability",
655
+ code: HASURA_CURSOR_CODES.backward,
656
+ message: `@burojs/hasura implements forward cursor pagination only; '${m.table}' was asked to page backwards with \`before\`. Nothing in this framework drives backward keyset paging today, and an unexercised implementation of it would be a worse answer than a refusal.`
657
+ };
658
+ assertCursorLimit(pagination.limit, m.table);
659
+ const sorters = descriptor.sort?.filter((s) => s.field);
660
+ const ordering = effectiveCursorOrdering(sorters, m);
661
+ assertCursorOrderable(ordering, sorters, m);
662
+ const baseWhere = composeListWhere(m, descriptor, context);
663
+ const where = pagination.after === void 0 ? baseWhere : mergeWhere(baseWhere, keysetWhere(ordering, decodeCursor(pagination.after, ordering, m.table), m.int64Fields));
664
+ const fields = m.selectFields.join(" ");
665
+ const orderByExpr = `[${ordering.map((c) => `{${c.field}: ${c.direction}}`).join(", ")}]`;
666
+ const whereArg = where ? `, $where: ${m.table}_bool_exp` : "";
667
+ const whereParam = where ? ", where: $where" : "";
668
+ const itemsQuery = `query ListCursor_${m.table}($limit: Int${whereArg}) {
669
+ items: ${m.table}(limit: $limit, order_by: ${orderByExpr}${whereParam}) { ${fields} }
670
+ }`;
671
+ const itemsVars = { limit: pagination.limit + 1 };
672
+ if (where) itemsVars.where = where;
673
+ const fetched = (await gql(itemsQuery, itemsVars, m.role, context.signal)).items ?? [];
674
+ const hasNextPage = fetched.length > pagination.limit;
675
+ const rows = hasNextPage ? fetched.slice(0, pagination.limit) : fetched;
676
+ let total;
677
+ const listAggRoot = aggregateRoot(m);
678
+ if (!m.noAggregate && listAggRoot) try {
679
+ total = await runAggregateCount(m, listAggRoot, baseWhere, context.signal);
680
+ } catch (err) {
681
+ console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
682
+ }
683
+ const boundary = rows[rows.length - 1];
684
+ const nextCursor = hasNextPage && boundary !== null && typeof boundary === "object" ? encodeCursor(ordering, boundary, m.table) : void 0;
685
+ const spill = m.jsonbSpill;
686
+ return {
687
+ data: spill ? rows.map((it) => flattenJsonbSpill(it, spill)) : rows,
688
+ total,
689
+ pageInfo: {
690
+ nextCursor,
691
+ hasNextPage
692
+ }
693
+ };
694
+ }
695
+ return (0, _burojs_core.defineDataProvider)({
696
+ queries: {
697
+ async list(descriptor, context) {
698
+ const m = mapping(descriptor.resource);
699
+ if (descriptor.pagination?.kind === "cursor") return await listByCursor(m, descriptor, descriptor.pagination, context);
700
+ const limit = descriptor.pagination?.kind === "offset" ? descriptor.pagination.pageSize : 25;
701
+ const offset = ((descriptor.pagination?.kind === "offset" ? descriptor.pagination.page : 1) - 1) * limit;
702
+ const where = composeListWhere(m, descriptor, context);
703
+ const sorters = descriptor.sort?.filter((s) => s.field);
704
+ let orderByExpr;
705
+ if (sorters && sorters.length > 0) orderByExpr = `[${sorters.map((s) => `{${s.field}: ${s.direction}}`).join(", ")}]`;
706
+ else orderByExpr = `{${m.orderByField ?? "id"}: desc}`;
707
+ const fields = m.selectFields.join(" ");
708
+ const whereArg = where ? `, $where: ${m.table}_bool_exp` : "";
709
+ const whereParam = where ? ", where: $where" : "";
710
+ const itemsQuery = `query List_${m.table}($limit: Int, $offset: Int${whereArg}) {
576
711
  items: ${m.table}(limit: $limit, offset: $offset, order_by: ${orderByExpr}${whereParam}) { ${fields} }
577
712
  }`;
578
- const itemsVars = { limit, offset };
579
- if (where) itemsVars["where"] = where;
580
- const itemsData = await gql(
581
- itemsQuery,
582
- itemsVars,
583
- m.role,
584
- context.signal
585
- );
586
- let total;
587
- const listAggRoot = aggregateRoot(m);
588
- if (!m.noAggregate && listAggRoot) {
589
- try {
590
- total = await runAggregateCount(m, listAggRoot, where, context.signal);
591
- } catch (err) {
592
- console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
593
- }
594
- }
595
- const spill = m.jsonbSpill;
596
- const items = spill ? itemsData.items.map((it) => flattenJsonbSpill(it, spill)) : itemsData.items;
597
- return { data: items, total };
598
- },
599
- /**
600
- * On-demand row count — the answer to "how many are there?" on the lists
601
- * that page without a grand total (`noAggregate`). Never fired implicitly:
602
- * one source app measured ~55 s for a single COUNT, which is exactly why
603
- * the list stopped issuing one on every page.
604
- *
605
- * `{ total: null }` means "not countable here at all" — the registry says
606
- * this table has no aggregate root, or the resource isn't mapped by this
607
- * provider. It is a DECISION, and the UI latches the affordance off for the
608
- * session. A transient backend failure REJECTS instead (it propagates out of
609
- * `gql`), so a retry stays possible; never conflate the two.
610
- *
611
- * The `where` comes from the same {@link composeListWhere} `getList` uses —
612
- * same filters, same scope, same `fixedFilter` — so the number always
613
- * describes the rows the list is paging through.
614
- */
615
- async count(descriptor, context) {
616
- const m = config.resources[descriptor.resource];
617
- if (!m) return { total: null };
618
- const root = aggregateRoot(m);
619
- if (!root) return { total: null };
620
- return {
621
- total: await runAggregateCount(
622
- m,
623
- root,
624
- composeListWhere(m, descriptor, context),
625
- context.signal
626
- )
627
- };
628
- },
629
- async many(descriptor, context) {
630
- const m = mapping(descriptor.resource);
631
- if (descriptor.ids.length === 0) return { data: [] };
632
- const pkField = m.pkField ?? "id";
633
- const idsWhere = { [pkField]: { _in: descriptor.ids } };
634
- const where = mergeWhere(
635
- idsWhere,
636
- composeListWhere(m, descriptor, context)
637
- );
638
- const fields = m.selectFields.join(" ");
639
- const query = `query Many_${m.table}($where: ${m.table}_bool_exp) {
713
+ const itemsVars = {
714
+ limit,
715
+ offset
716
+ };
717
+ if (where) itemsVars.where = where;
718
+ const itemsData = await gql(itemsQuery, itemsVars, m.role, context.signal);
719
+ let total;
720
+ const listAggRoot = aggregateRoot(m);
721
+ if (!m.noAggregate && listAggRoot) try {
722
+ total = await runAggregateCount(m, listAggRoot, where, context.signal);
723
+ } catch (err) {
724
+ console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
725
+ }
726
+ const spill = m.jsonbSpill;
727
+ return {
728
+ data: spill ? itemsData.items.map((it) => flattenJsonbSpill(it, spill)) : itemsData.items,
729
+ total
730
+ };
731
+ },
732
+ async count(descriptor, context) {
733
+ const m = config.resources[descriptor.resource];
734
+ if (!m) return { total: null };
735
+ const root = aggregateRoot(m);
736
+ if (!root) return { total: null };
737
+ return { total: await runAggregateCount(m, root, composeListWhere(m, descriptor, context), context.signal) };
738
+ },
739
+ async many(descriptor, context) {
740
+ const m = mapping(descriptor.resource);
741
+ localeWhere(m, descriptor.locale);
742
+ if (descriptor.ids.length === 0) return { data: [] };
743
+ const where = mergeWhere({ [m.pkField ?? "id"]: { _in: descriptor.ids } }, composeListWhere(m, descriptor, context));
744
+ const fields = m.selectFields.join(" ");
745
+ const data = await gql(`query Many_${m.table}($where: ${m.table}_bool_exp) {
640
746
  items: ${m.table}(where: $where) { ${fields} }
641
- }`;
642
- const data = await gql(query, { where }, m.role, context.signal);
643
- const spill = m.jsonbSpill;
644
- const items = spill ? data.items.map((item) => flattenJsonbSpill(item, spill)) : data.items;
645
- return { data: items };
646
- },
647
- async one(descriptor, context) {
648
- const m = mapping(descriptor.resource);
649
- const dbSelect = m.dataBody ? ` ${m.dataBody.relationship} { ${m.dataBody.column} }` : "";
650
- const fields = m.selectFields.join(" ") + dbSelect;
651
- const pkType = m.pkType ?? "bigint";
652
- const pkField = m.pkField ?? "id";
653
- let item;
654
- const root = byPkRoot(m);
655
- if (m.fixedFilter || root === null) {
656
- const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
657
- const query = `query One_${m.table}($where: ${m.table}_bool_exp) {
747
+ }`, { where }, m.role, context.signal);
748
+ const spill = m.jsonbSpill;
749
+ return { data: spill ? data.items.map((item) => flattenJsonbSpill(item, spill)) : data.items };
750
+ },
751
+ async one(descriptor, context) {
752
+ const m = mapping(descriptor.resource);
753
+ const dbSelect = m.dataBody ? ` ${m.dataBody.relationship} { ${m.dataBody.column} }` : "";
754
+ const fields = m.selectFields.join(" ") + dbSelect;
755
+ const pkType = m.pkType ?? "bigint";
756
+ const pkField = m.pkField ?? "id";
757
+ let item;
758
+ const root = byPkRoot(m);
759
+ const localeSlice = localeWhere(m, descriptor.locale);
760
+ if (m.fixedFilter || localeSlice || root === null) {
761
+ const where = mergeWhere(mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter), localeSlice);
762
+ item = (await gql(`query One_${m.table}($where: ${m.table}_bool_exp) {
658
763
  items: ${m.table}(where: $where, limit: 1) { ${fields} }
659
- }`;
660
- const data = await gql(query, { where }, m.role, context.signal);
661
- item = data.items?.[0] ?? null;
662
- } else {
663
- const query = `query One_${m.table}($id: ${pkType}!) {
764
+ }`, { where }, m.role, context.signal)).items?.[0] ?? null;
765
+ } else item = (await gql(`query One_${m.table}($id: ${pkType}!) {
664
766
  item: ${root}(${pkField}: $id) { ${fields} }
665
- }`;
666
- const data = await gql(
667
- query,
668
- { id: descriptor.id },
669
- m.role,
670
- context.signal
671
- );
672
- item = data.item;
673
- }
674
- if (item == null)
675
- throw {
676
- kind: "protocol",
677
- code: "record-not-found",
678
- message: `Not found: ${descriptor.resource}/${descriptor.id}`
679
- };
680
- let result = m.jsonbSpill ? flattenJsonbSpill(item, m.jsonbSpill) : item;
681
- if (m.dataBody && result && typeof result === "object") {
682
- const rec = { ...result };
683
- const sibling = rec[m.dataBody.relationship];
684
- const body = sibling && typeof sibling === "object" ? sibling[m.dataBody.column] : null;
685
- delete rec[m.dataBody.relationship];
686
- result = body && typeof body === "object" ? { ...rec, ...body } : rec;
687
- }
688
- return { data: result };
689
- },
690
- ...hasCustomQueries ? {
691
- async custom(descriptor, context) {
692
- return executeCustomOperation(
693
- descriptor.resource,
694
- descriptor.operation,
695
- descriptor.input,
696
- "query",
697
- context.signal
698
- );
699
- }
700
- } : {}
701
- },
702
- mutations: {
703
- async createOne(descriptor, context) {
704
- const m = mapping(descriptor.resource);
705
- const fields = m.selectFields.join(" ");
706
- const rawInput = descriptor.input;
707
- let mainInput = rawInput;
708
- let dataBody;
709
- if (m.dataBody) {
710
- const split = partitionDataBody(rawInput, m.dataBody);
711
- mainInput = split.rest;
712
- dataBody = split.hasDataBody ? split.dataBody : void 0;
713
- }
714
- const object = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
715
- const query = `mutation Create_${m.table}($object: ${m.table}_insert_input!) {
767
+ }`, { id: descriptor.id }, m.role, context.signal)).item;
768
+ if (item == null) throw {
769
+ kind: "protocol",
770
+ code: "record-not-found",
771
+ message: `Not found: ${descriptor.resource}/${descriptor.id}`
772
+ };
773
+ let result = m.jsonbSpill ? flattenJsonbSpill(item, m.jsonbSpill) : item;
774
+ if (m.dataBody && result && typeof result === "object") {
775
+ const rec = { ...result };
776
+ const sibling = rec[m.dataBody.relationship];
777
+ const body = sibling && typeof sibling === "object" ? sibling[m.dataBody.column] : null;
778
+ delete rec[m.dataBody.relationship];
779
+ result = body && typeof body === "object" ? {
780
+ ...rec,
781
+ ...body
782
+ } : rec;
783
+ }
784
+ return { data: result };
785
+ },
786
+ ...hasCustomQueries ? { async custom(descriptor, context) {
787
+ return executeCustomOperation(descriptor.resource, descriptor.operation, descriptor.input, "query", context.signal);
788
+ } } : {}
789
+ },
790
+ mutations: {
791
+ async createOne(descriptor, context) {
792
+ const m = mapping(descriptor.resource);
793
+ const fields = m.selectFields.join(" ");
794
+ const rawInput = descriptor.input;
795
+ let mainInput = rawInput;
796
+ let dataBody;
797
+ if (m.dataBody) {
798
+ const split = partitionDataBody(rawInput, m.dataBody);
799
+ mainInput = split.rest;
800
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
801
+ }
802
+ const object = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
803
+ const data = await gql(`mutation Create_${m.table}($object: ${m.table}_insert_input!) {
716
804
  item: insert_${m.table}_one(object: $object) { ${fields} }
717
- }`;
718
- const data = await gql(query, { object }, m.role, context.signal);
719
- const result = mutationRecord(m, descriptor.idField, data.item, descriptor.resource);
720
- if (m.dataBody && dataBody)
721
- await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
722
- return result;
723
- },
724
- async updateOne(descriptor, context) {
725
- const m = mapping(descriptor.resource);
726
- const fields = m.selectFields.join(" ");
727
- const rawInput = descriptor.input;
728
- let mainInput = rawInput;
729
- let dataBody;
730
- if (m.dataBody) {
731
- const split = partitionDataBody(rawInput, m.dataBody);
732
- mainInput = split.rest;
733
- dataBody = split.hasDataBody ? split.dataBody : void 0;
734
- }
735
- const set = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
736
- const pkField = m.pkField ?? descriptor.idField;
737
- const ifUpdatedAt = descriptor.providerOptions?.ifUpdatedAt;
738
- let item;
739
- if (Object.keys(set).length === 0) {
740
- item = await readMutationRecord(m, descriptor.id, context.signal);
741
- } else if (m.fixedFilter || ifUpdatedAt != null) {
742
- let where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
743
- if (ifUpdatedAt != null) where = mergeWhere(where, { updated_at: { _eq: ifUpdatedAt } });
744
- const query = `mutation Update_${m.table}($where: ${m.table}_bool_exp!, $set: ${m.table}_set_input!) {
805
+ }`, { object }, m.role, context.signal);
806
+ const result = mutationRecord(m, descriptor.idField, data.item, descriptor.resource);
807
+ if (m.dataBody && dataBody) await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
808
+ return result;
809
+ },
810
+ async updateOne(descriptor, context) {
811
+ const m = mapping(descriptor.resource);
812
+ const fields = m.selectFields.join(" ");
813
+ const rawInput = descriptor.input;
814
+ let mainInput = rawInput;
815
+ let dataBody;
816
+ if (m.dataBody) {
817
+ const split = partitionDataBody(rawInput, m.dataBody);
818
+ mainInput = split.rest;
819
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
820
+ }
821
+ const set = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
822
+ const pkField = m.pkField ?? descriptor.idField;
823
+ const ifUpdatedAt = descriptor.providerOptions?.ifUpdatedAt;
824
+ let item;
825
+ if (Object.keys(set).length === 0) item = await readMutationRecord(m, descriptor.id, context.signal);
826
+ else if (m.fixedFilter || ifUpdatedAt != null) {
827
+ let where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
828
+ if (ifUpdatedAt != null) where = mergeWhere(where, { updated_at: { _eq: ifUpdatedAt } });
829
+ const data = await gql(`mutation Update_${m.table}($where: ${m.table}_bool_exp!, $set: ${m.table}_set_input!) {
745
830
  result: update_${m.table}(where: $where, _set: $set) { affected_rows returning { ${fields} } }
746
- }`;
747
- const data = await gql(
748
- query,
749
- { where, set },
750
- m.role,
751
- context.signal
752
- );
753
- if (ifUpdatedAt != null && ((data.result.affected_rows ?? 0) === 0 || (data.result.returning?.length ?? 0) === 0)) {
754
- throw {
755
- kind: "conflict",
756
- code: "stale-record",
757
- message: `Update for '${descriptor.resource}/${descriptor.id}' matched no row: the record was changed since it was loaded.`
758
- };
759
- }
760
- item = data.result.returning?.[0] ?? null;
761
- } else {
762
- const pkType = m.pkType ?? "bigint";
763
- const query = `mutation Update_${m.table}($id: ${pkType}!, $set: ${m.table}_set_input!) {
831
+ }`, {
832
+ where,
833
+ set
834
+ }, m.role, context.signal);
835
+ if (ifUpdatedAt != null && ((data.result.affected_rows ?? 0) === 0 || (data.result.returning?.length ?? 0) === 0)) throw {
836
+ kind: "conflict",
837
+ code: "stale-record",
838
+ message: `Update for '${descriptor.resource}/${descriptor.id}' matched no row: the record was changed since it was loaded.`
839
+ };
840
+ item = data.result.returning?.[0] ?? null;
841
+ } else {
842
+ const pkType = m.pkType ?? "bigint";
843
+ item = (await gql(`mutation Update_${m.table}($id: ${pkType}!, $set: ${m.table}_set_input!) {
764
844
  item: update_${m.table}_by_pk(pk_columns: {${pkField}: $id}, _set: $set) { ${fields} }
765
- }`;
766
- const data = await gql(
767
- query,
768
- { id: descriptor.id, set },
769
- m.role,
770
- context.signal
771
- );
772
- item = data.item;
773
- }
774
- const result = mutationRecord(
775
- m,
776
- descriptor.idField,
777
- item,
778
- descriptor.resource,
779
- descriptor.id
780
- );
781
- if (m.dataBody && dataBody)
782
- await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
783
- return result;
784
- },
785
- async deleteOne(descriptor, context) {
786
- const m = mapping(descriptor.resource);
787
- const fields = m.selectFields.join(" ");
788
- const pkField = m.pkField ?? descriptor.idField;
789
- let item;
790
- if (m.fixedFilter) {
791
- const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
792
- const query = `mutation Delete_${m.table}($where: ${m.table}_bool_exp!) {
845
+ }`, {
846
+ id: descriptor.id,
847
+ set
848
+ }, m.role, context.signal)).item;
849
+ }
850
+ const result = mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
851
+ if (m.dataBody && dataBody) await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
852
+ return result;
853
+ },
854
+ async deleteOne(descriptor, context) {
855
+ const m = mapping(descriptor.resource);
856
+ const fields = m.selectFields.join(" ");
857
+ const pkField = m.pkField ?? descriptor.idField;
858
+ let item;
859
+ if (m.fixedFilter) {
860
+ const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
861
+ item = (await gql(`mutation Delete_${m.table}($where: ${m.table}_bool_exp!) {
793
862
  result: delete_${m.table}(where: $where) { affected_rows returning { ${fields} } }
794
- }`;
795
- const data = await gql(
796
- query,
797
- { where },
798
- m.role,
799
- context.signal
800
- );
801
- item = data.result.returning?.[0] ?? null;
802
- } else {
803
- const pkType = m.pkType ?? "bigint";
804
- const query = `mutation Delete_${m.table}($id: ${pkType}!) {
863
+ }`, { where }, m.role, context.signal)).result.returning?.[0] ?? null;
864
+ } else {
865
+ const pkType = m.pkType ?? "bigint";
866
+ item = (await gql(`mutation Delete_${m.table}($id: ${pkType}!) {
805
867
  item: delete_${m.table}_by_pk(${pkField}: $id) { ${fields} }
806
- }`;
807
- const data = await gql(
808
- query,
809
- { id: descriptor.id },
810
- m.role,
811
- context.signal
812
- );
813
- item = data.item;
814
- }
815
- mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
816
- return { kind: "identity", id: descriptor.id };
817
- },
818
- ...hasCustomMutations ? {
819
- async custom(descriptor, context) {
820
- return executeCustomOperation(
821
- descriptor.resource,
822
- descriptor.operation,
823
- descriptor.input,
824
- "mutation",
825
- context.signal
826
- );
827
- }
828
- } : {}
829
- },
830
- live: createHasuraLiveProvider({
831
- resources: config.resources,
832
- getToken: config.getToken,
833
- endpoint,
834
- role: defaultRole
835
- })
836
- });
868
+ }`, { id: descriptor.id }, m.role, context.signal)).item;
869
+ }
870
+ mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
871
+ return {
872
+ kind: "identity",
873
+ id: descriptor.id
874
+ };
875
+ },
876
+ ...hasCustomMutations ? { async custom(descriptor, context) {
877
+ return executeCustomOperation(descriptor.resource, descriptor.operation, descriptor.input, "mutation", context.signal);
878
+ } } : {}
879
+ },
880
+ live: createHasuraLiveProvider({
881
+ resources: config.resources,
882
+ getToken: config.getToken,
883
+ endpoint,
884
+ role: defaultRole
885
+ })
886
+ });
837
887
  }
838
-
888
+ //#endregion
839
889
  exports.DEFAULT_HASURA_ENDPOINT = DEFAULT_HASURA_ENDPOINT;
840
890
  exports.FILTER_OPERATOR_UNSUPPORTED_CODE = FILTER_OPERATOR_UNSUPPORTED_CODE;
891
+ exports.HASURA_CURSOR_CODES = HASURA_CURSOR_CODES;
892
+ exports.LOCALE_REQUIRED_CODE = LOCALE_REQUIRED_CODE;
841
893
  exports.NOT_AUTHENTICATED_CODE = NOT_AUTHENTICATED_CODE;
842
894
  exports.aggregateRoot = aggregateRoot;
895
+ exports.assertCursorLimit = assertCursorLimit;
896
+ exports.assertCursorOrderable = assertCursorOrderable;
843
897
  exports.byPkRoot = byPkRoot;
898
+ exports.coerceInt64Filter = coerceInt64Filter;
844
899
  exports.createHasuraDataProvider = createHasuraDataProvider;
845
900
  exports.createHasuraLiveProvider = createHasuraLiveProvider;
901
+ exports.decodeCursor = decodeCursor;
902
+ exports.effectiveCursorOrdering = effectiveCursorOrdering;
903
+ exports.encodeCursor = encodeCursor;
846
904
  exports.filtersToWhere = filtersToWhere;
847
905
  exports.flattenJsonbSpill = flattenJsonbSpill;
848
906
  exports.hasuraWsUrl = hasuraWsUrl;
907
+ exports.keysetWhere = keysetWhere;
908
+ exports.localeWhere = localeWhere;
849
909
  exports.mergeWhere = mergeWhere;
910
+ exports.orderingSignature = orderingSignature;
850
911
  exports.partitionDataBody = partitionDataBody;
851
912
  exports.partitionJsonbSpill = partitionJsonbSpill;
852
913
  exports.scopeToWhere = scopeToWhere;
853
- //# sourceMappingURL=index.cjs.map
914
+
854
915
  //# sourceMappingURL=index.cjs.map