@constructive-io/data 0.9.5 → 0.10.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,6 +1,6 @@
1
1
  import { Kind, OperationTypeNode, print } from 'graphql';
2
2
  import Ajv from 'ajv';
3
- import { parse, toError, errors } from '@constructive-io/errors';
3
+ import { parse, ConstructiveError, toError, errors } from '@constructive-io/errors';
4
4
  export { ConstructiveError, classify, errors, format, isPublicCode, parse, toError } from '@constructive-io/errors';
5
5
 
6
6
  var __create = Object.create;
@@ -1071,13 +1071,13 @@ var MetaContractError = class extends Error {
1071
1071
  code;
1072
1072
  compatibility;
1073
1073
  constructor(compatibility) {
1074
- const unavailable = compatibility.status === "unavailable";
1074
+ const unavailable2 = compatibility.status === "unavailable";
1075
1075
  const detail = compatibility.missing.length > 0 ? ` Missing: ${compatibility.missing.join(", ")}.` : "";
1076
1076
  super(
1077
- unavailable ? `This endpoint does not expose Constructive _meta ${compatibility.contractVersion}.${detail}` : `This endpoint must be upgraded to Constructive _meta ${compatibility.contractVersion}.${detail}`
1077
+ unavailable2 ? `This endpoint does not expose Constructive _meta ${compatibility.contractVersion}.${detail}` : `This endpoint must be upgraded to Constructive _meta ${compatibility.contractVersion}.${detail}`
1078
1078
  );
1079
1079
  this.name = "MetaContractError";
1080
- this.code = unavailable ? "META_CONTRACT_UNAVAILABLE" : "META_CONTRACT_INCOMPATIBLE";
1080
+ this.code = unavailable2 ? "META_CONTRACT_UNAVAILABLE" : "META_CONTRACT_INCOMPATIBLE";
1081
1081
  this.compatibility = compatibility;
1082
1082
  }
1083
1083
  };
@@ -1111,6 +1111,1971 @@ function parseMetaSearchWeights(config) {
1111
1111
  }
1112
1112
  }
1113
1113
 
