@burojs/hasura 0.2.0 → 0.5.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,968 @@
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 FORBIDDEN_CODES = new Set(["access-denied", "permission-error"]);
346
+ const HASURA_EXTERNAL_FAILURE_CODES = new Set([
347
+ "unexpected",
348
+ "remote-schema-error",
349
+ "parse-failed"
350
+ ]);
351
+ const MUTATION_REFUSAL_CODES = new Map([["constraint-violation", "conflict"], ["validation-failed", "validation"]]);
352
+ function graphqlError(errors, operation, external) {
353
+ const message = errors.map((e) => e.message).join("; ");
354
+ const codes = errors.flatMap((e) => typeof e.extensions?.code === "string" ? [e.extensions.code] : []);
355
+ if (codes.includes("invalid-jwt")) return {
356
+ kind: "auth",
357
+ code: "invalid-jwt",
358
+ message,
359
+ details: errors
360
+ };
361
+ const outside = operation === "mutation" && external ? codes.find((code) => HASURA_EXTERNAL_FAILURE_CODES.has(code) || MUTATION_REFUSAL_CODES.has(code) || FORBIDDEN_CODES.has(code)) : void 0;
362
+ if (outside !== void 0) return {
363
+ kind: "sent",
364
+ code: outside,
365
+ message,
366
+ retryable: false,
367
+ details: errors
368
+ };
369
+ const forbidden = codes.find((code) => FORBIDDEN_CODES.has(code));
370
+ if (forbidden !== void 0) return {
371
+ kind: "forbidden",
372
+ code: forbidden,
373
+ message,
374
+ details: errors
375
+ };
376
+ if (operation === "mutation") for (const code of codes) {
377
+ const kind = MUTATION_REFUSAL_CODES.get(code);
378
+ if (kind !== void 0) return {
379
+ kind,
380
+ code,
381
+ message,
382
+ details: errors
383
+ };
384
+ }
385
+ return {
386
+ kind: "protocol",
387
+ code: "graphql-error",
388
+ message,
389
+ details: errors
390
+ };
391
+ }
392
+ function answerLost(code, message, status, cause) {
393
+ return {
394
+ kind: "sent",
395
+ code,
396
+ message,
397
+ status,
398
+ retryable: false,
399
+ ...cause === void 0 ? {} : { cause }
400
+ };
401
+ }
402
+ const LOCALE_REQUIRED_CODE = "locale-required";
403
+ function localeWhere(m, locale) {
404
+ if (m.localeField === void 0) return void 0;
405
+ if (typeof locale !== "string" || locale.length === 0) throw {
406
+ kind: "capability",
407
+ code: LOCALE_REQUIRED_CODE,
408
+ 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.`
409
+ };
410
+ return { [m.localeField]: { _eq: locale } };
411
+ }
412
+ const OP_MAP = {
413
+ eq: "_eq",
414
+ neq: "_neq",
415
+ ne: "_neq",
416
+ lt: "_lt",
417
+ lte: "_lte",
418
+ gt: "_gt",
419
+ gte: "_gte",
420
+ in: "_in",
421
+ notIn: "_nin",
422
+ nin: "_nin",
423
+ contains: "_ilike",
424
+ containss: "_like",
425
+ startsWith: "_ilike",
426
+ endsWith: "_ilike",
427
+ startswith: "_ilike",
428
+ endswith: "_ilike",
429
+ null: "_is_null"
241
430
  };
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"
431
+ const FILTER_OPERATOR_UNSUPPORTED_CODE = "filter-operator-unsupported";
432
+ const UNEXPRESSIBLE_OPS = {
433
+ has: "a collection-membership test",
434
+ hasAny: "a collection-membership test",
435
+ hasAll: "a collection-membership test"
247
436
  };
248
437
  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
- };
438
+ const why = UNEXPRESSIBLE_OPS[op];
439
+ return {
440
+ kind: "capability",
441
+ code: FILTER_OPERATOR_UNSUPPORTED_CODE,
442
+ 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}').`
443
+ };
255
444
  }
