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