1114
+ // src/table-model/meta-capabilities.ts
1115
+ var META_OPTIONAL_CAPABILITIES = {
1116
+ metaTable: { typeName: "MetaTable", fields: ["kind", "description", "isJunction", "tableName"] },
1117
+ metaField: {
1118
+ typeName: "MetaField",
1119
+ fields: ["allowedValues", "isRequiredOnCreate", "isWritableOnCreate", "isWritableOnUpdate", "isComputed", "file"]
1120
+ },
1121
+ metaType: { typeName: "MetaType", fields: ["maxLength", "precision", "scale"] },
1122
+ metaBelongsTo: { typeName: "MetaBelongsToRelation", fields: ["refKeys"] },
1123
+ metaHas: { typeName: "MetaHasRelation", fields: ["remoteKeys"] },
1124
+ metaStorage: { typeName: "MetaStorage", fields: ["filesType", "bucketsType", "downloadUrlField", "upload"] },
1125
+ metaFileField: { typeName: "MetaFileField", fields: ["kind", "isMultiple", "filesType"] },
1126
+ metaStorageUpload: {
1127
+ typeName: "MetaStorageUpload",
1128
+ fields: ["mutation", "inputType", "payloadType", "bulkMutation", "requiresOwnerId"]
1129
+ }
1130
+ };
1131
+ var capabilityAliases = /* @__PURE__ */ new Map();
1132
+ for (const [alias, { typeName }] of Object.entries(META_CONTRACT_REQUIREMENTS)) capabilityAliases.set(alias, typeName);
1133
+ for (const [alias, { typeName }] of Object.entries(META_OPTIONAL_CAPABILITIES)) capabilityAliases.set(alias, typeName);
1134
+ var META_CAPABILITY_INTROSPECTION_SOURCE = (
1135
+ /* GraphQL */
1136
+ `
1137
+ query ConstructiveMetaContract {
1138
+ ${[...capabilityAliases].map(([alias, typeName]) => `${alias}: __type(name: "${typeName}") { name fields { name } }`).join("\n ")}
1139
+ }
1140
+ `
1141
+ );
1142
+ var META_CAPABILITY_INTROSPECTION_DOCUMENT = new TypedDocumentString(META_CAPABILITY_INTROSPECTION_SOURCE);
1143
+ function fieldNames(type) {
1144
+ return new Set((type?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []));
1145
+ }
1146
+ function emptyMetaCapabilities() {
1147
+ return Object.fromEntries(
1148
+ Object.keys(META_OPTIONAL_CAPABILITIES).map((alias) => [alias, /* @__PURE__ */ new Set()])
1149
+ );
1150
+ }
1151
+ function assessMetaCapabilities(result) {
1152
+ const compatibility = assessMetaContract(result);
1153
+ const capabilities = Object.fromEntries(
1154
+ Object.entries(META_OPTIONAL_CAPABILITIES).map(([alias, requirement]) => {
1155
+ const available = fieldNames(result?.[alias]);
1156
+ const fields = requirement.fields;
1157
+ return [alias, new Set(fields.filter((field2) => available.has(field2)))];
1158
+ })
1159
+ );
1160
+ return { compatibility, capabilities };
1161
+ }
1162
+ function has(capabilities, alias, field2) {
1163
+ return capabilities[alias].has(field2);
1164
+ }
1165
+ function present(capabilities, alias, fields) {
1166
+ return fields.filter((field2) => has(capabilities, alias, field2)).join(" ");
1167
+ }
1168
+ function fileSelection(capabilities) {
1169
+ if (!has(capabilities, "metaField", "file") || !has(capabilities, "metaFileField", "kind")) return "";
1170
+ return `file { ${present(capabilities, "metaFileField", ["kind", "isMultiple", "filesType"])} }`;
1171
+ }
1172
+ function uploadSelection(capabilities) {
1173
+ if (!has(capabilities, "metaStorage", "upload")) return "";
1174
+ const fields = present(capabilities, "metaStorageUpload", [
1175
+ "mutation",
1176
+ "inputType",
1177
+ "payloadType",
1178
+ "bulkMutation",
1179
+ "requiresOwnerId"
1180
+ ]);
1181
+ return fields ? `upload { ${fields} }` : "";
1182
+ }
1183
+ function buildMetaQuerySource(capabilities = emptyMetaCapabilities()) {
1184
+ const tableExtras = present(capabilities, "metaTable", ["kind", "description", "isJunction", "tableName"]);
1185
+ const typeExtras = present(capabilities, "metaType", ["maxLength", "precision", "scale"]);
1186
+ const tableFieldExtras = [
1187
+ present(capabilities, "metaField", [
1188
+ "allowedValues",
1189
+ "isRequiredOnCreate",
1190
+ "isWritableOnCreate",
1191
+ "isWritableOnUpdate",
1192
+ "isComputed"
1193
+ ]),
1194
+ fileSelection(capabilities)
1195
+ ].filter(Boolean).join(" ");
1196
+ const refKeys = has(capabilities, "metaBelongsTo", "refKeys") ? "refKeys { ...ConstructiveMetaField }" : "";
1197
+ const remoteKeys = has(capabilities, "metaHas", "remoteKeys") ? "remoteKeys { ...ConstructiveMetaField }" : "";
1198
+ const storageExtras = [
1199
+ present(capabilities, "metaStorage", ["filesType", "bucketsType", "downloadUrlField"]),
1200
+ uploadSelection(capabilities)
1201
+ ].filter(Boolean).join(" ");
1202
+ const hasRelation = (name) => (
1203
+ /* GraphQL */
1204
+ `
1205
+ ${name} {
1206
+ fieldName
1207
+ isUnique
1208
+ type
1209
+ keys { ...ConstructiveMetaField }
1210
+ referencedBy { name }
1211
+ ${remoteKeys}
1212
+ }`
1213
+ );
1214
+ return (
1215
+ /* GraphQL */
1216
+ `
1217
+ query ConstructiveMeta {
1218
+ _meta {
1219
+ tables {
1220
+ name
1221
+ schemaName
1222
+ ${tableExtras}
1223
+ query { all one create update delete }
1224
+ fields { ...ConstructiveMetaTableField }
1225
+ inflection {
1226
+ tableType
1227
+ allRows
1228
+ connection
1229
+ edge
1230
+ filterType
1231
+ orderByType
1232
+ conditionType
1233
+ patchType
1234
+ createInputType
1235
+ createPayloadType
1236
+ updatePayloadType
1237
+ deletePayloadType
1238
+ }
1239
+ indexes {
1240
+ name
1241
+ isUnique
1242
+ isPrimary
1243
+ columns
1244
+ fields { ...ConstructiveMetaField }
1245
+ }
1246
+ constraints {
1247
+ primaryKey { name fields { ...ConstructiveMetaField } }
1248
+ unique { name fields { ...ConstructiveMetaField } }
1249
+ foreignKey { ...ConstructiveMetaForeignKey }
1250
+ }
1251
+ foreignKeyConstraints { ...ConstructiveMetaForeignKey }
1252
+ primaryKeyConstraints { name fields { ...ConstructiveMetaField } }
1253
+ uniqueConstraints { name fields { ...ConstructiveMetaField } }
1254
+ relations {
1255
+ belongsTo {
1256
+ fieldName
1257
+ isUnique
1258
+ type
1259
+ keys { ...ConstructiveMetaField }
1260
+ references { name }
1261
+ ${refKeys}
1262
+ }${hasRelation("has")}${hasRelation("hasOne")}${hasRelation("hasMany")}
1263
+ manyToMany {
1264
+ fieldName
1265
+ type
1266
+ junctionTable { name }
1267
+ junctionLeftConstraint { ...ConstructiveMetaForeignKey }
1268
+ junctionLeftKeyAttributes { ...ConstructiveMetaField }
1269
+ junctionRightConstraint { ...ConstructiveMetaForeignKey }
1270
+ junctionRightKeyAttributes { ...ConstructiveMetaField }
1271
+ leftKeyAttributes { ...ConstructiveMetaField }
1272
+ rightKeyAttributes { ...ConstructiveMetaField }
1273
+ rightTable { name }
1274
+ }
1275
+ }
1276
+ storage { isFilesTable isBucketsTable ${storageExtras} }
1277
+ search {
1278
+ algorithms
1279
+ columns { name algorithm }
1280
+ hasUnifiedSearch
1281
+ config { weights boostRecent boostRecencyField boostRecencyDecay }
1282
+ }
1283
+ i18n { translationTable translatableFields { name type } }
1284
+ realtime { subscriptionFieldName }
1285
+ scope { scope tier keyColumn entityTable source }
1286
+ }
1287
+ }
1288
+ }
1289
+
1290
+ fragment ConstructiveMetaType on MetaType {
1291
+ pgType
1292
+ gqlType
1293
+ isArray
1294
+ isNotNull
1295
+ hasDefault
1296
+ subtype
1297
+ encoding {
1298
+ kind
1299
+ elementType
1300
+ dimensions
1301
+ geometrySubtype
1302
+ srid
1303
+ dotPath
1304
+ }
1305
+ ${typeExtras}
1306
+ }
1307
+
1308
+ fragment ConstructiveMetaField on MetaField {
1309
+ name
1310
+ type { ...ConstructiveMetaType }
1311
+ isNotNull
1312
+ hasDefault
1313
+ isPrimaryKey
1314
+ isForeignKey
1315
+ description
1316
+ enumValues { name values }
1317
+ }
1318
+
1319
+ fragment ConstructiveMetaTableField on MetaField {
1320
+ ...ConstructiveMetaField
1321
+ ${tableFieldExtras}
1322
+ }
1323
+
1324
+ fragment ConstructiveMetaForeignKey on MetaForeignKeyConstraint {
1325
+ name
1326
+ fields { ...ConstructiveMetaField }
1327
+ referencedTable
1328
+ referencedFields
1329
+ refFields { ...ConstructiveMetaField }
1330
+ refTable { name }
1331
+ }
1332
+ `
1333
+ );
1334
+ }
1335
+ function buildMetaDocument(capabilities = emptyMetaCapabilities()) {
1336
+ return new TypedDocumentString(buildMetaQuerySource(capabilities));
1337
+ }
1338
+
1339
+ // src/table-model/schema-introspection.ts
1340
+ var TYPE_REF_SELECTION = "kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } }";
1341
+ var NAMED_TYPE_FRAGMENT = (
1342
+ /* GraphQL */
1343
+ `
1344
+ fragment ConstructiveTypeRef on __Type { ${TYPE_REF_SELECTION} }
1345
+ fragment ConstructiveNamedType on __Type {
1346
+ kind
1347
+ name
1348
+ fields(includeDeprecated: true) {
1349
+ name
1350
+ args { name defaultValue type { ...ConstructiveTypeRef } }
1351
+ type { ...ConstructiveTypeRef }
1352
+ }
1353
+ inputFields { name defaultValue type { ...ConstructiveTypeRef } }
1354
+ enumValues(includeDeprecated: true) { name }
1355
+ }
1356
+ `
1357
+ );
1358
+ var SCHEMA_ROOTS_SOURCE = (
1359
+ /* GraphQL */
1360
+ `
1361
+ query ConstructiveSchemaRoots {
1362
+ __schema {
1363
+ queryType { ...ConstructiveNamedType }
1364
+ mutationType { ...ConstructiveNamedType }
1365
+ }
1366
+ }
1367
+ ${NAMED_TYPE_FRAGMENT}
1368
+ `
1369
+ );
1370
+ var TYPE_BATCH_SIZE = 80;
1371
+ function buildSchemaTypesSource(count) {
1372
+ const variables = Array.from({ length: count }, (_, index) => `$n${index}: String!`).join(", ");
1373
+ const lookups = Array.from(
1374
+ { length: count },
1375
+ (_, index) => `t${index}: __type(name: $n${index}) { ...ConstructiveNamedType }`
1376
+ ).join("\n ");
1377
+ return (
1378
+ /* GraphQL */
1379
+ `
1380
+ query ConstructiveSchemaTypes(${variables}) {
1381
+ ${lookups}
1382
+ }
1383
+ ${NAMED_TYPE_FRAGMENT}
1384
+ `
1385
+ );
1386
+ }
1387
+ function namedTypeOf(ref) {
1388
+ let current = ref ?? null;
1389
+ while (current && (current.kind === "NON_NULL" || current.kind === "LIST")) current = current.ofType;
1390
+ return current?.name ? { kind: current.kind, name: current.name } : null;
1391
+ }
1392
+ function isListTypeRef(ref) {
1393
+ let current = ref ?? null;
1394
+ while (current) {
1395
+ if (current.kind === "LIST") return true;
1396
+ current = current.ofType;
1397
+ }
1398
+ return false;
1399
+ }
1400
+ function isNonNullTypeRef(ref) {
1401
+ return ref?.kind === "NON_NULL";
1402
+ }
1403
+ function printTypeRef(ref) {
1404
+ if (ref.kind === "NON_NULL") return ref.ofType ? `${printTypeRef(ref.ofType)}!` : "";
1405
+ if (ref.kind === "LIST") return ref.ofType ? `[${printTypeRef(ref.ofType)}]` : "";
1406
+ return ref.name ?? "";
1407
+ }
1408
+ function isRequiredInput(value) {
1409
+ return isNonNullTypeRef(value.type) && value.defaultValue == null;
1410
+ }
1411
+ var GRAPHQL_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
1412
+ function createSchemaTypeLoader() {
1413
+ const types = /* @__PURE__ */ new Map();
1414
+ const pending = /* @__PURE__ */ new Map();
1415
+ let roots = null;
1416
+ let rootsPromise = null;
1417
+ const index = {
1418
+ get roots() {
1419
+ return roots;
1420
+ },
1421
+ get(name) {
1422
+ return types.has(name) ? types.get(name) ?? null : void 0;
1423
+ }
1424
+ };
1425
+ function remember(type) {
1426
+ if (type?.name) types.set(type.name, type);
1427
+ }
1428
+ async function fetchBatch(execute2, names2) {
1429
+ const variables = Object.fromEntries(names2.map((name, position) => [`n${position}`, name]));
1430
+ const response = await execute2(buildSchemaTypesSource(names2.length), variables);
1431
+ names2.forEach((name, position) => {
1432
+ const type = response?.[`t${position}`] ?? null;
1433
+ types.set(name, type && type.name === name ? type : null);
1434
+ });
1435
+ }
1436
+ return {
1437
+ index,
1438
+ wasRequested(name) {
1439
+ return types.has(name) || pending.has(name);
1440
+ },
1441
+ loadRoots(execute2) {
1442
+ if (roots) return Promise.resolve(roots);
1443
+ if (rootsPromise) return rootsPromise;
1444
+ const request = execute2(SCHEMA_ROOTS_SOURCE).then((response) => {
1445
+ const loaded = {
1446
+ query: response?.__schema?.queryType ?? null,
1447
+ mutation: response?.__schema?.mutationType ?? null
1448
+ };
1449
+ remember(loaded.query);
1450
+ remember(loaded.mutation);
1451
+ roots = loaded;
1452
+ return loaded;
1453
+ });
1454
+ rootsPromise = request;
1455
+ request.catch(() => {
1456
+ if (rootsPromise === request) rootsPromise = null;
1457
+ });
1458
+ return request;
1459
+ },
1460
+ async loadTypes(execute2, names2) {
1461
+ const wanted = [...new Set(names2)].filter((name) => GRAPHQL_NAME.test(name));
1462
+ const fresh = wanted.filter((name) => !types.has(name) && !pending.has(name));
1463
+ const inFlight = wanted.flatMap((name) => {
1464
+ const promise = pending.get(name);
1465
+ return promise ? [promise] : [];
1466
+ });
1467
+ const batches = [];
1468
+ for (let start = 0; start < fresh.length; start += TYPE_BATCH_SIZE) {
1469
+ const batch = fresh.slice(start, start + TYPE_BATCH_SIZE);
1470
+ const request = fetchBatch(execute2, batch).finally(() => {
1471
+ for (const name of batch) if (pending.get(name) === request) pending.delete(name);
1472
+ });
1473
+ for (const name of batch) pending.set(name, request);
1474
+ batches.push(request);
1475
+ }
1476
+ await Promise.all([...batches, ...inFlight]);
1477
+ }
1478
+ };
1479
+ }
1480
+
1481
+ // src/table-model/table-key.ts
1482
+ var TableModelError = class extends Error {
1483
+ code;
1484
+ /** The table the error concerns, when known. */
1485
+ tableKey;
1486
+ /** Table keys that matched an ambiguous name. */
1487
+ candidates;
1488
+ constructor(code, message, options = {}) {
1489
+ super(message);
1490
+ this.name = "TableModelError";
1491
+ this.code = code;
1492
+ this.tableKey = options.tableKey ?? null;
1493
+ this.candidates = options.candidates ?? [];
1494
+ }
1495
+ };
1496
+ function tableKeyOf(table) {
1497
+ return `${table.schemaName ?? ""}.${table.name}`;
1498
+ }
1499
+ function metaTablesOf(meta) {
1500
+ return (meta?._meta?.tables ?? []).filter((table) => Boolean(table?.name));
1501
+ }
1502
+ function findMetaTable(tables, ref) {
1503
+ const byKey = tables.find((table) => tableKeyOf(table) === ref);
1504
+ if (byKey) return byKey;
1505
+ const byName = tables.filter((table) => table.name === ref);
1506
+ if (byName.length === 1) return byName[0];
1507
+ if (byName.length > 1) {
1508
+ const candidates = byName.map(tableKeyOf);
1509
+ throw new TableModelError(
1510
+ "TABLE_AMBIGUOUS",
1511
+ `More than one table is called "${ref}". Choose one of: ${candidates.join(", ")}.`,
1512
+ { candidates }
1513
+ );
1514
+ }
1515
+ throw new TableModelError("TABLE_NOT_FOUND", `There is no table called "${ref}".`);
1516
+ }
1517
+ function tableKeyForName(tables, name) {
1518
+ if (!name) return null;
1519
+ const matches = tables.filter((table) => table.name === name);
1520
+ return matches.length === 1 ? tableKeyOf(matches[0]) : null;
1521
+ }
1522
+
1523
+ // src/row-identity.ts
1524
+ function primaryKeyColumnNames(table) {
1525
+ const constraints = table.constraints;
1526
+ if (constraints && !Array.isArray(constraints)) {
1527
+ const names2 = (constraints.primaryKey?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1528
+ if (names2.length > 0) return [...new Set(names2)];
1529
+ }
1530
+ for (const constraint of table.primaryKeyConstraints ?? []) {
1531
+ const names2 = (constraint?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1532
+ if (names2.length > 0) return [...new Set(names2)];
1533
+ }
1534
+ return [...new Set(
1535
+ (table.fields ?? []).flatMap((field2) => field2?.isPrimaryKey && field2.name ? [field2.name] : [])
1536
+ )];
1537
+ }
1538
+ function isRowIdentityValue(value) {
1539
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1540
+ if (typeof value === "number") return Number.isFinite(value);
1541
+ if (Array.isArray(value)) return value.every(isRowIdentityValue);
1542
+ if (typeof value !== "object" || value === null) return false;
1543
+ const prototype = Object.getPrototypeOf(value);
1544
+ if (prototype !== Object.prototype && prototype !== null) return false;
1545
+ return Object.values(value).every(isRowIdentityValue);
1546
+ }
1547
+ function sortIdentityValue(value) {
1548
+ if (Array.isArray(value)) return value.map(sortIdentityValue);
1549
+ if (typeof value !== "object" || value === null) return value;
1550
+ return Object.fromEntries(
1551
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortIdentityValue(item)])
1552
+ );
1553
+ }
1554
+ function getRowIdentityDefinition(table) {
1555
+ const schemaName = table.schemaName ?? null;
1556
+ const columnNames = primaryKeyColumnNames(table);
1557
+ if (columnNames.length === 0) {
1558
+ return {
1559
+ status: "read-only",
1560
+ schemaName,
1561
+ tableName: table.name,
1562
+ reason: "no-primary-key"
1563
+ };
1564
+ }
1565
+ return {
1566
+ status: "keyed",
1567
+ schemaName,
1568
+ tableName: table.name,
1569
+ fields: columnNames.map((columnName) => ({
1570
+ columnName,
1571
+ // `_meta` exposes GraphQL field names here (already inflected), so using
1572
+ // them verbatim also handles custom/renamed primary keys.
1573
+ fieldName: columnName
1574
+ }))
1575
+ };
1576
+ }
1577
+ function resolveRowIdentity(table, row) {
1578
+ const definition = getRowIdentityDefinition(table);
1579
+ if (definition.status === "read-only") return definition;
1580
+ const missingFields = [];
1581
+ const invalidFields = [];
1582
+ const fields = [];
1583
+ for (const field2 of definition.fields) {
1584
+ if (!Object.prototype.hasOwnProperty.call(row, field2.fieldName)) {
1585
+ missingFields.push(field2.fieldName);
1586
+ continue;
1587
+ }
1588
+ const value = row[field2.fieldName];
1589
+ if (value === null || !isRowIdentityValue(value)) {
1590
+ invalidFields.push(field2.fieldName);
1591
+ continue;
1592
+ }
1593
+ fields.push({ ...field2, value });
1594
+ }
1595
+ if (missingFields.length > 0 || invalidFields.length > 0) {
1596
+ return {
1597
+ status: "invalid-row",
1598
+ schemaName: definition.schemaName,
1599
+ tableName: definition.tableName,
1600
+ missingFields,
1601
+ invalidFields
1602
+ };
1603
+ }
1604
+ return {
1605
+ status: "identified",
1606
+ identity: {
1607
+ schemaName: definition.schemaName,
1608
+ tableName: definition.tableName,
1609
+ fields
1610
+ }
1611
+ };
1612
+ }
1613
+ function serializeRowIdentity(identity) {
1614
+ return JSON.stringify([
1615
+ identity.schemaName,
1616
+ identity.tableName,
1617
+ identity.fields.map((field2) => [
1618
+ field2.columnName,
1619
+ field2.fieldName,
1620
+ sortIdentityValue(field2.value)
1621
+ ])
1622
+ ]);
1623
+ }
1624
+ function rowIdentityToPrimaryKey(identity) {
1625
+ return Object.fromEntries(
1626
+ identity.fields.map((field2) => [field2.fieldName, field2.value])
1627
+ );
1628
+ }
1629
+ function assessTableWriteCapability(table) {
1630
+ const definition = getRowIdentityDefinition(table);
1631
+ if (definition.status === "read-only") return definition;
1632
+ return {
1633
+ status: "mutable",
1634
+ primaryKeyFields: definition.fields.map((field2) => field2.fieldName),
1635
+ operations: {
1636
+ create: Boolean(table.query?.create),
1637
+ update: Boolean(table.query?.update),
1638
+ delete: Boolean(table.query?.delete)
1639
+ }
1640
+ };
1641
+ }
1642
+
1643
+ // src/table-model/names.ts
1644
+ function canonicalName(value) {
1645
+ return value.replace(/[^A-Za-z0-9]/g, "").toLowerCase();
1646
+ }
1647
+
1648
+ // src/table-model/selection.ts
1649
+ var MAX_SELECTION_DEPTH = 3;
1650
+ function buildOutputSelection(type, lookup, options = {}, depth = 0) {
1651
+ if (!type || type.kind !== "OBJECT" && type.kind !== "INTERFACE") return null;
1652
+ const parts = type.kind === "INTERFACE" ? ["__typename"] : [];
1653
+ for (const field2 of type.fields ?? []) {
1654
+ if (field2.args.some(isRequiredInput)) continue;
1655
+ const named = namedTypeOf(field2.type);
1656
+ if (!named) continue;
1657
+ if (named.kind === "SCALAR" || named.kind === "ENUM") {
1658
+ parts.push(field2.name);
1659
+ continue;
1660
+ }
1661
+ if (options.leavesOnly || depth + 1 >= MAX_SELECTION_DEPTH) continue;
1662
+ if (named.kind !== "OBJECT" && named.kind !== "INTERFACE") continue;
1663
+ const nested = buildOutputSelection(lookup.type(named.name), lookup, options, depth + 1);
1664
+ if (nested) parts.push(`${field2.name} ${nested}`);
1665
+ }
1666
+ return parts.some((part) => part !== "__typename") ? `{ ${parts.join(" ")} }` : null;
1667
+ }
1668
+
1669
+ // src/table-model/value-kind.ts
1670
+ var KIND_BY_ENCODING = {
1671
+ datetime: "datetime",
1672
+ date: "date",
1673
+ time: "time",
1674
+ interval: "interval",
1675
+ uuid: "uuid",
1676
+ geojson: "geometry",
1677
+ point: "point",
1678
+ inet: "network",
1679
+ ltree: "path",
1680
+ vector: "vector",
1681
+ bytea: "binary",
1682
+ composite: "composite"
1683
+ };
1684
+ var KIND_BY_CODEC = {
1685
+ tsvector: "fulltext",
1686
+ bit: "bitstring",
1687
+ varbit: "bitstring",
1688
+ macaddr: "network",
1689
+ macaddr8: "network",
1690
+ json: "json",
1691
+ jsonb: "json",
1692
+ email: "text",
1693
+ url: "text",
1694
+ hostname: "text",
1695
+ origin: "text"
1696
+ };
1697
+ var KIND_BY_SCALAR = {
1698
+ String: "text",
1699
+ ID: "text",
1700
+ Int: "integer",
1701
+ Float: "float",
1702
+ Boolean: "boolean",
1703
+ UUID: "uuid",
1704
+ JSON: "json",
1705
+ BigInt: "bigint",
1706
+ BigFloat: "decimal",
1707
+ Datetime: "datetime",
1708
+ Date: "date",
1709
+ Time: "time",
1710
+ GeoJSON: "geometry",
1711
+ InternetAddress: "network",
1712
+ CidrAddress: "network",
1713
+ MacAddress: "network",
1714
+ LTree: "path",
1715
+ FullText: "fulltext",
1716
+ BitString: "bitstring",
1717
+ Base64EncodedBinary: "binary"
1718
+ };
1719
+ var SEMANTIC_DOMAINS = /* @__PURE__ */ new Set([
1720
+ "email",
1721
+ "url",
1722
+ "hostname",
1723
+ "origin",
1724
+ "image",
1725
+ "upload",
1726
+ "attachment",
1727
+ "currency"
1728
+ ]);
1729
+ var FILE_DOMAINS = /* @__PURE__ */ new Set(["image", "upload", "attachment"]);
1730
+ function elementCodecName(field2) {
1731
+ const pgType = field2.type.pgType ?? "";
1732
+ return field2.type.isArray && pgType.endsWith("Array") ? pgType.slice(0, -"Array".length) : pgType;
1733
+ }
1734
+ var INTEGER_BOUNDS = {
1735
+ int2: { min: -32768, max: 32767 },
1736
+ int4: { min: -2147483648, max: 2147483647 }
1737
+ };
1738
+ function integerBoundsOf(field2) {
1739
+ return INTEGER_BOUNDS[elementCodecName(field2)] ?? null;
1740
+ }
1741
+ function isRangeType(type, lookup) {
1742
+ if (!type || type.kind !== "OBJECT") return false;
1743
+ const names2 = new Set((type.fields ?? []).map((field2) => field2.name));
1744
+ if (names2.size !== 2 || !names2.has("start") || !names2.has("end")) return false;
1745
+ return ["start", "end"].every((bound) => {
1746
+ const boundType = lookup.typeOf(lookup.field(type, bound)?.type);
1747
+ const boundFields = new Set((boundType?.fields ?? []).map((field2) => field2.name));
1748
+ return boundFields.has("value") && boundFields.has("inclusive");
1749
+ });
1750
+ }
1751
+ function columnFile(field2) {
1752
+ const meta = field2.file;
1753
+ if (meta?.kind && FILE_DOMAINS.has(meta.kind)) {
1754
+ return {
1755
+ kind: meta.kind,
1756
+ multiple: meta.isMultiple ?? field2.type.isArray,
1757
+ filesType: meta.filesType ?? null
1758
+ };
1759
+ }
1760
+ const codec = elementCodecName(field2);
1761
+ if (!FILE_DOMAINS.has(codec)) return null;
1762
+ return { kind: codec, multiple: field2.type.isArray, filesType: null };
1763
+ }
1764
+ function columnSemantic(field2, file) {
1765
+ if (file) return file.kind;
1766
+ const codec = elementCodecName(field2);
1767
+ if (codec === "money") return "currency";
1768
+ return SEMANTIC_DOMAINS.has(codec) ? codec : null;
1769
+ }
1770
+ function columnValueKind(field2, outputType, file, lookup) {
1771
+ if (file) return "file";
1772
+ if (outputType?.kind === "ENUM" || field2.enumValues?.name) return "enum";
1773
+ const encoding = field2.type.encoding?.kind;
1774
+ if (encoding === "bigint") return field2.type.gqlType === "BigFloat" ? "decimal" : "bigint";
1775
+ if (encoding && KIND_BY_ENCODING[encoding]) return KIND_BY_ENCODING[encoding];
1776
+ if (isRangeType(outputType, lookup)) return "range";
1777
+ const codecKind = KIND_BY_CODEC[elementCodecName(field2)];
1778
+ if (codecKind) return codecKind;
1779
+ const scalarName = outputType?.kind === "SCALAR" ? outputType.name : field2.type.gqlType;
1780
+ return KIND_BY_SCALAR[scalarName] ?? "unknown";
1781
+ }
1782
+
1783
+ // src/table-model/build-columns.ts
1784
+ var UNREADABLE = "This field cannot be shown here yet.";
1785
+ var UNSUPPORTED_WRITE = "This kind of value cannot be edited here yet.";
1786
+ var COMPUTED = "This value is calculated automatically.";
1787
+ function sortIndex(orderByType) {
1788
+ const index = /* @__PURE__ */ new Map();
1789
+ for (const { name } of orderByType?.enumValues ?? []) {
1790
+ const match = /^(.*)_(ASC|DESC)$/.exec(name);
1791
+ if (!match) continue;
1792
+ const key = canonicalName(match[1]);
1793
+ const entry = index.get(key) ?? { asc: [], desc: [] };
1794
+ (match[2] === "ASC" ? entry.asc : entry.desc).push(name);
1795
+ index.set(key, entry);
1796
+ }
1797
+ return index;
1798
+ }
1799
+ function columnSort(name, index) {
1800
+ const entry = index.get(canonicalName(name));
1801
+ return entry && entry.asc.length === 1 && entry.desc.length === 1 ? { asc: entry.asc[0], desc: entry.desc[0] } : null;
1802
+ }
1803
+ function columnFilter(name, filterType, lookup) {
1804
+ const field2 = filterType?.inputFields?.find((input) => input.name === name);
1805
+ const named = namedTypeOf(field2?.type);
1806
+ if (!field2 || named?.kind !== "INPUT_OBJECT") return null;
1807
+ const operatorType = lookup.type(named.name);
1808
+ if (!operatorType) return null;
1809
+ const operators = [];
1810
+ for (const operator of operatorType.inputFields ?? []) {
1811
+ const input = lookup.inputValue(operator.type);
1812
+ if (input) operators.push({ name: operator.name, input });
1813
+ }
1814
+ return operators.length > 0 ? { field: field2.name, typeName: named.name, operators } : null;
1815
+ }
1816
+ function prettyEnumLabel(value) {
1817
+ const words = value.replace(/^_+/, "").replace(/_+/g, " ").trim().toLowerCase();
1818
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : value;
1819
+ }
1820
+ function enumOptions(field2, enumType) {
1821
+ const values = (enumType?.enumValues ?? []).map((value) => value.name);
1822
+ if (values.length === 0) return null;
1823
+ const labels = field2.enumValues?.values ?? [];
1824
+ const byPosition = labels.length === values.length;
1825
+ return values.map((value, position) => ({ value, label: byPosition ? labels[position] : prettyEnumLabel(value) }));
1826
+ }
1827
+ function inputField(type, name) {
1828
+ return type?.inputFields?.find((field2) => field2.name === name) ?? null;
1829
+ }
1830
+ function columnWrite(field2, ctx, readable, hasInputShape) {
1831
+ const recordField = inputField(ctx.recordType, field2.name);
1832
+ const patchField = inputField(ctx.patchType, field2.name);
1833
+ const reasonFor = (operationExists, inInput, metaAllows, noOperation, notInInput) => {
1834
+ if (!operationExists) return noOperation;
1835
+ if (field2.isComputed === true) return COMPUTED;
1836
+ if (!inInput || metaAllows === false) return notInInput;
1837
+ if (!readable || !hasInputShape) return UNSUPPORTED_WRITE;
1838
+ return null;
1839
+ };
1840
+ const createReason = reasonFor(
1841
+ Boolean(ctx.operations.create),
1842
+ Boolean(recordField),
1843
+ field2.isWritableOnCreate,
1844
+ "This table does not allow adding records.",
1845
+ "This field is filled in automatically when a record is added."
1846
+ );
1847
+ const updateReason = reasonFor(
1848
+ Boolean(ctx.operations.update),
1849
+ Boolean(patchField),
1850
+ field2.isWritableOnUpdate,
1851
+ "This table does not allow changes.",
1852
+ "This field cannot be changed."
1853
+ );
1854
+ const create = createReason === null;
1855
+ return {
1856
+ create,
1857
+ update: updateReason === null,
1858
+ requiredOnCreate: create && ((recordField ? isRequiredInput(recordField) : false) || field2.isRequiredOnCreate === true),
1859
+ createReason,
1860
+ updateReason
1861
+ };
1862
+ }
1863
+ function buildColumn(field2, ctx, sorts) {
1864
+ const { lookup } = ctx;
1865
+ const rowField = lookup.field(ctx.rowType, field2.name);
1866
+ const named = namedTypeOf(rowField?.type);
1867
+ const isObject2 = named?.kind === "OBJECT" || named?.kind === "INTERFACE";
1868
+ const outputType = !named ? null : named.kind === "SCALAR" ? { kind: "SCALAR", name: named.name, fields: null, inputFields: null, enumValues: null } : lookup.type(named.name);
1869
+ const file = columnFile(field2);
1870
+ const kind = columnValueKind(field2, outputType, file, lookup);
1871
+ const selection = isObject2 ? buildOutputSelection(outputType, lookup, { leavesOnly: kind === "geometry" }) : null;
1872
+ const readReason = !rowField ? "This field is not available through this API." : rowField.args.some(isRequiredInput) || named?.kind === "UNION" || isObject2 && !selection ? UNREADABLE : null;
1873
+ const readable = readReason === null;
1874
+ const inputRef = (inputField(ctx.patchType, field2.name) ?? inputField(ctx.recordType, field2.name))?.type;
1875
+ const input = inputRef ? lookup.inputValue(inputRef) : null;
1876
+ const write = columnWrite(field2, ctx, readable, input !== null);
1877
+ const options = kind === "enum" ? enumOptions(field2, outputType?.kind === "ENUM" ? outputType : null) : field2.allowedValues?.length ? field2.allowedValues.map((value) => ({ value, label: value })) : null;
1878
+ const encoding = field2.type.encoding;
1879
+ return {
1880
+ name: field2.name,
1881
+ description: field2.description ?? null,
1882
+ value: {
1883
+ kind,
1884
+ isArray: field2.type.isArray,
1885
+ typeName: named?.name ?? field2.type.gqlType,
1886
+ semantic: columnSemantic(field2, file),
1887
+ options,
1888
+ selection,
1889
+ input,
1890
+ maxLength: field2.type.maxLength ?? null,
1891
+ precision: field2.type.precision ?? null,
1892
+ scale: field2.type.scale ?? null,
1893
+ integerBounds: kind === "integer" ? integerBoundsOf(field2) : null,
1894
+ dimensions: encoding?.dimensions ?? null,
1895
+ geometrySubtype: encoding?.geometrySubtype ?? field2.type.subtype ?? null,
1896
+ srid: encoding?.srid ?? null,
1897
+ file
1898
+ },
1899
+ nullable: !(field2.isNotNull ?? field2.type.isNotNull ?? false),
1900
+ hasDefault: Boolean(field2.hasDefault ?? field2.type.hasDefault),
1901
+ isPrimaryKey: ctx.primaryKey.includes(field2.name) || field2.isPrimaryKey === true,
1902
+ isForeignKey: field2.isForeignKey === true,
1903
+ readable,
1904
+ readReason,
1905
+ write,
1906
+ sort: readable ? columnSort(field2.name, sorts) : null,
1907
+ filter: readable ? columnFilter(field2.name, ctx.filterType, lookup) : null
1908
+ };
1909
+ }
1910
+ function buildColumns(ctx) {
1911
+ const sorts = sortIndex(ctx.orderByType);
1912
+ return ctx.fields.map((field2) => {
1913
+ const column = buildColumn(field2, ctx, sorts);
1914
+ if (column.readReason) {
1915
+ ctx.issues.push({ scope: "column", target: column.name, code: "COLUMN_UNREADABLE", message: column.readReason });
1916
+ } else if (column.write.updateReason === UNSUPPORTED_WRITE || column.write.createReason === UNSUPPORTED_WRITE) {
1917
+ ctx.issues.push({ scope: "column", target: column.name, code: "COLUMN_UNWRITABLE", message: UNSUPPORTED_WRITE });
1918
+ }
1919
+ return column;
1920
+ });
1921
+ }
1922
+
1923
+ // src/table-model/build-operations.ts
1924
+ var CLIENT_MUTATION_ID = "clientMutationId";
1925
+ var LOGICAL_OPERATORS = ["and", "or", "not"];
1926
+ var PAGE_INFO_FIELDS = ["hasNextPage", "hasPreviousPage", "startCursor", "endCursor"];
1927
+ function argumentModel(value) {
1928
+ const named = namedTypeOf(value.type);
1929
+ return named ? { name: value.name, type: printTypeRef(value.type), typeName: named.name } : null;
1930
+ }
1931
+ function operationIssue(issues, target, code, message) {
1932
+ issues.push({ scope: "operation", target, code, message });
1933
+ }
1934
+ function mutationInput(field2) {
1935
+ if (field2.args.length === 1) return field2.args[0];
1936
+ return field2.args.find((arg) => arg.name === "input") ?? null;
1937
+ }
1938
+ function payloadRowField(lookup, field2, rowTypeName) {
1939
+ const payload = lookup.typeOf(field2.type);
1940
+ const matches = (payload?.fields ?? []).filter(
1941
+ (candidate) => !isListTypeRef(candidate.type) && namedTypeOf(candidate.type)?.name === rowTypeName
1942
+ );
1943
+ return matches.length === 1 ? matches[0].name : null;
1944
+ }
1945
+ function recordFields(inputType) {
1946
+ return (inputType?.inputFields ?? []).filter(
1947
+ (field2) => field2.name !== CLIENT_MUTATION_ID && isNonNullTypeRef(field2.type) && namedTypeOf(field2.type)?.kind === "INPUT_OBJECT"
1948
+ );
1949
+ }
1950
+ function keyArguments(inputType, excluded, primaryKey) {
1951
+ const keys = (inputType?.inputFields ?? []).filter(
1952
+ (field2) => field2.name !== CLIENT_MUTATION_ID && !excluded.has(field2.name) && isNonNullTypeRef(field2.type)
1953
+ );
1954
+ const names2 = new Set(keys.map((field2) => field2.name));
1955
+ if (primaryKey.length === 0 || names2.size !== primaryKey.length) return null;
1956
+ return primaryKey.every((name) => names2.has(name)) ? [...primaryKey] : null;
1957
+ }
1958
+ function createRecordOf(table, roots, lookup) {
1959
+ const name = table.query?.create;
1960
+ const field2 = name ? lookup.field(roots.mutation, name) : null;
1961
+ const input = field2 ? mutationInput(field2) : null;
1962
+ if (!field2 || !input) return null;
1963
+ const records = recordFields(lookup.typeOf(input.type));
1964
+ if (records.length !== 1) return null;
1965
+ return { field: field2, input, recordField: records[0], recordType: lookup.typeOf(records[0].type) };
1966
+ }
1967
+ function buildList(ctx) {
1968
+ const { table, roots, lookup, issues } = ctx;
1969
+ const none = { list: null, filterType: null, orderByType: null };
1970
+ const field2 = table.query?.all ? lookup.field(roots.query, table.query.all) : null;
1971
+ if (!field2) {
1972
+ operationIssue(issues, "list", "LIST_UNAVAILABLE", "This table cannot be read through this API.");
1973
+ return none;
1974
+ }
1975
+ const returned = namedTypeOf(field2.type);
1976
+ let shape = null;
1977
+ let connection = null;
1978
+ if (returned?.name === table.name && isListTypeRef(field2.type)) {
1979
+ shape = "list";
1980
+ } else if (returned?.kind === "OBJECT") {
1981
+ connection = lookup.type(returned.name);
1982
+ const nodes = lookup.field(connection, "nodes");
1983
+ if (namedTypeOf(nodes?.type)?.name === table.name && isListTypeRef(nodes?.type)) shape = "connection";
1984
+ }
1985
+ if (!shape) {
1986
+ operationIssue(issues, "list", "LIST_UNAVAILABLE", "The list of records for this table has an unexpected shape.");
1987
+ return none;
1988
+ }
1989
+ const pageInfoType = lookup.typeOf(lookup.field(connection, "pageInfo")?.type);
1990
+ const pageInfo = PAGE_INFO_FIELDS.every((name) => lookup.field(pageInfoType, name) !== null);
1991
+ const filterArgs = field2.args.filter((arg) => {
1992
+ if (namedTypeOf(arg.type)?.kind !== "INPUT_OBJECT") return false;
1993
+ const inputs = lookup.typeOf(arg.type)?.inputFields ?? [];
1994
+ return inputs.some((input) => LOGICAL_OPERATORS.includes(input.name));
1995
+ });
1996
+ const orderByArgs = field2.args.filter(
1997
+ (arg) => isListTypeRef(arg.type) && namedTypeOf(arg.type)?.kind === "ENUM"
1998
+ );
1999
+ const filterArg = filterArgs.length === 1 ? filterArgs[0] : null;
2000
+ const orderByArg = orderByArgs.length === 1 ? orderByArgs[0] : null;
2001
+ const filterType = filterArg ? lookup.typeOf(filterArg.type) : null;
2002
+ const orderByType = orderByArg ? lookup.typeOf(orderByArg.type) : null;
2003
+ const pagingArg = (name, typeName) => {
2004
+ const arg = field2.args.find((candidate) => candidate.name === name);
2005
+ if (!arg || typeName && namedTypeOf(arg.type)?.name !== typeName) return null;
2006
+ return argumentModel(arg);
2007
+ };
2008
+ const filterFields = new Set((filterType?.inputFields ?? []).map((input) => input.name));
2009
+ return {
2010
+ list: {
2011
+ field: field2.name,
2012
+ shape,
2013
+ filter: filterArg ? argumentModel(filterArg) : null,
2014
+ orderBy: orderByArg ? argumentModel(orderByArg) : null,
2015
+ first: pagingArg("first", "Int"),
2016
+ offset: pagingArg("offset", "Int"),
2017
+ after: shape === "connection" ? pagingArg("after") : null,
2018
+ totalCount: shape === "connection" && Boolean(lookup.field(connection, "totalCount")),
2019
+ pageInfo: shape === "connection" && pageInfo,
2020
+ logicalOperators: LOGICAL_OPERATORS.filter((name) => filterFields.has(name))
2021
+ },
2022
+ filterType,
2023
+ orderByType
2024
+ };
2025
+ }
2026
+ function buildCreate(ctx) {
2027
+ const { table, roots, lookup, issues } = ctx;
2028
+ if (!table.query?.create) {
2029
+ operationIssue(issues, "create", "CREATE_UNAVAILABLE", "New records cannot be added to this table.");
2030
+ return { create: null, recordType: null };
2031
+ }
2032
+ const record = createRecordOf(table, roots, lookup);
2033
+ const argument2 = record ? argumentModel(record.input) : null;
2034
+ const payloadField = record ? payloadRowField(lookup, record.field, table.name) : null;
2035
+ const recordTypeName = record ? namedTypeOf(record.recordField.type)?.name : null;
2036
+ if (!record || !argument2 || !payloadField || !recordTypeName) {
2037
+ operationIssue(
2038
+ issues,
2039
+ "create",
2040
+ "CREATE_UNAVAILABLE",
2041
+ "Adding records is turned off because the add operation for this table has an unexpected shape."
2042
+ );
2043
+ return { create: null, recordType: null };
2044
+ }
2045
+ return {
2046
+ create: {
2047
+ field: record.field.name,
2048
+ input: argument2,
2049
+ recordField: record.recordField.name,
2050
+ recordType: recordTypeName,
2051
+ payloadField
2052
+ },
2053
+ recordType: record.recordType
2054
+ };
2055
+ }
2056
+ function noKeyReason(table, action) {
2057
+ return table.kind === "view" ? `This is a view of other tables, so its records cannot be ${action} here.` : `Records in this table cannot be ${action} because the table has no primary key.`;
2058
+ }
2059
+ function buildUpdate(ctx) {
2060
+ const { table, roots, lookup, issues, primaryKey } = ctx;
2061
+ if (!table.query?.update || primaryKey.length === 0) {
2062
+ operationIssue(
2063
+ issues,
2064
+ "update",
2065
+ "UPDATE_UNAVAILABLE",
2066
+ primaryKey.length === 0 ? noKeyReason(table, "changed") : "Records in this table cannot be changed."
2067
+ );
2068
+ return { update: null, patchType: null };
2069
+ }
2070
+ const field2 = lookup.field(roots.mutation, table.query.update);
2071
+ const input = field2 ? mutationInput(field2) : null;
2072
+ const inputType = input ? lookup.typeOf(input.type) : null;
2073
+ const patches = recordFields(inputType);
2074
+ const patch = patches.length === 1 ? patches[0] : null;
2075
+ const keyArgs = patch ? keyArguments(inputType, /* @__PURE__ */ new Set([patch.name]), primaryKey) : null;
2076
+ const argument2 = input ? argumentModel(input) : null;
2077
+ const payloadField = field2 ? payloadRowField(lookup, field2, table.name) : null;
2078
+ const patchTypeName = patch ? namedTypeOf(patch.type)?.name : null;
2079
+ if (!field2 || !argument2 || !patch || !keyArgs || !payloadField || !patchTypeName) {
2080
+ operationIssue(
2081
+ issues,
2082
+ "update",
2083
+ "UPDATE_UNAVAILABLE",
2084
+ "Changing records is turned off because the update operation for this table does not match its primary key."
2085
+ );
2086
+ return { update: null, patchType: null };
2087
+ }
2088
+ return {
2089
+ update: { field: field2.name, input: argument2, patchField: patch.name, patchType: patchTypeName, keyArgs, payloadField },
2090
+ patchType: lookup.typeOf(patch.type)
2091
+ };
2092
+ }
2093
+ function buildDelete(ctx) {
2094
+ const { table, roots, lookup, issues, primaryKey } = ctx;
2095
+ if (!table.query?.delete || primaryKey.length === 0) {
2096
+ operationIssue(
2097
+ issues,
2098
+ "delete",
2099
+ "DELETE_UNAVAILABLE",
2100
+ primaryKey.length === 0 ? noKeyReason(table, "deleted") : "Records in this table cannot be deleted."
2101
+ );
2102
+ return null;
2103
+ }
2104
+ const field2 = lookup.field(roots.mutation, table.query.delete);
2105
+ const input = field2 ? mutationInput(field2) : null;
2106
+ const keyArgs = input ? keyArguments(lookup.typeOf(input.type), /* @__PURE__ */ new Set(), primaryKey) : null;
2107
+ const argument2 = input ? argumentModel(input) : null;
2108
+ if (!field2 || !argument2 || !keyArgs) {
2109
+ operationIssue(
2110
+ issues,
2111
+ "delete",
2112
+ "DELETE_UNAVAILABLE",
2113
+ "Deleting records is turned off because the delete operation for this table does not match its primary key."
2114
+ );
2115
+ return null;
2116
+ }
2117
+ return { field: field2.name, input: argument2, keyArgs, payloadField: payloadRowField(lookup, field2, table.name) };
2118
+ }
2119
+ function buildOperations(ctx) {
2120
+ const { list, filterType, orderByType } = buildList(ctx);
2121
+ const { create, recordType } = buildCreate(ctx);
2122
+ const { update, patchType } = buildUpdate(ctx);
2123
+ return {
2124
+ operations: { list, create, update, delete: buildDelete(ctx) },
2125
+ recordType,
2126
+ patchType,
2127
+ filterType,
2128
+ orderByType
2129
+ };
2130
+ }
2131
+
2132
+ // src/table-model/display-fields.ts
2133
+ var NAME_FIELDS = [
2134
+ "displayName",
2135
+ "fullName",
2136
+ "name",
2137
+ "title",
2138
+ "label",
2139
+ "preferredName",
2140
+ "nickname",
2141
+ "username",
2142
+ "handle",
2143
+ "email",
2144
+ "firstName",
2145
+ "lastName",
2146
+ "givenName",
2147
+ "familyName",
2148
+ "slug",
2149
+ "code",
2150
+ "phone",
2151
+ "description"
2152
+ ];
2153
+ var NAME_LIKE = /(name|title|label|display)/i;
2154
+ var MAX_DISPLAY_FIELDS = 3;
2155
+ function isTextLike(candidate) {
2156
+ return candidate.isLeaf && !candidate.isArray && candidate.kind === "text";
2157
+ }
2158
+ function overrideFor(overrides, table) {
2159
+ if (!overrides) return null;
2160
+ return overrides[table.key] ?? overrides[table.name] ?? null;
2161
+ }
2162
+ function resolveDisplayFieldsFromCandidates(table, candidates, primaryKey, overrides) {
2163
+ const byName = new Map(candidates.map((candidate) => [candidate.name, candidate]));
2164
+ const hostFields = (overrideFor(overrides, table) ?? []).filter((name) => byName.get(name)?.isLeaf);
2165
+ if (hostFields.length > 0) return { fields: hostFields, source: "host" };
2166
+ const known = NAME_FIELDS.filter((name) => {
2167
+ const candidate = byName.get(name);
2168
+ return candidate ? isTextLike(candidate) : false;
2169
+ });
2170
+ const nameLike = candidates.filter((candidate) => isTextLike(candidate) && NAME_LIKE.test(candidate.name) && !known.includes(candidate.name)).map((candidate) => candidate.name).sort((left, right) => left.length - right.length);
2171
+ const named = [...known, ...nameLike].slice(0, MAX_DISPLAY_FIELDS);
2172
+ if (named.length > 0) return { fields: named, source: "name" };
2173
+ const text = candidates.find(
2174
+ (candidate) => isTextLike(candidate) && !candidate.isPrimaryKey && !candidate.isForeignKey
2175
+ );
2176
+ if (text) return { fields: [text.name], source: "text" };
2177
+ const key = primaryKey.filter((name) => byName.get(name)?.isLeaf);
2178
+ if (key.length > 0) return { fields: key, source: "key" };
2179
+ return { fields: [], source: "none" };
2180
+ }
2181
+ function resolveDisplayFields(table, overrides) {
2182
+ return resolveDisplayFieldsFromCandidates(
2183
+ table,
2184
+ table.columns.map((column) => ({
2185
+ name: column.name,
2186
+ kind: column.value.kind,
2187
+ isArray: column.value.isArray,
2188
+ isLeaf: column.readable && column.value.selection === null,
2189
+ isPrimaryKey: column.isPrimaryKey,
2190
+ isForeignKey: column.isForeignKey
2191
+ })),
2192
+ table.primaryKey,
2193
+ overrides
2194
+ );
2195
+ }
2196
+
2197
+ // src/table-model/build-relations.ts
2198
+ function names(fields) {
2199
+ return (fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
2200
+ }
2201
+ function sameSet(left, right) {
2202
+ const set = new Set(left);
2203
+ return left.length === right.length && right.every((name) => set.has(name));
2204
+ }
2205
+ function foreignKeysOf(table) {
2206
+ const nested = Array.isArray(table.constraints) ? null : table.constraints?.foreignKey;
2207
+ return (nested ?? table.foreignKeyConstraints ?? []).filter(
2208
+ (constraint) => constraint != null
2209
+ );
2210
+ }
2211
+ function fieldOf(table, name) {
2212
+ return table?.fields?.find((field2) => field2?.name === name) ?? null;
2213
+ }
2214
+ function isRequiredField(field2) {
2215
+ return Boolean(field2?.isNotNull ?? field2?.type.isNotNull);
2216
+ }
2217
+ function relationTarget(target, lookup, overrides) {
2218
+ if (!target) return { target: { primaryKey: [], labelFields: [] }, rowType: null };
2219
+ const rowType = lookup.type(target.name);
2220
+ const identity = getRowIdentityDefinition(target);
2221
+ const primaryKey = identity.status === "keyed" ? identity.fields.map((field2) => field2.fieldName) : [];
2222
+ const candidates = (target.fields ?? []).flatMap((field2) => {
2223
+ if (!field2) return [];
2224
+ const rowField = lookup.field(rowType, field2.name);
2225
+ const named = namedTypeOf(rowField?.type);
2226
+ const isLeaf = Boolean(rowField && named && (named.kind === "SCALAR" || named.kind === "ENUM") && !rowField.args.some(isRequiredInput));
2227
+ const outputType = named ? { kind: named.kind, name: named.name, fields: null, inputFields: null, enumValues: null } : null;
2228
+ return [{
2229
+ name: field2.name,
2230
+ kind: columnValueKind(field2, outputType, null, lookup),
2231
+ isArray: field2.type.isArray,
2232
+ isLeaf,
2233
+ isPrimaryKey: primaryKey.includes(field2.name),
2234
+ isForeignKey: field2.isForeignKey === true
2235
+ }];
2236
+ });
2237
+ const leafNames = new Set(candidates.filter((candidate) => candidate.isLeaf).map((candidate) => candidate.name));
2238
+ const display = resolveDisplayFieldsFromCandidates(
2239
+ { key: tableKeyOf(target), name: target.name },
2240
+ candidates,
2241
+ primaryKey,
2242
+ overrides
2243
+ );
2244
+ return {
2245
+ target: {
2246
+ primaryKey: primaryKey.every((name) => leafNames.has(name)) ? primaryKey : [],
2247
+ labelFields: display.fields
2248
+ },
2249
+ rowType
2250
+ };
2251
+ }
2252
+ function fieldShape(field2, targetName, single, lookup) {
2253
+ if (!field2 || field2.args.some(isRequiredInput)) return null;
2254
+ const named = namedTypeOf(field2.type);
2255
+ if (!named) return null;
2256
+ const firstArg = field2.args.find((arg) => arg.name === "first" && namedTypeOf(arg.type)?.name === "Int");
2257
+ if (named.name === targetName) {
2258
+ if (single && !isListTypeRef(field2.type)) return { shape: "object", pageArg: null, hasTotalCount: false };
2259
+ if (!single && isListTypeRef(field2.type)) return { shape: "list", pageArg: firstArg?.name ?? null, hasTotalCount: false };
2260
+ return null;
2261
+ }
2262
+ if (single || named.kind !== "OBJECT") return null;
2263
+ const connection = lookup.type(named.name);
2264
+ const nodes = lookup.field(connection, "nodes");
2265
+ if (namedTypeOf(nodes?.type)?.name !== targetName || !isListTypeRef(nodes?.type)) return null;
2266
+ return { shape: "connection", pageArg: firstArg?.name ?? null, hasTotalCount: Boolean(lookup.field(connection, "totalCount")) };
2267
+ }
2268
+ var LOGICAL_OPERATORS2 = ["and", "or", "not"];
2269
+ function existsFieldFor(filterType, fieldName) {
2270
+ const matches = (filterType.inputFields ?? []).filter(
2271
+ (input) => (input.name === `${fieldName}Exists` || input.name === `${fieldName}Exist`) && !isListTypeRef(input.type) && namedTypeOf(input.type)?.name === "Boolean"
2272
+ );
2273
+ return matches.length === 1 ? matches[0].name : null;
2274
+ }
2275
+ function relationFilter(filterType, fieldName, single, lookup) {
2276
+ const field2 = filterType?.inputFields?.find((input2) => input2.name === fieldName);
2277
+ const named = namedTypeOf(field2?.type);
2278
+ if (!filterType || !field2 || named?.kind !== "INPUT_OBJECT" || isListTypeRef(field2.type)) return null;
2279
+ const input = lookup.type(named.name);
2280
+ if (!input) return null;
2281
+ const inputFields = input.inputFields ?? [];
2282
+ const exists = existsFieldFor(filterType, fieldName);
2283
+ if (single) {
2284
+ if (!inputFields.some((inputField2) => LOGICAL_OPERATORS2.includes(inputField2.name))) return null;
2285
+ return { field: field2.name, typeName: named.name, exists, many: null, recordFilterType: named.name };
2286
+ }
2287
+ const quantifier = (name) => {
2288
+ const inputField2 = inputFields.find((candidate) => candidate.name === name);
2289
+ return inputField2 && namedTypeOf(inputField2.type)?.kind === "INPUT_OBJECT" ? inputField2 : null;
2290
+ };
2291
+ const many = { some: quantifier("some"), every: quantifier("every"), none: quantifier("none") };
2292
+ const present2 = Object.values(many).filter((inputField2) => inputField2 !== null);
2293
+ if (present2.length === 0) return null;
2294
+ const targets = new Set(present2.map((inputField2) => namedTypeOf(inputField2.type)?.name));
2295
+ const [recordFilterType] = [...targets];
2296
+ return {
2297
+ field: field2.name,
2298
+ typeName: named.name,
2299
+ exists,
2300
+ many: { some: many.some?.name ?? null, every: many.every?.name ?? null, none: many.none?.name ?? null },
2301
+ recordFilterType: targets.size === 1 && recordFilterType ? recordFilterType : null
2302
+ };
2303
+ }
2304
+ function allFieldsOf(table, fieldNames2) {
2305
+ return Boolean(table) && fieldNames2.every((name) => fieldOf(table, name) !== null);
2306
+ }
2307
+ function belongsToKeys(table, relation, referenced) {
2308
+ const local = names(relation.keys);
2309
+ if (local.length === 0) return null;
2310
+ const refKeys = names(relation.refKeys);
2311
+ if (refKeys.length > 0) {
2312
+ return refKeys.length === local.length && allFieldsOf(referenced, refKeys) ? local.map((name, position) => ({ local: name, remote: refKeys[position] })) : null;
2313
+ }
2314
+ const constraints = foreignKeysOf(table).filter((constraint2) => sameSet(names(constraint2.fields), local));
2315
+ if (constraints.length !== 1) return null;
2316
+ const constraint = constraints[0];
2317
+ const constraintLocal = names(constraint.fields);
2318
+ const constraintRemote = names(constraint.refFields).length > 0 ? names(constraint.refFields) : constraint.referencedFields ?? [];
2319
+ if (constraintRemote.length !== constraintLocal.length) return null;
2320
+ return local.map((name) => ({ local: name, remote: constraintRemote[constraintLocal.indexOf(name)] }));
2321
+ }
2322
+ function hasKeys(table, relation, related) {
2323
+ const local = names(relation.keys);
2324
+ const remoteKeys = names(relation.remoteKeys);
2325
+ if (local.length > 0 && remoteKeys.length > 0) {
2326
+ return remoteKeys.length === local.length && allFieldsOf(related, remoteKeys) ? { keys: local.map((name, position) => ({ local: name, remote: remoteKeys[position] })) } : { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2327
+ }
2328
+ if (!related || local.length === 0) {
2329
+ return { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2330
+ }
2331
+ const linksHere = [...table.relations?.hasOne ?? [], ...table.relations?.hasMany ?? []].filter(
2332
+ (candidate) => candidate?.referencedBy?.name === related.name
2333
+ );
2334
+ const backLinks = (related.relations?.belongsTo ?? []).filter(
2335
+ (candidate) => candidate?.references?.name === table.name
2336
+ );
2337
+ if (linksHere.length !== 1 || backLinks.length !== 1) {
2338
+ return {
2339
+ problem: {
2340
+ code: "RELATION_AMBIGUOUS",
2341
+ message: "More than one link connects these tables, so this field is read-only."
2342
+ }
2343
+ };
2344
+ }
2345
+ const pairs = belongsToKeys(related, backLinks[0], table);
2346
+ if (!pairs || !sameSet(pairs.map((pair) => pair.remote), local)) {
2347
+ return { problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } };
2348
+ }
2349
+ return { keys: local.map((name) => ({ local: name, remote: pairs.find((pair) => pair.remote === name).local })) };
2350
+ }
2351
+ function junctionModel(relation, ctx) {
2352
+ const junctionMeta = ctx.tables.find((candidate) => candidate.name === relation.junctionTable?.name);
2353
+ const leftJunction = names(relation.junctionLeftKeyAttributes);
2354
+ const leftLocal = names(relation.leftKeyAttributes);
2355
+ const rightJunction = names(relation.junctionRightKeyAttributes);
2356
+ const rightRemote = names(relation.rightKeyAttributes);
2357
+ const incomplete = {
2358
+ junction: null,
2359
+ problem: { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." },
2360
+ unlinkProblem: "Links for this field cannot be removed here."
2361
+ };
2362
+ if (!junctionMeta || leftJunction.length === 0 || leftJunction.length !== leftLocal.length || rightJunction.length === 0 || rightJunction.length !== rightRemote.length) {
2363
+ return incomplete;
2364
+ }
2365
+ const keyFields = /* @__PURE__ */ new Set([...leftJunction, ...rightJunction]);
2366
+ const record = createRecordOf(junctionMeta, ctx.roots, ctx.lookup);
2367
+ const extraRequiredFields = record?.recordType ? (record.recordType.inputFields ?? []).filter((field2) => !keyFields.has(field2.name) && isRequiredInput(field2)).map((field2) => field2.name) : (junctionMeta.fields ?? []).flatMap((field2) => {
2368
+ if (!field2 || keyFields.has(field2.name)) return [];
2369
+ const required = field2.isRequiredOnCreate ?? (isRequiredField(field2) && !(field2.hasDefault ?? field2.type.hasDefault));
2370
+ return required ? [field2.name] : [];
2371
+ });
2372
+ const canCreate = Boolean(record?.recordType);
2373
+ const pure = canCreate && extraRequiredFields.length === 0;
2374
+ const canDelete = Boolean(junctionMeta.query?.delete && ctx.lookup.field(ctx.roots.mutation, junctionMeta.query.delete));
2375
+ return {
2376
+ junction: {
2377
+ tableKey: tableKeyOf(junctionMeta),
2378
+ tableName: junctionMeta.name,
2379
+ left: leftJunction.map((junction, position) => ({ junction, local: leftLocal[position] })),
2380
+ right: rightJunction.map((junction, position) => ({ junction, remote: rightRemote[position] })),
2381
+ pure,
2382
+ extraRequiredFields
2383
+ },
2384
+ problem: !canCreate ? { code: "RELATION_INCOMPLETE", message: "Links for this field cannot be added on this API." } : !pure ? {
2385
+ code: "RELATION_INCOMPLETE",
2386
+ message: `Adding a link needs more information (${extraRequiredFields.join(", ")}), so this field is read-only.`
2387
+ } : null,
2388
+ unlinkProblem: canDelete ? null : "Links for this field cannot be removed here."
2389
+ };
2390
+ }
2391
+ function draftRelations(ctx) {
2392
+ const { table, tables } = ctx;
2393
+ const relations = table.relations;
2394
+ const drafts = [];
2395
+ const findTable = (name) => tables.find((candidate) => candidate.name === name);
2396
+ for (const relation of relations?.belongsTo ?? []) {
2397
+ if (!relation?.fieldName) continue;
2398
+ const keys = belongsToKeys(table, relation, findTable(relation.references.name));
2399
+ const nullable = (keys ?? []).every((pair) => !isRequiredField(fieldOf(table, pair.local)));
2400
+ drafts.push({
2401
+ kind: "belongsTo",
2402
+ fieldName: relation.fieldName,
2403
+ targetName: relation.references.name,
2404
+ keys: keys ?? [],
2405
+ junction: null,
2406
+ keyProblem: keys ? null : { code: "RELATION_INCOMPLETE", message: "The linked record for this field cannot be identified." },
2407
+ unlinkProblem: nullable ? null : "This link is required, so it cannot be removed."
2408
+ });
2409
+ }
2410
+ for (const [kind, list] of [["hasOne", relations?.hasOne], ["hasMany", relations?.hasMany]]) {
2411
+ for (const relation of list ?? []) {
2412
+ if (!relation?.fieldName) continue;
2413
+ const related = findTable(relation.referencedBy.name);
2414
+ const resolved = hasKeys(table, relation, related);
2415
+ const keys = "keys" in resolved ? resolved.keys : [];
2416
+ const nullable = keys.every((pair) => !isRequiredField(fieldOf(related, pair.remote)));
2417
+ drafts.push({
2418
+ kind,
2419
+ fieldName: relation.fieldName,
2420
+ targetName: relation.referencedBy.name,
2421
+ keys,
2422
+ junction: null,
2423
+ keyProblem: "problem" in resolved ? resolved.problem : null,
2424
+ unlinkProblem: nullable ? null : "Each linked record must keep this link, so it cannot be removed."
2425
+ });
2426
+ }
2427
+ }
2428
+ for (const relation of relations?.manyToMany ?? []) {
2429
+ if (!relation?.fieldName) continue;
2430
+ const { junction, problem, unlinkProblem } = junctionModel(relation, ctx);
2431
+ drafts.push({
2432
+ kind: "manyToMany",
2433
+ fieldName: relation.fieldName,
2434
+ targetName: relation.rightTable.name,
2435
+ keys: [],
2436
+ junction,
2437
+ keyProblem: problem,
2438
+ unlinkProblem
2439
+ });
2440
+ }
2441
+ return drafts;
2442
+ }
2443
+ function buildRelations(ctx) {
2444
+ const { lookup, issues } = ctx;
2445
+ return draftRelations(ctx).map((draft) => {
2446
+ const targetMeta = ctx.tables.find((candidate) => candidate.name === draft.targetName);
2447
+ const targetKey = tableKeyForName(ctx.tables, draft.targetName);
2448
+ const { target } = relationTarget(targetMeta, lookup, ctx.displayOverrides);
2449
+ const single = draft.kind === "belongsTo" || draft.kind === "hasOne";
2450
+ const shape = fieldShape(lookup.field(ctx.rowType, draft.fieldName), draft.targetName, single, lookup);
2451
+ const selectable = target.primaryKey.length + target.labelFields.length > 0;
2452
+ const keyProblem = !targetKey ? { code: "RELATION_UNRESOLVED", message: "The linked table for this field cannot be found." } : draft.keyProblem ?? (target.primaryKey.length === 0 ? { code: "RELATION_INCOMPLETE", message: "The linked records for this field cannot be identified." } : null);
2453
+ const readProblem = !shape || !selectable ? "The linked records for this field cannot be shown here." : null;
2454
+ const editable = !keyProblem && !readProblem;
2455
+ const unlinkable = editable && draft.unlinkProblem === null;
2456
+ const reason = readProblem ?? keyProblem?.message ?? draft.unlinkProblem;
2457
+ if (readProblem) {
2458
+ issues.push({ scope: "relation", target: draft.fieldName, code: "RELATION_UNREADABLE", message: readProblem });
2459
+ } else if (keyProblem) {
2460
+ issues.push({ scope: "relation", target: draft.fieldName, code: keyProblem.code, message: keyProblem.message });
2461
+ }
2462
+ return {
2463
+ kind: draft.kind,
2464
+ fieldName: draft.fieldName,
2465
+ targetKey,
2466
+ targetName: draft.targetName,
2467
+ shape: shape?.shape ?? (single ? "object" : "connection"),
2468
+ readable: readProblem === null,
2469
+ keys: draft.keys,
2470
+ junction: draft.junction,
2471
+ target,
2472
+ pageArg: shape?.pageArg ?? null,
2473
+ hasTotalCount: shape?.hasTotalCount ?? false,
2474
+ filter: relationFilter(ctx.filterType, draft.fieldName, single, lookup),
2475
+ editable,
2476
+ unlinkable,
2477
+ reason: editable && unlinkable ? null : reason
2478
+ };
2479
+ });
2480
+ }
2481
+
2482
+ // src/table-model/type-lookup.ts
2483
+ var MAX_INPUT_DEPTH = 4;
2484
+ function createTypeLookup(index) {
2485
+ const missing = /* @__PURE__ */ new Set();
2486
+ const type = (name) => {
2487
+ if (!name) return null;
2488
+ const found = index.get(name);
2489
+ if (found === void 0) {
2490
+ missing.add(name);
2491
+ return null;
2492
+ }
2493
+ return found;
2494
+ };
2495
+ const inputValue = (ref, depth = 0) => {
2496
+ const named = namedTypeOf(ref);
2497
+ if (!named) return null;
2498
+ const isList = isListTypeRef(ref);
2499
+ if (named.kind === "SCALAR") {
2500
+ return { typeName: named.name, shape: "scalar", isList, enumValues: null, fields: null };
2501
+ }
2502
+ if (named.kind === "ENUM") {
2503
+ const enumType = type(named.name);
2504
+ if (!enumType) return null;
2505
+ return {
2506
+ typeName: named.name,
2507
+ shape: "enum",
2508
+ isList,
2509
+ enumValues: (enumType.enumValues ?? []).map((value) => value.name),
2510
+ fields: null
2511
+ };
2512
+ }
2513
+ if (named.kind !== "INPUT_OBJECT") return null;
2514
+ if (depth >= MAX_INPUT_DEPTH) {
2515
+ return { typeName: named.name, shape: "object", isList, enumValues: null, fields: null };
2516
+ }
2517
+ const objectType = type(named.name);
2518
+ if (!objectType) return null;
2519
+ const fields = [];
2520
+ for (const field2 of objectType.inputFields ?? []) {
2521
+ const value = inputValue(field2.type, depth + 1);
2522
+ if (!value) return null;
2523
+ fields.push({ name: field2.name, required: isRequiredInput(field2), value });
2524
+ }
2525
+ return { typeName: named.name, shape: "object", isList, enumValues: null, fields };
2526
+ };
2527
+ return {
2528
+ type,
2529
+ typeOf: (ref) => type(namedTypeOf(ref)?.name),
2530
+ field: (owner, name) => owner?.fields?.find((candidate) => candidate.name === name) ?? null,
2531
+ inputValue,
2532
+ missing
2533
+ };
2534
+ }
2535
+
2536
+ // src/table-model/build-table-model.ts
2537
+ function storageModel(table) {
2538
+ const storage = table.storage;
2539
+ if (!storage || !storage.isFilesTable && !storage.isBucketsTable) return null;
2540
+ return {
2541
+ role: storage.isFilesTable ? "files" : "buckets",
2542
+ filesType: storage.filesType ?? null,
2543
+ bucketsType: storage.bucketsType ?? null,
2544
+ downloadUrlField: storage.downloadUrlField ?? null,
2545
+ upload: storage.upload ? {
2546
+ mutation: storage.upload.mutation ?? null,
2547
+ inputType: storage.upload.inputType ?? null,
2548
+ payloadType: storage.upload.payloadType ?? null,
2549
+ bulkMutation: storage.upload.bulkMutation ?? null,
2550
+ requiresOwnerId: storage.upload.requiresOwnerId ?? null
2551
+ } : null
2552
+ };
2553
+ }
2554
+ var UNIFIED_SEARCH_FIELD = "unifiedSearch";
2555
+ function searchModel(table, filterFields) {
2556
+ const search = table.search;
2557
+ if (!search) return null;
2558
+ return {
2559
+ algorithms: [...search.algorithms],
2560
+ columns: search.columns.flatMap((column) => column ? [{ name: column.name, algorithm: column.algorithm }] : []),
2561
+ unifiedSearchField: search.hasUnifiedSearch && filterFields.has(UNIFIED_SEARCH_FIELD) ? UNIFIED_SEARCH_FIELD : null,
2562
+ weights: parseMetaSearchWeights(search.config)
2563
+ };
2564
+ }
2565
+ function tableKind(table) {
2566
+ return table.kind === "table" || table.kind === "view" ? table.kind : "unknown";
2567
+ }
2568
+ function displayModel(table, columns, primaryKey, overrides) {
2569
+ return resolveDisplayFieldsFromCandidates(
2570
+ { key: tableKeyOf(table), name: table.name },
2571
+ columns.map((column) => ({
2572
+ name: column.name,
2573
+ kind: column.value.kind,
2574
+ isArray: column.value.isArray,
2575
+ isLeaf: column.readable && column.value.selection === null,
2576
+ isPrimaryKey: column.isPrimaryKey,
2577
+ isForeignKey: column.isForeignKey
2578
+ })),
2579
+ primaryKey,
2580
+ overrides
2581
+ );
2582
+ }
2583
+ function buildTableModel(input) {
2584
+ const { table, tables, schema, displayOverrides } = input;
2585
+ const lookup = createTypeLookup(schema);
2586
+ const issues = [];
2587
+ const key = tableKeyOf(table);
2588
+ const roots = schema.roots ?? { query: null, mutation: null };
2589
+ const identity = getRowIdentityDefinition(table);
2590
+ const primaryKey = identity.status === "keyed" ? identity.fields.map((field2) => field2.fieldName) : [];
2591
+ if (primaryKey.length === 0) {
2592
+ issues.push({
2593
+ scope: "table",
2594
+ target: null,
2595
+ code: "NO_PRIMARY_KEY",
2596
+ // A view shows rows of other tables; that, not a missing key, is what a person needs to hear.
2597
+ message: tableKind(table) === "view" ? "This is a view of other tables, so its records cannot be changed or deleted here." : "This table has no primary key, so its records cannot be changed or deleted."
2598
+ });
2599
+ }
2600
+ const rowType = lookup.type(table.name);
2601
+ if (schema.get(table.name) === null || rowType && rowType.kind !== "OBJECT") {
2602
+ issues.push({
2603
+ scope: "table",
2604
+ target: null,
2605
+ code: "TABLE_NOT_IN_SCHEMA",
2606
+ message: "This table is not available through this API."
2607
+ });
2608
+ }
2609
+ const built = buildOperations({ table, roots, lookup, primaryKey, issues });
2610
+ const fields = (table.fields ?? []).filter((field2) => Boolean(field2?.name));
2611
+ const columns = buildColumns({ ...built, fields, rowType, primaryKey, lookup, issues });
2612
+ const relations = buildRelations({
2613
+ table,
2614
+ tables,
2615
+ rowType,
2616
+ filterType: built.filterType,
2617
+ roots,
2618
+ lookup,
2619
+ issues,
2620
+ displayOverrides
2621
+ });
2622
+ const filterFields = new Set((built.filterType?.inputFields ?? []).map((field2) => field2.name));
2623
+ const model = {
2624
+ key,
2625
+ name: table.name,
2626
+ schemaName: table.schemaName ?? null,
2627
+ kind: tableKind(table),
2628
+ description: table.description ?? null,
2629
+ columns,
2630
+ primaryKey,
2631
+ relations,
2632
+ operations: built.operations,
2633
+ display: displayModel(table, columns, primaryKey, displayOverrides),
2634
+ storage: storageModel(table),
2635
+ search: searchModel(table, filterFields),
2636
+ isJunction: table.isJunction ?? null,
2637
+ issues
2638
+ };
2639
+ return { model, missingTypes: [...lookup.missing] };
2640
+ }
2641
+
2642
+ // src/table-model/resolver.ts
2643
+ var MAX_ROUNDS = 6;
2644
+ function initialTypeNames(table) {
2645
+ const inflection3 = table.inflection;
2646
+ const relations = table.relations;
2647
+ return [
2648
+ table.name,
2649
+ inflection3?.connection,
2650
+ inflection3?.filterType,
2651
+ inflection3?.orderByType,
2652
+ inflection3?.patchType,
2653
+ inflection3?.createInputType,
2654
+ inflection3?.createPayloadType,
2655
+ inflection3?.updatePayloadType,
2656
+ inflection3?.deletePayloadType,
2657
+ ...(relations?.belongsTo ?? []).flatMap((relation) => [relation?.references?.name, relation?.type]),
2658
+ ...(relations?.hasOne ?? []).flatMap((relation) => [relation?.referencedBy?.name, relation?.type]),
2659
+ ...(relations?.hasMany ?? []).flatMap((relation) => [relation?.referencedBy?.name, relation?.type]),
2660
+ ...(relations?.manyToMany ?? []).flatMap((relation) => [
2661
+ relation?.rightTable?.name,
2662
+ relation?.junctionTable?.name,
2663
+ relation?.type
2664
+ ])
2665
+ ].filter((name) => typeof name === "string" && name.length > 0);
2666
+ }
2667
+ function createTableModelResolver(meta) {
2668
+ const tables = Array.isArray(meta) ? meta : metaTablesOf(meta);
2669
+ const loader = createSchemaTypeLoader();
2670
+ async function loadRoots(execute2) {
2671
+ try {
2672
+ return await loader.loadRoots(execute2);
2673
+ } catch (error) {
2674
+ const detail = error instanceof Error && error.message ? ` ${error.message}` : "";
2675
+ throw new TableModelError("SCHEMA_UNAVAILABLE", `The API schema could not be read.${detail}`);
2676
+ }
2677
+ }
2678
+ return {
2679
+ tables,
2680
+ schema: loader.index,
2681
+ async prefetch(execute2) {
2682
+ await loadRoots(execute2);
2683
+ },
2684
+ async resolve(execute2, ref, options = {}) {
2685
+ const table = findMetaTable(tables, ref);
2686
+ const roots = await Promise.all([
2687
+ loadRoots(execute2),
2688
+ loader.loadTypes(execute2, initialTypeNames(table))
2689
+ ]).then(([loaded]) => loaded);
2690
+ if (!roots.query) {
2691
+ throw new TableModelError("SCHEMA_UNAVAILABLE", "The API schema has no query type.", {
2692
+ tableKey: `${table.schemaName ?? ""}.${table.name}`
2693
+ });
2694
+ }
2695
+ const build = () => buildTableModel({ table, tables, schema: loader.index, displayOverrides: options.displayOverrides });
2696
+ let result = build();
2697
+ let previous = "";
2698
+ for (let round = 0; round < MAX_ROUNDS && result.missingTypes.length > 0; round += 1) {
2699
+ const missing = [...result.missingTypes].sort().join(",");
2700
+ if (missing === previous) break;
2701
+ previous = missing;
2702
+ await loader.loadTypes(execute2, result.missingTypes);
2703
+ result = build();
2704
+ }
2705
+ return result.model;
2706
+ }
2707
+ };
2708
+ }
2709
+
2710
+ // src/table-model/value-codec.ts
2711
+ var DECIMAL_STRING_SCALARS = /* @__PURE__ */ new Set(["BigInt", "BigFloat"]);
2712
+ function isPlainObject(value) {
2713
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2714
+ const prototype = Object.getPrototypeOf(value);
2715
+ return prototype === Object.prototype || prototype === null;
2716
+ }
2717
+ function invalid(ctx, detail) {
2718
+ return new TableModelError("INVALID_VALUE", `The value for "${ctx.column}" ${detail}.`);
2719
+ }
2720
+ function encodeEnum(input, value, ctx) {
2721
+ if (typeof value !== "string") throw invalid(ctx, "must be one of its choices");
2722
+ const values = input.enumValues ?? [];
2723
+ if (values.includes(value)) return value;
2724
+ const byLabel = ctx.options?.find(
2725
+ (option) => option.label === value && values.includes(option.value) && canonicalName(option.label) === canonicalName(option.value)
2726
+ );
2727
+ if (byLabel) return byLabel.value;
2728
+ throw invalid(ctx, `"${value}" is not one of its choices`);
2729
+ }
2730
+ function encodeScalar(input, value, ctx) {
2731
+ if (ctx.kind === "geometry" && isPlainObject(value) && "geojson" in value) return value.geojson;
2732
+ if (DECIMAL_STRING_SCALARS.has(input.typeName) && typeof value === "number") {
2733
+ if (!Number.isFinite(value)) throw invalid(ctx, "must be a finite number");
2734
+ return String(value);
2735
+ }
2736
+ return value;
2737
+ }
2738
+ function encodeObject(input, value, ctx) {
2739
+ if (!isPlainObject(value)) throw invalid(ctx, "must be a structured value");
2740
+ const nested = { ...ctx, kind: null, options: null };
2741
+ if (!input.fields) {
2742
+ const { __typename: _typename, ...rest } = value;
2743
+ return rest;
2744
+ }
2745
+ const encoded = {};
2746
+ for (const field2 of input.fields) {
2747
+ if (!Object.prototype.hasOwnProperty.call(value, field2.name)) continue;
2748
+ const fieldValue = value[field2.name];
2749
+ if (fieldValue === void 0) continue;
2750
+ encoded[field2.name] = encodeValue(field2.value, fieldValue, nested);
2751
+ }
2752
+ return encoded;
2753
+ }
2754
+ function encodeElement(input, value, ctx) {
2755
+ if (value === null || value === void 0) return value;
2756
+ if (input.shape === "enum") return encodeEnum(input, value, ctx);
2757
+ if (input.shape === "object") return encodeObject(input, value, ctx);
2758
+ return encodeScalar(input, value, ctx);
2759
+ }
2760
+ function encodeValue(input, value, ctx) {
2761
+ if (value === null || value === void 0) return value;
2762
+ if (input.isList && Array.isArray(value)) return value.map((element) => encodeElement(input, element, ctx));
2763
+ return encodeElement(input, value, ctx);
2764
+ }
2765
+ function encodeColumnValue(column, value) {
2766
+ const input = column.value.input;
2767
+ if (!input) {
2768
+ throw new TableModelError(
2769
+ "FIELD_NOT_WRITABLE",
2770
+ column.write.updateReason ?? column.write.createReason ?? `"${column.name}" cannot be written.`
2771
+ );
2772
+ }
2773
+ return encodeValue(input, value, { column: column.name, kind: column.value.kind, options: column.value.options });
2774
+ }
2775
+ function encodeWriteValues(model, values, operation) {
2776
+ const encoded = {};
2777
+ for (const [name, value] of Object.entries(values)) {
2778
+ if (value === void 0) continue;
2779
+ const column = model.columns.find((candidate) => candidate.name === name);
2780
+ if (!column) {
2781
+ throw new TableModelError("UNKNOWN_FIELD", `"${name}" is not a field of this table.`, { tableKey: model.key });
2782
+ }
2783
+ const allowed = operation === "create" ? column.write.create : column.write.update;
2784
+ if (!allowed) {
2785
+ const reason = operation === "create" ? column.write.createReason : column.write.updateReason;
2786
+ throw new TableModelError("FIELD_NOT_WRITABLE", `"${name}": ${reason ?? "this field cannot be written."}`, {
2787
+ tableKey: model.key
2788
+ });
2789
+ }
2790
+ encoded[name] = encodeColumnValue(column, value);
2791
+ }
2792
+ return encoded;
2793
+ }
2794
+
2795
+ // src/table-model/documents.ts
2796
+ var RELATION_TOTAL_COUNTS_KEY = "__relationTotalCounts";
2797
+ var CELL_ERRORS_KEY = "__cellErrors";
2798
+ var DEFAULT_RELATION_PAGE_SIZE = 20;
2799
+ function documentOf(source, variables) {
2800
+ return { document: new TypedDocumentString(source), source, variables };
2801
+ }
2802
+ function unavailable(model, operation) {
2803
+ const issue = model.issues.find((candidate) => candidate.scope === "operation" && candidate.target === operation);
2804
+ return new TableModelError("OPERATION_UNAVAILABLE", issue?.message ?? `This table does not support ${operation}.`, {
2805
+ tableKey: model.key
2806
+ });
2807
+ }
2808
+ function columnSelection(column) {
2809
+ return column.value.selection ? `${column.name} ${column.value.selection}` : column.name;
2810
+ }
2811
+ function columnsSelection(model, returning) {
2812
+ const columns = model.columns.filter((column) => column.readable);
2813
+ if (!returning) return columns.map(columnSelection).join(" ");
2814
+ return returning.map((name) => {
2815
+ const column = columns.find((candidate) => candidate.name === name);
2816
+ if (!column) throw new TableModelError("UNKNOWN_FIELD", `"${name}" cannot be returned by this table.`, { tableKey: model.key });
2817
+ return columnSelection(column);
2818
+ }).join(" ");
2819
+ }
2820
+ function listColumnNames(model, requested, relations) {
2821
+ if (!requested) return void 0;
2822
+ const readable = new Set(model.columns.filter((column) => column.readable).map((column) => column.name));
2823
+ for (const name of requested) {
2824
+ if (!readable.has(name)) {
2825
+ throw new TableModelError("UNKNOWN_FIELD", `"${name}" is not a column this table can show.`, { tableKey: model.key });
2826
+ }
2827
+ }
2828
+ const wanted = /* @__PURE__ */ new Set([
2829
+ ...requested,
2830
+ ...model.primaryKey,
2831
+ ...relations.flatMap((relation) => relation.keys.map((pair) => pair.local)),
2832
+ ...relations.flatMap((relation) => relation.junction?.left.map((pair) => pair.local) ?? [])
2833
+ ]);
2834
+ return model.columns.filter((column) => column.readable && wanted.has(column.name)).map((column) => column.name);
2835
+ }
2836
+ function relationSelection(relation, pageSize) {
2837
+ const fields = [.../* @__PURE__ */ new Set([...relation.target.primaryKey, ...relation.target.labelFields])].join(" ");
2838
+ const page = relation.pageArg ? `(${relation.pageArg}: ${pageSize})` : "";
2839
+ if (relation.shape === "object") return `${relation.fieldName} { ${fields} }`;
2840
+ if (relation.shape === "list") return `${relation.fieldName}${page} { ${fields} }`;
2841
+ return `${relation.fieldName}${page} { nodes { ${fields} }${relation.hasTotalCount ? " totalCount" : ""} }`;
2842
+ }
2843
+ function selectedRelations(model, choice) {
2844
+ if (!choice || choice === "none") return [];
2845
+ if (choice === "all") return model.relations.filter((relation) => relation.readable);
2846
+ return choice.flatMap((fieldName) => {
2847
+ const relation = model.relations.find((candidate) => candidate.fieldName === fieldName);
2848
+ if (!relation) {
2849
+ throw new TableModelError("UNKNOWN_FIELD", `"${fieldName}" is not a relation of this table.`, { tableKey: model.key });
2850
+ }
2851
+ return relation.readable ? [relation] : [];
2852
+ });
2853
+ }
2854
+ function pageSizeOf(options) {
2855
+ const size = options.relationPageSize ?? DEFAULT_RELATION_PAGE_SIZE;
2856
+ return Number.isInteger(size) && size > 0 ? size : DEFAULT_RELATION_PAGE_SIZE;
2857
+ }
2858
+ function readRow(row, relations) {
2859
+ if (!row || typeof row !== "object") return {};
2860
+ const next = { ...row };
2861
+ const totals = {};
2862
+ for (const relation of relations) {
2863
+ if (relation.shape !== "connection") continue;
2864
+ const value = next[relation.fieldName];
2865
+ if (!value || typeof value !== "object") continue;
2866
+ next[relation.fieldName] = Array.isArray(value.nodes) ? value.nodes : [];
2867
+ if (typeof value.totalCount === "number") totals[relation.fieldName] = value.totalCount;
2868
+ }
2869
+ if (Object.keys(totals).length > 0) next[RELATION_TOTAL_COUNTS_KEY] = totals;
2870
+ return next;
2871
+ }
2872
+ function readCellError(row, fieldName) {
2873
+ const errors2 = row?.[CELL_ERRORS_KEY];
2874
+ if (!errors2 || typeof errors2 !== "object") return null;
2875
+ const message = errors2[fieldName];
2876
+ return typeof message === "string" ? message : null;
2877
+ }
2878
+ function cellErrorsOf(errors2, listField, shape) {
2879
+ const byRow = /* @__PURE__ */ new Map();
2880
+ const offset = shape === "connection" ? 2 : 1;
2881
+ for (const error of errors2) {
2882
+ const path = error.path ?? [];
2883
+ const row = path[offset];
2884
+ const field2 = path[offset + 1];
2885
+ const located = path[0] === listField && (shape === "list" || path[1] === "nodes");
2886
+ if (!located || typeof row !== "number" || typeof field2 !== "string") {
2887
+ throw new TableModelError("READ_FAILED", error.message || "The rows could not be read.");
2888
+ }
2889
+ const cells = byRow.get(row) ?? {};
2890
+ cells[field2] ??= error.message || "This value cannot be shown.";
2891
+ byRow.set(row, cells);
2892
+ }
2893
+ return byRow;
2894
+ }
2895
+ function withCellErrors(rows, cellErrors) {
2896
+ if (cellErrors.size === 0) return rows;
2897
+ return rows.map((row, position) => {
2898
+ const cells = cellErrors.get(position);
2899
+ return cells ? { ...row, [CELL_ERRORS_KEY]: cells } : row;
2900
+ });
2901
+ }
2902
+ function readRelationTotalCount(row, fieldName) {
2903
+ const totals = row?.[RELATION_TOTAL_COUNTS_KEY];
2904
+ if (!totals || typeof totals !== "object") return null;
2905
+ const total = totals[fieldName];
2906
+ return typeof total === "number" ? total : null;
2907
+ }
2908
+ function orderByValues(model, orderBy) {
2909
+ return orderBy.map(({ field: field2, direction }) => {
2910
+ const column = model.columns.find((candidate) => candidate.name === field2);
2911
+ if (!column?.sort) {
2912
+ throw new TableModelError("SORT_UNAVAILABLE", `This table cannot be sorted by "${field2}".`, { tableKey: model.key });
2913
+ }
2914
+ return direction === "desc" ? column.sort.desc : column.sort.asc;
2915
+ });
2916
+ }
2917
+ function readPageInfo(value) {
2918
+ if (!value || typeof value !== "object") return null;
2919
+ const info = value;
2920
+ return {
2921
+ hasNextPage: info.hasNextPage === true,
2922
+ hasPreviousPage: info.hasPreviousPage === true,
2923
+ startCursor: typeof info.startCursor === "string" ? info.startCursor : null,
2924
+ endCursor: typeof info.endCursor === "string" ? info.endCursor : null
2925
+ };
2926
+ }
2927
+ function buildListDocument(model, options = {}) {
2928
+ const list = model.operations.list;
2929
+ if (!list) throw unavailable(model, "list");
2930
+ const definitions = [];
2931
+ const args = [];
2932
+ const variables = {};
2933
+ const bind = (argument2, variable2, value, code, message) => {
2934
+ if (!argument2) throw new TableModelError(code, message, { tableKey: model.key });
2935
+ definitions.push(`$${variable2}: ${argument2.type}`);
2936
+ args.push(`${argument2.name}: $${variable2}`);
2937
+ variables[variable2] = value;
2938
+ };
2939
+ if (options.first !== void 0) bind(list.first, "first", options.first, "PAGING_UNAVAILABLE", "This table cannot be read page by page.");
2940
+ if (options.offset !== void 0) bind(list.offset, "offset", options.offset, "PAGING_UNAVAILABLE", "This table cannot skip rows.");
2941
+ if (options.after) bind(list.after, "after", options.after, "PAGING_UNAVAILABLE", "This table cannot continue from a cursor.");
2942
+ if (options.where && Object.keys(options.where).length > 0) {
2943
+ bind(list.filter, "where", options.where, "FILTER_UNAVAILABLE", "This table cannot be filtered.");
2944
+ }
2945
+ if (options.orderBy && options.orderBy.length > 0) {
2946
+ bind(list.orderBy, "orderBy", orderByValues(model, options.orderBy), "SORT_UNAVAILABLE", "This table cannot be sorted.");
2947
+ }
2948
+ const relations = selectedRelations(model, options.relations);
2949
+ const pageSize = pageSizeOf(options);
2950
+ const rowSelection = [
2951
+ columnsSelection(model, listColumnNames(model, options.columns, relations)),
2952
+ ...relations.map((relation) => relationSelection(relation, pageSize))
2953
+ ].filter(Boolean).join(" ");
2954
+ const withTotal = list.totalCount && options.totalCount !== false;
2955
+ const withPageInfo = list.pageInfo && options.pageInfo !== false;
2956
+ const body = list.shape === "connection" ? `{ nodes { ${rowSelection} }${withTotal ? " totalCount" : ""}${withPageInfo ? ` pageInfo { ${PAGE_INFO_FIELDS.join(" ")} }` : ""} }` : `{ ${rowSelection} }`;
2957
+ const source = `query ModelList_${model.name}${definitions.length ? `(${definitions.join(", ")})` : ""} {
2958
+ ${list.field}${args.length ? `(${args.join(", ")})` : ""} ${body}
2959
+ }`;
2960
+ return {
2961
+ ...documentOf(source, variables),
2962
+ read(data, errors2 = []) {
2963
+ const value = data?.[list.field];
2964
+ if (errors2.length > 0 && value == null) {
2965
+ throw new TableModelError("READ_FAILED", errors2[0]?.message || "The rows could not be read.", { tableKey: model.key });
2966
+ }
2967
+ const cellErrors = cellErrorsOf(errors2, list.field, list.shape);
2968
+ if (list.shape === "list") {
2969
+ const rows = Array.isArray(value) ? value.map((row) => readRow(row, relations)) : [];
2970
+ return { rows: withCellErrors(rows, cellErrors), totalCount: null, pageInfo: null };
2971
+ }
2972
+ const connection = value ?? {};
2973
+ const nodes = Array.isArray(connection.nodes) ? connection.nodes : [];
2974
+ return {
2975
+ rows: withCellErrors(nodes.map((row) => readRow(row, relations)), cellErrors),
2976
+ totalCount: withTotal && typeof connection.totalCount === "number" ? connection.totalCount : null,
2977
+ pageInfo: withPageInfo ? readPageInfo(connection.pageInfo) : null
2978
+ };
2979
+ }
2980
+ };
2981
+ }
2982
+ function keyValues(model, key, fields) {
2983
+ const values = {};
2984
+ for (const field2 of fields) {
2985
+ const value = key[field2];
2986
+ if (value === void 0 || value === null) {
2987
+ throw new TableModelError("KEY_INCOMPLETE", `The record key is missing "${field2}".`, { tableKey: model.key });
2988
+ }
2989
+ const column = model.columns.find((candidate) => candidate.name === field2);
2990
+ values[field2] = column?.value.input ? encodeColumnValue(column, value) : value;
2991
+ }
2992
+ return values;
2993
+ }
2994
+ function buildFindOneDocument(model, key, options = {}) {
2995
+ if (model.primaryKey.length === 0) {
2996
+ throw new TableModelError("KEY_INCOMPLETE", "This table has no primary key, so one record cannot be looked up.", {
2997
+ tableKey: model.key
2998
+ });
2999
+ }
3000
+ const values = keyValues(model, key, model.primaryKey);
3001
+ const where = Object.fromEntries(
3002
+ model.primaryKey.map((field2) => {
3003
+ const column = model.columns.find((candidate) => candidate.name === field2);
3004
+ if (!column?.filter?.operators.some((operator) => operator.name === "equalTo")) {
3005
+ throw new TableModelError("FILTER_UNAVAILABLE", "One record cannot be looked up on this table.", {
3006
+ tableKey: model.key
3007
+ });
3008
+ }
3009
+ return [column.filter.field, { equalTo: values[field2] }];
3010
+ })
3011
+ );
3012
+ const list = buildListDocument(model, {
3013
+ ...options,
3014
+ where,
3015
+ first: model.operations.list?.first ? 1 : void 0,
3016
+ totalCount: false,
3017
+ pageInfo: false
3018
+ });
3019
+ return {
3020
+ document: list.document,
3021
+ source: list.source,
3022
+ variables: list.variables,
3023
+ read: (data, errors2) => list.read(data, errors2).rows[0] ?? null
3024
+ };
3025
+ }
3026
+ function payloadApplied(data, field2, payloadField) {
3027
+ if (!payloadField) return null;
3028
+ const payload = data?.[field2];
3029
+ if (payload === null || payload === void 0) return false;
3030
+ if (!(payloadField in payload)) return null;
3031
+ return payload[payloadField] !== null;
3032
+ }
3033
+ function readPayloadRow(data, field2, payloadField) {
3034
+ if (!payloadField) return null;
3035
+ const payload = data?.[field2];
3036
+ const row = payload?.[payloadField];
3037
+ return row && typeof row === "object" ? row : null;
3038
+ }
3039
+ function buildCreateDocument(model, values, options = {}) {
3040
+ const create = model.operations.create;
3041
+ if (!create) throw unavailable(model, "create");
3042
+ const variables = { input: { [create.recordField]: encodeWriteValues(model, values, "create") } };
3043
+ const source = `mutation ModelCreate_${model.name}($input: ${create.input.type}) {
3044
+ ${create.field}(${create.input.name}: $input) { ${create.payloadField} { ${columnsSelection(model, options.returning)} } }
3045
+ }`;
3046
+ return { ...documentOf(source, variables), read: (data) => readPayloadRow(data, create.field, create.payloadField) };
3047
+ }
3048
+ function buildUpdateDocument(model, key, patch, options = {}) {
3049
+ const update = model.operations.update;
3050
+ if (!update) throw unavailable(model, "update");
3051
+ const variables = {
3052
+ input: { ...keyValues(model, key, update.keyArgs), [update.patchField]: encodeWriteValues(model, patch, "update") }
3053
+ };
3054
+ const source = `mutation ModelUpdate_${model.name}($input: ${update.input.type}) {
3055
+ ${update.field}(${update.input.name}: $input) { ${update.payloadField} { ${columnsSelection(model, options.returning)} } }
3056
+ }`;
3057
+ return {
3058
+ ...documentOf(source, variables),
3059
+ read: (data) => readPayloadRow(data, update.field, update.payloadField),
3060
+ applied: (data) => payloadApplied(data, update.field, update.payloadField)
3061
+ };
3062
+ }
3063
+ function buildDeleteDocument(model, key) {
3064
+ const remove = model.operations.delete;
3065
+ if (!remove) throw unavailable(model, "delete");
3066
+ const variables = { input: keyValues(model, key, remove.keyArgs) };
3067
+ const keySelection = model.columns.filter((column) => column.readable && model.primaryKey.includes(column.name)).map(columnSelection).join(" ");
3068
+ const payload = remove.payloadField && keySelection ? `${remove.payloadField} { ${keySelection} }` : "__typename";
3069
+ const source = `mutation ModelDelete_${model.name}($input: ${remove.input.type}) {
3070
+ ${remove.field}(${remove.input.name}: $input) { ${payload} }
3071
+ }`;
3072
+ return {
3073
+ ...documentOf(source, variables),
3074
+ read: (data) => readPayloadRow(data, remove.field, remove.payloadField && keySelection ? remove.payloadField : null),
3075
+ applied: (data) => payloadApplied(data, remove.field, remove.payloadField && keySelection ? remove.payloadField : null)
3076
+ };
3077
+ }
3078
+
1114
3079
  // ../../node_modules/.pnpm/inflekt@0.5.1/node_modules/inflekt/esm/pluralize.js
1115
3080
  var inflection = __toESM(require_inflection());
1116
3081
  var LATIN_SUFFIX_OVERRIDES = [
@@ -1330,17 +3295,17 @@ function tableIdentifier(table) {
1330
3295
  }
1331
3296
  function includedTableNames(values) {
1332
3297
  if (!values) return null;
1333
- const names = /* @__PURE__ */ new Set();
3298
+ const names2 = /* @__PURE__ */ new Set();
1334
3299
  for (const value of values) {
1335
- names.add(value);
3300
+ names2.add(value);
1336
3301
  const separator = value.lastIndexOf(".");
1337
3302
  const schemaName = separator >= 0 ? value.slice(0, separator) : null;
1338
3303
  const physicalName = separator >= 0 ? value.slice(separator + 1) : value;
1339
3304
  const graphqlName = codecNameToTableName(pgFieldToCamelCase(physicalName));
1340
- names.add(graphqlName);
1341
- if (schemaName) names.add(`${schemaName}.${graphqlName}`);
3305
+ names2.add(graphqlName);
3306
+ if (schemaName) names2.add(`${schemaName}.${graphqlName}`);
1342
3307
  }
1343
- return names;
3308
+ return names2;
1344
3309
  }
1345
3310
  function collectJunctionTableNames(tables) {
1346
3311
  const junctions = /* @__PURE__ */ new Set();
@@ -1378,124 +3343,23 @@ function selectConsoleDataTables(metaTables, options = {}) {
1378
3343
  });
1379
3344
  }
1380
3345
 
1381
- // src/row-identity.ts
1382
- function primaryKeyColumnNames(table) {
1383
- const constraints = table.constraints;
1384
- if (constraints && !Array.isArray(constraints)) {
1385
- const names = (constraints.primaryKey?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1386
- if (names.length > 0) return [...new Set(names)];
1387
- }
1388
- for (const constraint of table.primaryKeyConstraints ?? []) {
1389
- const names = (constraint?.fields ?? []).flatMap((field2) => field2?.name ? [field2.name] : []);
1390
- if (names.length > 0) return [...new Set(names)];
1391
- }
1392
- return [...new Set(
1393
- (table.fields ?? []).flatMap((field2) => field2?.isPrimaryKey && field2.name ? [field2.name] : [])
1394
- )];
1395
- }
1396
- function isRowIdentityValue(value) {
1397
- if (value === null || typeof value === "string" || typeof value === "boolean") return true;
1398
- if (typeof value === "number") return Number.isFinite(value);
1399
- if (Array.isArray(value)) return value.every(isRowIdentityValue);
1400
- if (typeof value !== "object" || value === null) return false;
1401
- const prototype = Object.getPrototypeOf(value);
1402
- if (prototype !== Object.prototype && prototype !== null) return false;
1403
- return Object.values(value).every(isRowIdentityValue);
1404
- }
1405
- function sortIdentityValue(value) {
1406
- if (Array.isArray(value)) return value.map(sortIdentityValue);
1407
- if (typeof value !== "object" || value === null) return value;
1408
- return Object.fromEntries(
1409
- Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortIdentityValue(item)])
1410
- );
1411
- }
1412
- function getRowIdentityDefinition(table) {
1413
- const schemaName = table.schemaName ?? null;
1414
- const columnNames = primaryKeyColumnNames(table);
1415
- if (columnNames.length === 0) {
1416
- return {
1417
- status: "read-only",
1418
- schemaName,
1419
- tableName: table.name,
1420
- reason: "no-primary-key"
1421
- };
1422
- }
1423
- return {
1424
- status: "keyed",
1425
- schemaName,
1426
- tableName: table.name,
1427
- fields: columnNames.map((columnName) => ({
1428
- columnName,
1429
- // `_meta` exposes GraphQL field names here (already inflected), so using
1430
- // them verbatim also handles custom/renamed primary keys.
1431
- fieldName: columnName
1432
- }))
1433
- };
3346
+ // src/system-tables.ts
3347
+ function physicalKey(schemaName, tableName) {
3348
+ return `${schemaName}.${tableName}`;
1434
3349
  }
1435
- function resolveRowIdentity(table, row) {
1436
- const definition = getRowIdentityDefinition(table);
1437
- if (definition.status === "read-only") return definition;
1438
- const missingFields = [];
1439
- const invalidFields = [];
1440
- const fields = [];
1441
- for (const field2 of definition.fields) {
1442
- if (!Object.prototype.hasOwnProperty.call(row, field2.fieldName)) {
1443
- missingFields.push(field2.fieldName);
1444
- continue;
1445
- }
1446
- const value = row[field2.fieldName];
1447
- if (value === null || !isRowIdentityValue(value)) {
1448
- invalidFields.push(field2.fieldName);
1449
- continue;
1450
- }
1451
- fields.push({ ...field2, value });
1452
- }
1453
- if (missingFields.length > 0 || invalidFields.length > 0) {
1454
- return {
1455
- status: "invalid-row",
1456
- schemaName: definition.schemaName,
1457
- tableName: definition.tableName,
1458
- missingFields,
1459
- invalidFields
1460
- };
3350
+ function tableRolesFromCatalog(tables) {
3351
+ const roles = /* @__PURE__ */ new Map();
3352
+ for (const table of tables) {
3353
+ const schemaName = table.schema?.schemaName;
3354
+ if (!schemaName || !table.name || !table.category) continue;
3355
+ roles.set(physicalKey(schemaName, table.name), table.category.toUpperCase() === "APP" ? "app" : "system");
1461
3356
  }
1462
- return {
1463
- status: "identified",
1464
- identity: {
1465
- schemaName: definition.schemaName,
1466
- tableName: definition.tableName,
1467
- fields
1468
- }
1469
- };
1470
- }
1471
- function serializeRowIdentity(identity) {
1472
- return JSON.stringify([
1473
- identity.schemaName,
1474
- identity.tableName,
1475
- identity.fields.map((field2) => [
1476
- field2.columnName,
1477
- field2.fieldName,
1478
- sortIdentityValue(field2.value)
1479
- ])
1480
- ]);
1481
- }
1482
- function rowIdentityToPrimaryKey(identity) {
1483
- return Object.fromEntries(
1484
- identity.fields.map((field2) => [field2.fieldName, field2.value])
1485
- );
3357
+ return roles;
1486
3358
  }
1487
- function assessTableWriteCapability(table) {
1488
- const definition = getRowIdentityDefinition(table);
1489
- if (definition.status === "read-only") return definition;
1490
- return {
1491
- status: "mutable",
1492
- primaryKeyFields: definition.fields.map((field2) => field2.fieldName),
1493
- operations: {
1494
- create: Boolean(table.query?.create),
1495
- update: Boolean(table.query?.update),
1496
- delete: Boolean(table.query?.delete)
1497
- }
1498
- };
3359
+ function isSystemTable(table, roles) {
3360
+ const role = roles && table.schemaName && table.tableName ? roles.get(physicalKey(table.schemaName, table.tableName)) : void 0;
3361
+ if (role === "system") return true;
3362
+ return Boolean(table.storage?.isFilesTable || table.storage?.isBucketsTable || table.scope?.scope === "database");
1499
3363
  }
1500
3364
  var document = ({ definitions }) => ({
1501
3365
  kind: Kind.DOCUMENT,
@@ -2946,16 +4810,16 @@ function convertCustomSelectionToOptions(table, allTables, selection) {
2946
4810
  });
2947
4811
  }
2948
4812
  if (selection.include) {
2949
- Object.entries(selection.include).forEach(([relationField, relationSelection]) => {
4813
+ Object.entries(selection.include).forEach(([relationField, relationSelection2]) => {
2950
4814
  if (isRelationalField2(relationField, table)) {
2951
- if (relationSelection === true) {
4815
+ if (relationSelection2 === true) {
2952
4816
  options[relationField] = {
2953
4817
  select: getRelatedTableScalarFields(relationField, table, allTables),
2954
4818
  variables: {}
2955
4819
  };
2956
- } else if (Array.isArray(relationSelection)) {
4820
+ } else if (Array.isArray(relationSelection2)) {
2957
4821
  const selectObj = {};
2958
- relationSelection.forEach((field2) => {
4822
+ relationSelection2.forEach((field2) => {
2959
4823
  selectObj[field2] = true;
2960
4824
  });
2961
4825
  options[relationField] = {
@@ -4089,9 +5953,9 @@ function analyzeSchemaIntrospectionCompatibility(introspection, metaQuery) {
4089
5953
  missing.add(fallbackPath);
4090
5954
  return false;
4091
5955
  }
4092
- const inputField = inputType.inputFields?.find((field2) => field2.name === fieldName);
4093
- if (!inputField) return true;
4094
- if (baseTypeName(inputField.type) !== enumTypeName) {
5956
+ const inputField2 = inputType.inputFields?.find((field2) => field2.name === fieldName);
5957
+ if (!inputField2) return true;
5958
+ if (baseTypeName(inputField2.type) !== enumTypeName) {
4095
5959
  missing.add(`${typePath(inputType.name)}.inputFields.${fieldName}.type.${enumTypeName}`);
4096
5960
  return false;
4097
5961
  }
@@ -4288,12 +6152,27 @@ function wait(ms) {
4288
6152
  function getErrorCode(error) {
4289
6153
  return parse(error).code;
4290
6154
  }
4291
- var AUTH_ERROR_CODES = /* @__PURE__ */ new Set(["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"]);
4292
- var AUTH_MESSAGE_PATTERN = /unauthenticated|unauthorized|not authorized|authentication|session expired|token expired/;
6155
+ var AUTHENTICATION_ERROR_CODES = ["UNAUTHENTICATED", "BAD_TOKEN_DEFINITION"];
6156
+ function isAuthenticationCode(code) {
6157
+ return typeof code === "string" && AUTHENTICATION_ERROR_CODES.includes(code);
6158
+ }
6159
+ var AUTH_STATUS = 401;
6160
+ function asShape(value) {
6161
+ return value && typeof value === "object" ? value : null;
6162
+ }
6163
+ function hasAuthCode(node) {
6164
+ return isAuthenticationCode(asShape(asShape(node)?.extensions)?.code);
6165
+ }
6166
+ function hasAuthCodeIn(errors2) {
6167
+ return Array.isArray(errors2) && errors2.some(hasAuthCode);
6168
+ }
4293
6169
  function isAuthenticationError(error) {
4294
- const parsed = parse(error);
4295
- if (parsed.code && AUTH_ERROR_CODES.has(parsed.code)) return true;
4296
- return AUTH_MESSAGE_PATTERN.test((parsed.rawMessage ?? "").toLowerCase());
6170
+ if (error instanceof ConstructiveError) return isAuthenticationCode(error.code);
6171
+ const shape = asShape(error);
6172
+ if (!shape) return false;
6173
+ const response = asShape(shape.response);
6174
+ if (shape.status === AUTH_STATUS || shape.statusCode === AUTH_STATUS || response?.status === AUTH_STATUS) return true;
6175
+ return hasAuthCode(shape) || hasAuthCodeIn(shape.errors) || hasAuthCodeIn(response?.errors);
4297
6176
  }
4298
6177
  var RETRYABLE_CODES = /* @__PURE__ */ new Set(["NETWORK_ERROR", "TIMEOUT_ERROR", "RATE_LIMITED", "TOO_MANY_REQUESTS"]);
4299
6178
  function isRetryable(error) {
@@ -4373,7 +6252,7 @@ function stripEmpty(value) {
4373
6252
  return value;
4374
6253
  }
4375
6254
  var asFieldIds = (ids) => ids;
4376
- function isPlainObject(value) {
6255
+ function isPlainObject2(value) {
4377
6256
  return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
4378
6257
  }
4379
6258
  function hasNestedDirtyFields(dirtyFields, prefix) {
@@ -4449,7 +6328,7 @@ function prepareMutationInput(input, options) {
4449
6328
  result[key] = value;
4450
6329
  continue;
4451
6330
  }
4452
- if (isPlainObject(value)) {
6331
+ if (isPlainObject2(value)) {
4453
6332
  const hasRelevantDirtyFields = !hasDirtyTracking || isDirty || hasNestedDirtyFields(dirtyFields, fullPath);
4454
6333
  if (!hasRelevantDirtyFields) {
4455
6334
  continue;
@@ -5353,6 +7232,6 @@ inflection/lib/inflection.js:
5353
7232
  *)
5354
7233
  */
5355
7234
 
5356
- export { CONSTRAINT_MESSAGES, CRUD_OPERATIONS, CRUD_TO_PRIVILEGE, DATA_NODE_GENERATED_FIELDS, DEFAULT_CONSOLE_APPLICATION_SCOPES, DEFAULT_CRUD_GRANT_PRIVILEGES, MEMBERSHIP_TYPES, META_CONTRACT_INTROSPECTION_DOCUMENT, META_CONTRACT_INTROSPECTION_SOURCE, META_CONTRACT_REQUIREMENTS, META_CONTRACT_VERSION, META_DOCUMENT, META_QUERY_SOURCE, MetaContractError, POLICY_PROVISIONING_CONFIG, QueryBuilder, SCHEMA_INTROSPECTION_QUERY, TypedDocumentString, analyzeSchemaIntrospectionCompatibility, asFieldIds, assertMetaContract, assertMetaQuery, assessMetaContract, assessSchemaIntrospectionCompatibility, assessTableWriteCapability, buildCount, buildFindOne, buildNodeData, buildNodeDataForDataNodeType, buildPostGraphileCreate, buildPostGraphileDelete, buildPostGraphileUpdate, buildSelect, buildTypeRegistry, cleanTable, cleanTableToMetaObject, convertFromMetaSchema, convertToSelectionOptions, createASTQueryBuilder, createError2 as createError, createOne, deleteOne, filterOperations, generateIntrospectionSchema, geometryAst, geometryCollectionAst, geometryPointAst, getAll, getAvailableRelations, getConstraintMessage, getCount, getCustomAst, getCustomAstForCleanField, getCustomOperations, getDataNodeForPolicy, getErrorCode, getFieldsRequiringColumns, getGeneratedFields, getHumanReadableError, getMany, getOne, getPolicyCategory, getPolicyFieldDefaults, getPolicyProvisioningConfig, getRowIdentityDefinition, getSelections, getTableOperationNames, groupCrudOperationsByConfig, hasGeneratedFields, injectSchemaFields, intervalAst, isAuthenticationError, isGraphQLVariableValue, isGraphQLVariables, isIntervalType, isRelationalField2 as isRelationalField, isRetryable, isTableOperation, normalizeInflectionValue, normalizeSchemaEnumInputValues, parseError, parseGraphQLError2 as parseGraphQLError, parseMetaSearchWeights, patchOne, pgFieldToCamelCase, policyCanBeNodeless, policyRequiresDataNode, prepareCreateInput, prepareMutationInput, preparePatchInput, prepareUpdateInput, requiresSubfieldSelection, resolveRowIdentity, rowIdentityToPrimaryKey, sanitizePolicyData, selectConsoleDataTables, serializeRowIdentity, stripEmpty, toCamelCasePlural, toCamelCaseSingular, toCreateInputTypeName, toCreateMutationName, toDeleteInputTypeName, toDeleteMutationName, toFilterTypeName, toOrderByEnumValue, toOrderByTypeName, toPatchFieldName, toUpdateInputTypeName, toUpdateMutationName, transformSchemaToOperations, validateFieldSelection, validateMetaObject, withRetry };
7235
+ export { AUTHENTICATION_ERROR_CODES, CELL_ERRORS_KEY, CONSTRAINT_MESSAGES, CRUD_OPERATIONS, CRUD_TO_PRIVILEGE, DATA_NODE_GENERATED_FIELDS, DEFAULT_CONSOLE_APPLICATION_SCOPES, DEFAULT_CRUD_GRANT_PRIVILEGES, DEFAULT_RELATION_PAGE_SIZE, MEMBERSHIP_TYPES, META_CAPABILITY_INTROSPECTION_DOCUMENT, META_CAPABILITY_INTROSPECTION_SOURCE, META_CONTRACT_INTROSPECTION_DOCUMENT, META_CONTRACT_INTROSPECTION_SOURCE, META_CONTRACT_REQUIREMENTS, META_CONTRACT_VERSION, META_DOCUMENT, META_OPTIONAL_CAPABILITIES, META_QUERY_SOURCE, MetaContractError, POLICY_PROVISIONING_CONFIG, QueryBuilder, RELATION_TOTAL_COUNTS_KEY, SCHEMA_INTROSPECTION_QUERY, SCHEMA_ROOTS_SOURCE, TableModelError, TypedDocumentString, analyzeSchemaIntrospectionCompatibility, asFieldIds, assertMetaContract, assertMetaQuery, assessMetaCapabilities, assessMetaContract, assessSchemaIntrospectionCompatibility, assessTableWriteCapability, buildCount, buildCreateDocument, buildDeleteDocument, buildFindOne, buildFindOneDocument, buildListDocument, buildMetaDocument, buildMetaQuerySource, buildNodeData, buildNodeDataForDataNodeType, buildPostGraphileCreate, buildPostGraphileDelete, buildPostGraphileUpdate, buildSchemaTypesSource, buildSelect, buildTableModel, buildTypeRegistry, buildUpdateDocument, cleanTable, cleanTableToMetaObject, convertFromMetaSchema, convertToSelectionOptions, createASTQueryBuilder, createError2 as createError, createOne, createSchemaTypeLoader, createTableModelResolver, deleteOne, emptyMetaCapabilities, encodeColumnValue, encodeWriteValues, filterOperations, findMetaTable, generateIntrospectionSchema, geometryAst, geometryCollectionAst, geometryPointAst, getAll, getAvailableRelations, getConstraintMessage, getCount, getCustomAst, getCustomAstForCleanField, getCustomOperations, getDataNodeForPolicy, getErrorCode, getFieldsRequiringColumns, getGeneratedFields, getHumanReadableError, getMany, getOne, getPolicyCategory, getPolicyFieldDefaults, getPolicyProvisioningConfig, getRowIdentityDefinition, getSelections, getTableOperationNames, groupCrudOperationsByConfig, hasGeneratedFields, injectSchemaFields, intervalAst, isAuthenticationCode, isAuthenticationError, isGraphQLVariableValue, isGraphQLVariables, isIntervalType, isListTypeRef, isNonNullTypeRef, isRelationalField2 as isRelationalField, isRequiredInput, isRetryable, isSystemTable, isTableOperation, metaTablesOf, namedTypeOf, normalizeInflectionValue, normalizeSchemaEnumInputValues, parseError, parseGraphQLError2 as parseGraphQLError, parseMetaSearchWeights, patchOne, pgFieldToCamelCase, policyCanBeNodeless, policyRequiresDataNode, prepareCreateInput, prepareMutationInput, preparePatchInput, prepareUpdateInput, printTypeRef, readCellError, readRelationTotalCount, requiresSubfieldSelection, resolveDisplayFields, resolveRowIdentity, rowIdentityToPrimaryKey, sanitizePolicyData, selectConsoleDataTables, serializeRowIdentity, stripEmpty, tableKeyForName, tableKeyOf, tableRolesFromCatalog, toCamelCasePlural, toCamelCaseSingular, toCreateInputTypeName, toCreateMutationName, toDeleteInputTypeName, toDeleteMutationName, toFilterTypeName, toOrderByEnumValue, toOrderByTypeName, toPatchFieldName, toUpdateInputTypeName, toUpdateMutationName, transformSchemaToOperations, validateFieldSelection, validateMetaObject, withRetry };
5357
7236
  //# sourceMappingURL=index.js.map
5358
7237
  //# sourceMappingURL=index.js.map