256
445
  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 };
446
+ const clauses = [];
447
+ for (const key of scopeFields) {
448
+ const v = scope[key];
449
+ if (v == null || v === "") continue;
450
+ clauses.push({ [key]: { _eq: v } });
451
+ }
452
+ if (clauses.length === 0) return void 0;
453
+ if (clauses.length === 1) return clauses[0];
454
+ return { _and: clauses };
266
455
  }
267
456
  function mergeWhere(a, b) {
268
- if (!a) return b;
269
- if (!b) return a;
270
- return { _and: [a, b] };
457
+ if (!a) return b;
458
+ if (!b) return a;
459
+ return { _and: [a, b] };
460
+ }
461
+ function atFieldPath(field, predicate) {
462
+ const parts = field.split(".");
463
+ let out = predicate;
464
+ for (let i = parts.length - 1; i >= 0; i -= 1) out = { [parts[i]]: out };
465
+ return out;
271
466
  }
272
467
  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 } };
468
+ if (!filter || typeof filter !== "object") return void 0;
469
+ if ("and" in filter) {
470
+ if (filter.and.length === 0) return { _and: [] };
471
+ const clauses = filter.and.map(filtersToWhere).filter((item) => item !== void 0);
472
+ if (clauses.length === 0) return void 0;
473
+ return clauses.length === 1 ? clauses[0] : { _and: clauses };
474
+ }
475
+ if ("or" in filter) {
476
+ if (filter.or.length === 0) return { _or: [] };
477
+ const clauses = filter.or.map(filtersToWhere).filter((item) => item !== void 0);
478
+ if (clauses.length === 0) return void 0;
479
+ return clauses.length === 1 ? clauses[0] : { _or: clauses };
480
+ }
481
+ if ("not" in filter) {
482
+ const clause = filtersToWhere(filter.not);
483
+ return clause === void 0 ? void 0 : { _not: clause };
484
+ }
485
+ if (!("field" in filter) || typeof filter.field !== "string" || !("op" in filter)) return void 0;
486
+ const { field, op } = filter;
487
+ if (op === "isNull") return atFieldPath(field, { _is_null: true });
488
+ if (op === "isNotNull") return atFieldPath(field, { _is_null: false });
489
+ if (!("value" in filter) || filter.value === void 0) return void 0;
490
+ const operator = OP_MAP[op];
491
+ if (operator === void 0) throw unsupportedOperator(field, op);
492
+ let value = filter.value;
493
+ if (operator === "_ilike" || operator === "_like") {
494
+ const text = String(value);
495
+ value = op === "startsWith" ? `${text}%` : op === "endsWith" ? `%${text}` : `%${text}%`;
496
+ }
497
+ return atFieldPath(field, { [operator]: value });
304
498
  }
305
499
  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;
500
+ if (!filter || !fields?.length) return filter;
501
+ if ("and" in filter) return { and: filter.and.map((entry) => coerceInt64Filter(entry, fields)) };
502
+ if ("or" in filter) return { or: filter.or.map((entry) => coerceInt64Filter(entry, fields)) };
503
+ if ("not" in filter) return { not: coerceInt64Filter(filter.not, fields) };
504
+ if ("field" in filter && fields.includes(filter.field) && "value" in filter && filter.value != null) {
505
+ const value = Array.isArray(filter.value) ? filter.value.map(String) : String(filter.value);
506
+ return {
507
+ ...filter,
508
+ value
509
+ };
510
+ }
511
+ return filter;
326
512
  }
327
513
  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
- };
514
+ if (isDataError(error)) return error;
515
+ if (signal.aborted) return {
516
+ kind: "cancelled",
517
+ code: "request-aborted",
518
+ message: "Hasura request was aborted.",
519
+ cause: error
520
+ };
521
+ return {
522
+ kind: "transport",
523
+ code: "hasura-request-failed",
524
+ message: error instanceof Error && error.message ? error.message : fallback,
525
+ cause: error
526
+ };
342
527
  }
343
528
  function aggregateRoot(m) {
344
- if (m.aggregate === false) return null;
345
- return typeof m.aggregate === "string" ? m.aggregate : `${m.table}_aggregate`;
529
+ if (m.aggregate === false) return null;
530
+ return typeof m.aggregate === "string" ? m.aggregate : `${m.table}_aggregate`;
346
531
  }
347
532
  function byPkRoot(m) {
348
- if (m.byPkRoot === false) return null;
349
- return m.byPkRoot ?? `${m.table}_by_pk`;
533
+ if (m.byPkRoot === false) return null;
534
+ return m.byPkRoot ?? `${m.table}_by_pk`;
350
535
  }
351
536
  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);
537
+ if (source === void 0) return Object.freeze({});
538
+ const resources = {};
539
+ for (const [resource, operations] of Object.entries(source)) {
540
+ const entries = {};
541
+ for (const [name, operation] of Object.entries(operations)) entries[name] = Object.freeze({ ...operation });
542
+ resources[resource] = Object.freeze(entries);
543
+ }
544
+ return Object.freeze(resources);
362
545
  }
363
546
  function hasRegisteredOperationKind(operations, kind) {
364
- return Object.values(operations).some(
365
- (byName) => Object.values(byName).some((operation) => operation.kind === kind)
366
- );
547
+ return Object.values(operations).some((byName) => Object.values(byName).some((operation) => operation.kind === kind));
367
548
  }
368
549
  function normalizeRole(role) {
369
- return role === void 0 || role === null || role === "" ? null : role;
550
+ return role === void 0 || role === null || role === "" ? null : role;
370
551
  }
371
552
  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} {
553
+ const endpoint = config.endpoint ?? "/gql/v1/graphql";
554
+ const defaultRole = normalizeRole(config.defaultRole);
555
+ const operations = snapshotOperationRegistry(config.operations);
556
+ const hasCustomQueries = hasRegisteredOperationKind(operations, "query");
557
+ const hasCustomMutations = hasRegisteredOperationKind(operations, "mutation");
558
+ async function gql(query, variables, role, signal, operation, external = false) {
559
+ try {
560
+ const requestBody = JSON.stringify({
561
+ query,
562
+ variables
563
+ });
564
+ const request = async (token) => {
565
+ const headers = {
566
+ "Content-Type": "application/json",
567
+ Authorization: `Bearer ${token}`
568
+ };
569
+ const effectiveRole = role === void 0 ? defaultRole : normalizeRole(role);
570
+ if (effectiveRole !== null) headers["X-Hasura-Role"] = effectiveRole;
571
+ const fetchImpl = config.fetchImpl ?? fetch;
572
+ try {
573
+ return await fetchImpl(endpoint, {
574
+ method: "POST",
575
+ headers,
576
+ body: requestBody,
577
+ signal
578
+ });
579
+ } catch (cause) {
580
+ if (operation === "mutation" && !signal.aborted) throw {
581
+ kind: "sent",
582
+ code: "hasura-request-sent",
583
+ message: "Hasura did not answer a mutation; it may have been applied.",
584
+ retryable: false,
585
+ cause
586
+ };
587
+ throw cause;
588
+ }
589
+ };
590
+ let token = await config.getToken();
591
+ if (!token) throw {
592
+ kind: "auth",
593
+ code: NOT_AUTHENTICATED_CODE,
594
+ message: "Not authenticated."
595
+ };
596
+ let res = await request(token);
597
+ if (res.status === 401 && config.recoverAuth && await config.recoverAuth()) {
598
+ token = await config.getToken();
599
+ if (!token) throw {
600
+ kind: "auth",
601
+ code: NOT_AUTHENTICATED_CODE,
602
+ message: "Not authenticated."
603
+ };
604
+ res = await request(token);
605
+ }
606
+ if (!res.ok) {
607
+ if (operation === "mutation" && res.status >= 500) throw answerLost("hasura-answer-lost", `GraphQL HTTP ${res.status} after a mutation was sent; it may have been applied.`, res.status);
608
+ throw {
609
+ kind: "transport",
610
+ code: "graphql-http-error",
611
+ message: `GraphQL HTTP ${res.status}`,
612
+ status: res.status
613
+ };
614
+ }
615
+ let body;
616
+ try {
617
+ body = await res.json();
618
+ if (body === null || typeof body !== "object") throw new TypeError("The GraphQL answer is not an object.");
619
+ } catch (cause) {
620
+ if (operation === "mutation" && !signal.aborted) throw answerLost("hasura-answer-unreadable", "Hasura answered a mutation with a body that could not be read; it may have been applied.", res.status, cause);
621
+ throw cause;
622
+ }
623
+ if (body.errors?.length) throw graphqlError(body.errors, operation, external);
624
+ if (body.data === void 0) {
625
+ if (operation === "mutation") throw answerLost("hasura-answer-unreadable", "Hasura answered a mutation without data or errors; it may have been applied.", res.status);
626
+ throw {
627
+ kind: "protocol",
628
+ code: "empty-graphql-response",
629
+ message: "Empty GraphQL response."
630
+ };
631
+ }
632
+ return body.data;
633
+ } catch (error) {
634
+ throw hasuraError(error, signal, "Hasura request failed.");
635
+ }
636
+ }
637
+ function mapping(resource) {
638
+ const m = config.resources[resource];
639
+ if (!m) throw {
640
+ kind: "configuration",
641
+ code: "unknown-resource",
642
+ message: `Unknown resource: ${resource}`
643
+ };
644
+ return m;
645
+ }
646
+ function registeredOperation(resource, operation, kind) {
647
+ const registered = operations[resource]?.[operation];
648
+ if (registered === void 0 || registered.kind !== kind) throw {
649
+ kind: "capability",
650
+ code: "hasura-custom-operation-unsupported",
651
+ message: `Hasura ${kind} operation '${operation}' is not declared for '${resource}'.`
652
+ };
653
+ return registered;
654
+ }
655
+ async function executeCustomOperation(resource, operationName, input, kind, signal) {
656
+ const operation = registeredOperation(resource, operationName, kind);
657
+ const result = await gql(operation.document, operation.variables(input), operation.role ?? config.resources[resource]?.role, signal, kind, kind === "mutation");
658
+ return operation.mapResult === void 0 ? result : operation.mapResult(result);
659
+ }
660
+ function composeListWhere(m, descriptor, context) {
661
+ const userWhere = filtersToWhere(coerceInt64Filter(descriptor.filter, m.int64Fields));
662
+ const ignoreScope = descriptor.providerOptions?.ignoreScope === true;
663
+ const sessionScope = context.session.scopeKey !== null && typeof context.session.scopeKey === "object" && !Array.isArray(context.session.scopeKey) ? context.session.scopeKey : {};
664
+ return mergeWhere(mergeWhere(mergeWhere(userWhere, scopeToWhere(ignoreScope ? {} : {
665
+ ...sessionScope,
666
+ ...config.getScope?.(context) ?? {}
667
+ }, m.scopeFields ?? [])), m.fixedFilter), localeWhere(m, descriptor.locale));
668
+ }
669
+ async function runAggregateCount(m, root, where, signal) {
670
+ const aggWhereArg = where ? `($where: ${m.table}_bool_exp)` : "";
671
+ const aggWhereParam = where ? "(where: $where)" : "";
672
+ const metaQuery = `query Count_${m.table} ${aggWhereArg} {
481
673
  meta: ${root} ${aggWhereParam} { aggregate { count } }
482
674
  }`;
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!) {
675
+ const aggVars = {};
676
+ if (where) aggVars.where = where;
677
+ return (await gql(metaQuery, where ? aggVars : void 0, m.role, signal, "query")).meta.aggregate.count;
678
+ }
679
+ async function upsertDataBody(db, parentId, body, role, signal) {
680
+ await gql(`mutation UpsertDataBody($object: ${db.table}_insert_input!) {
495
681
  result: insert_${db.table}_one(
496
682
  object: $object,
497
683
  on_conflict: { constraint: ${db.constraint}, update_columns: [${db.column}] }
498
684
  ) { ${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) {
685
+ }`, { object: {
686
+ [db.fk]: parentId,
687
+ [db.column]: body
688
+ } }, role, signal, "mutation");
689
+ }
690
+ function mutationRecord(m, idField, item, resource, expectedId) {
691
+ if (item === null || typeof item !== "object" || Array.isArray(item)) throw {
692
+ kind: "not-found",
693
+ code: "record-not-found",
694
+ message: `Not found: ${resource}`
695
+ };
696
+ const id = item[m.pkField ?? idField];
697
+ if (typeof id !== "string" && (typeof id !== "number" || !Number.isFinite(id))) throw {
698
+ kind: "protocol",
699
+ code: "mutation-record-id-missing",
700
+ message: `Mutation for '${resource}' returned no valid '${m.pkField ?? idField}'.`
701
+ };
702
+ if (expectedId !== void 0 && id !== expectedId) throw {
703
+ kind: "protocol",
704
+ code: "unexpected-record-id",
705
+ message: `Mutation for '${resource}' returned '${String(id)}' instead of '${String(expectedId)}'.`
706
+ };
707
+ return {
708
+ kind: "record",
709
+ id,
710
+ record: item,
711
+ completeness: "partial"
712
+ };
713
+ }
714
+ async function readMutationRecord(m, id, signal) {
715
+ const fields = m.selectFields.join(" ");
716
+ const pkType = m.pkType ?? "bigint";
717
+ const pkField = m.pkField ?? "id";
718
+ const root = byPkRoot(m);
719
+ if (m.fixedFilter || root === null) {
720
+ const where = mergeWhere({ [pkField]: { _eq: id } }, m.fixedFilter);
721
+ return (await gql(`query One_${m.table}($where: ${m.table}_bool_exp) {
536
722
  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}!) {
723
+ }`, { where }, m.role, signal, "query")).items?.[0] ?? null;
724
+ }
725
+ return (await gql(`query One_${m.table}($id: ${pkType}!) {
542
726
  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}) {
727
+ }`, { id }, m.role, signal, "query")).item;
728
+ }
729
+ async function listByCursor(m, descriptor, pagination, context) {
730
+ if (pagination.before !== void 0) throw {
731
+ kind: "capability",
732
+ code: HASURA_CURSOR_CODES.backward,
733
+ 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.`
734
+ };
735
+ assertCursorLimit(pagination.limit, m.table);
736
+ const sorters = descriptor.sort?.filter((s) => s.field);
737
+ const ordering = effectiveCursorOrdering(sorters, m);
738
+ assertCursorOrderable(ordering, sorters, m);
739
+ const baseWhere = composeListWhere(m, descriptor, context);
740
+ const where = pagination.after === void 0 ? baseWhere : mergeWhere(baseWhere, keysetWhere(ordering, decodeCursor(pagination.after, ordering, m.table), m.int64Fields));
741
+ const fields = m.selectFields.join(" ");
742
+ const orderByExpr = `[${ordering.map((c) => `{${c.field}: ${c.direction}}`).join(", ")}]`;
743
+ const whereArg = where ? `, $where: ${m.table}_bool_exp` : "";
744
+ const whereParam = where ? ", where: $where" : "";
745
+ const itemsQuery = `query ListCursor_${m.table}($limit: Int${whereArg}) {
746
+ items: ${m.table}(limit: $limit, order_by: ${orderByExpr}${whereParam}) { ${fields} }
747
+ }`;
748
+ const itemsVars = { limit: pagination.limit + 1 };
749
+ if (where) itemsVars.where = where;
750
+ const fetched = (await gql(itemsQuery, itemsVars, m.role, context.signal, "query")).items ?? [];
751
+ const hasNextPage = fetched.length > pagination.limit;
752
+ const rows = hasNextPage ? fetched.slice(0, pagination.limit) : fetched;
753
+ let total;
754
+ const listAggRoot = aggregateRoot(m);
755
+ if (!m.noAggregate && listAggRoot) try {
756
+ total = await runAggregateCount(m, listAggRoot, baseWhere, context.signal);
757
+ } catch (err) {
758
+ console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
759
+ }
760
+ const boundary = rows[rows.length - 1];
761
+ const nextCursor = hasNextPage && boundary !== null && typeof boundary === "object" ? encodeCursor(ordering, boundary, m.table) : void 0;
762
+ const spill = m.jsonbSpill;
763
+ return {
764
+ data: spill ? rows.map((it) => flattenJsonbSpill(it, spill)) : rows,
765
+ total,
766
+ pageInfo: {
767
+ nextCursor,
768
+ hasNextPage
769
+ }
770
+ };
771
+ }
772
+ return defineDataProvider({
773
+ queries: {
774
+ async list(descriptor, context) {
775
+ const m = mapping(descriptor.resource);
776
+ if (descriptor.pagination?.kind === "cursor") return await listByCursor(m, descriptor, descriptor.pagination, context);
777
+ const limit = descriptor.pagination?.kind === "offset" ? descriptor.pagination.pageSize : 25;
778
+ const offset = ((descriptor.pagination?.kind === "offset" ? descriptor.pagination.page : 1) - 1) * limit;
779
+ const where = composeListWhere(m, descriptor, context);
780
+ const sorters = descriptor.sort?.filter((s) => s.field);
781
+ let orderByExpr;
782
+ if (sorters && sorters.length > 0) orderByExpr = `[${sorters.map((s) => `{${s.field}: ${s.direction}}`).join(", ")}]`;
783
+ else orderByExpr = `{${m.orderByField ?? "id"}: desc}`;
784
+ const fields = m.selectFields.join(" ");
785
+ const whereArg = where ? `, $where: ${m.table}_bool_exp` : "";
786
+ const whereParam = where ? ", where: $where" : "";
787
+ const itemsQuery = `query List_${m.table}($limit: Int, $offset: Int${whereArg}) {
574
788
  items: ${m.table}(limit: $limit, offset: $offset, order_by: ${orderByExpr}${whereParam}) { ${fields} }
575
789
  }`;
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) {
790
+ const itemsVars = {
791
+ limit,
792
+ offset
793
+ };
794
+ if (where) itemsVars.where = where;
795
+ const itemsData = await gql(itemsQuery, itemsVars, m.role, context.signal, "query");
796
+ let total;
797
+ const listAggRoot = aggregateRoot(m);
798
+ if (!m.noAggregate && listAggRoot) try {
799
+ total = await runAggregateCount(m, listAggRoot, where, context.signal);
800
+ } catch (err) {
801
+ console.warn(`[hasura] count failed for ${m.table}; rendering unknown-total`, err);
802
+ }
803
+ const spill = m.jsonbSpill;
804
+ return {
805
+ data: spill ? itemsData.items.map((it) => flattenJsonbSpill(it, spill)) : itemsData.items,
806
+ total
807
+ };
808
+ },
809
+ async count(descriptor, context) {
810
+ const m = config.resources[descriptor.resource];
811
+ if (!m) return { total: null };
812
+ const root = aggregateRoot(m);
813
+ if (!root) return { total: null };
814
+ return { total: await runAggregateCount(m, root, composeListWhere(m, descriptor, context), context.signal) };
815
+ },
816
+ async many(descriptor, context) {
817
+ const m = mapping(descriptor.resource);
818
+ localeWhere(m, descriptor.locale);
819
+ if (descriptor.ids.length === 0) return { data: [] };
820
+ const where = mergeWhere({ [m.pkField ?? "id"]: { _in: descriptor.ids } }, composeListWhere(m, descriptor, context));
821
+ const fields = m.selectFields.join(" ");
822
+ const data = await gql(`query Many_${m.table}($where: ${m.table}_bool_exp) {
638
823
  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) {
824
+ }`, { where }, m.role, context.signal, "query");
825
+ const spill = m.jsonbSpill;
826
+ return { data: spill ? data.items.map((item) => flattenJsonbSpill(item, spill)) : data.items };
827
+ },
828
+ async one(descriptor, context) {
829
+ const m = mapping(descriptor.resource);
830
+ const dbSelect = m.dataBody ? ` ${m.dataBody.relationship} { ${m.dataBody.column} }` : "";
831
+ const fields = m.selectFields.join(" ") + dbSelect;
832
+ const pkType = m.pkType ?? "bigint";
833
+ const pkField = m.pkField ?? "id";
834
+ let item;
835
+ const root = byPkRoot(m);
836
+ const localeSlice = localeWhere(m, descriptor.locale);
837
+ if (m.fixedFilter || localeSlice || root === null) {
838
+ const where = mergeWhere(mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter), localeSlice);
839
+ item = (await gql(`query One_${m.table}($where: ${m.table}_bool_exp) {
656
840
  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}!) {
841
+ }`, { where }, m.role, context.signal, "query")).items?.[0] ?? null;
842
+ } else item = (await gql(`query One_${m.table}($id: ${pkType}!) {
662
843
  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!) {
844
+ }`, { id: descriptor.id }, m.role, context.signal, "query")).item;
845
+ if (item == null) throw {
846
+ kind: "not-found",
847
+ code: "record-not-found",
848
+ message: `Not found: ${descriptor.resource}/${descriptor.id}`
849
+ };
850
+ let result = m.jsonbSpill ? flattenJsonbSpill(item, m.jsonbSpill) : item;
851
+ if (m.dataBody && result && typeof result === "object") {
852
+ const rec = { ...result };
853
+ const sibling = rec[m.dataBody.relationship];
854
+ const body = sibling && typeof sibling === "object" ? sibling[m.dataBody.column] : null;
855
+ delete rec[m.dataBody.relationship];
856
+ result = body && typeof body === "object" ? {
857
+ ...rec,
858
+ ...body
859
+ } : rec;
860
+ }
861
+ return { data: result };
862
+ },
863
+ ...hasCustomQueries ? { async custom(descriptor, context) {
864
+ return executeCustomOperation(descriptor.resource, descriptor.operation, descriptor.input, "query", context.signal);
865
+ } } : {}
866
+ },
867
+ mutations: {
868
+ async createOne(descriptor, context) {
869
+ const m = mapping(descriptor.resource);
870
+ const fields = m.selectFields.join(" ");
871
+ const rawInput = descriptor.input;
872
+ let mainInput = rawInput;
873
+ let dataBody;
874
+ if (m.dataBody) {
875
+ const split = partitionDataBody(rawInput, m.dataBody);
876
+ mainInput = split.rest;
877
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
878
+ }
879
+ const object = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
880
+ const data = await gql(`mutation Create_${m.table}($object: ${m.table}_insert_input!) {
714
881
  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!) {
882
+ }`, { object }, m.role, context.signal, "mutation");
883
+ const result = mutationRecord(m, descriptor.idField, data.item, descriptor.resource);
884
+ if (m.dataBody && dataBody) await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
885
+ return result;
886
+ },
887
+ async updateOne(descriptor, context) {
888
+ const m = mapping(descriptor.resource);
889
+ const fields = m.selectFields.join(" ");
890
+ const rawInput = descriptor.input;
891
+ let mainInput = rawInput;
892
+ let dataBody;
893
+ if (m.dataBody) {
894
+ const split = partitionDataBody(rawInput, m.dataBody);
895
+ mainInput = split.rest;
896
+ dataBody = split.hasDataBody ? split.dataBody : void 0;
897
+ }
898
+ const set = m.jsonbSpill ? partitionJsonbSpill(mainInput, m.jsonbSpill, m.selectFields) : mainInput;
899
+ const pkField = m.pkField ?? descriptor.idField;
900
+ const ifUpdatedAt = descriptor.providerOptions?.ifUpdatedAt;
901
+ let item;
902
+ if (Object.keys(set).length === 0) item = await readMutationRecord(m, descriptor.id, context.signal);
903
+ else if (m.fixedFilter || ifUpdatedAt != null) {
904
+ let where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
905
+ if (ifUpdatedAt != null) where = mergeWhere(where, { updated_at: { _eq: ifUpdatedAt } });
906
+ const data = await gql(`mutation Update_${m.table}($where: ${m.table}_bool_exp!, $set: ${m.table}_set_input!) {
743
907
  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!) {
908
+ }`, {
909
+ where,
910
+ set
911
+ }, m.role, context.signal, "mutation");
912
+ if (ifUpdatedAt != null && ((data.result.affected_rows ?? 0) === 0 || (data.result.returning?.length ?? 0) === 0)) throw {
913
+ kind: "conflict",
914
+ code: "stale-record",
915
+ message: `Update for '${descriptor.resource}/${descriptor.id}' matched no row: the record was changed since it was loaded.`
916
+ };
917
+ item = data.result.returning?.[0] ?? null;
918
+ } else {
919
+ const pkType = m.pkType ?? "bigint";
920
+ item = (await gql(`mutation Update_${m.table}($id: ${pkType}!, $set: ${m.table}_set_input!) {
762
921
  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!) {
922
+ }`, {
923
+ id: descriptor.id,
924
+ set
925
+ }, m.role, context.signal, "mutation")).item;
926
+ }
927
+ const result = mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
928
+ if (m.dataBody && dataBody) await upsertDataBody(m.dataBody, result.id, dataBody, m.role, context.signal);
929
+ return result;
930
+ },
931
+ async deleteOne(descriptor, context) {
932
+ const m = mapping(descriptor.resource);
933
+ const fields = m.selectFields.join(" ");
934
+ const pkField = m.pkField ?? descriptor.idField;
935
+ let item;
936
+ if (m.fixedFilter) {
937
+ const where = mergeWhere({ [pkField]: { _eq: descriptor.id } }, m.fixedFilter);
938
+ item = (await gql(`mutation Delete_${m.table}($where: ${m.table}_bool_exp!) {
791
939
  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}!) {
940
+ }`, { where }, m.role, context.signal, "mutation")).result.returning?.[0] ?? null;
941
+ } else {
942
+ const pkType = m.pkType ?? "bigint";
943
+ item = (await gql(`mutation Delete_${m.table}($id: ${pkType}!) {
803
944
  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
- });
945
+ }`, { id: descriptor.id }, m.role, context.signal, "mutation")).item;
946
+ }
947
+ mutationRecord(m, descriptor.idField, item, descriptor.resource, descriptor.id);
948
+ return {
949
+ kind: "identity",
950
+ id: descriptor.id
951
+ };
952
+ },
953
+ ...hasCustomMutations ? { async custom(descriptor, context) {
954
+ return executeCustomOperation(descriptor.resource, descriptor.operation, descriptor.input, "mutation", context.signal);
955
+ } } : {}
956
+ },
957
+ live: createHasuraLiveProvider({
958
+ resources: config.resources,
959
+ getToken: config.getToken,
960
+ endpoint,
961
+ role: defaultRole
962
+ })
963
+ });
835
964
  }
965
+ //#endregion
966
+ export { DEFAULT_HASURA_ENDPOINT, FILTER_OPERATOR_UNSUPPORTED_CODE, HASURA_CURSOR_CODES, HASURA_EXTERNAL_FAILURE_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
967
 
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
968
  //# sourceMappingURL=index.js.map