@cyphra/runtime 0.5.0 → 0.6.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
@@ -196,6 +196,9 @@ function integerToNumber(v) {
196
196
  }
197
197
  return v.toNumber();
198
198
  }
199
+ function decodeCount(v) {
200
+ return isInt(v) ? integerToNumber(v) : Number(v ?? 0);
201
+ }
199
202
  function utcDateTime(d) {
200
203
  return new neo4j2.types.DateTime(
201
204
  d.getUTCFullYear(),
@@ -537,7 +540,24 @@ function compileWhere(ctx, model, alias, where) {
537
540
  }
538
541
  return and(parts);
539
542
  }
540
- function compileOrderBy(model, alias, orderBy) {
543
+ function compileRelationCount(ctx, model, alias, rel, where) {
544
+ if (!rel.many) {
545
+ throw new CyphraValidationError(
546
+ `${model.name}.${rel.name} is a to-one relation; only to-many relations can be counted.`
547
+ );
548
+ }
549
+ const m = ctx.variable();
550
+ const pattern = relationPattern(ctx, alias, rel, m);
551
+ const inner = compileWhere(ctx, ctx.node(rel.target), m, where);
552
+ return inner ? `COUNT { MATCH ${pattern} WHERE ${inner} }` : `COUNT { MATCH ${pattern} }`;
553
+ }
554
+ function sortDirection(dir, what) {
555
+ if (dir !== "asc" && dir !== "desc") {
556
+ throw new CyphraValidationError(`orderBy ${what} must be "asc" or "desc".`);
557
+ }
558
+ return dir.toUpperCase();
559
+ }
560
+ function compileOrderBy(ctx, model, alias, orderBy) {
541
561
  if (orderBy === void 0 || orderBy === null) return null;
542
562
  const list = Array.isArray(orderBy) ? orderBy : [orderBy];
543
563
  const parts = [];
@@ -545,11 +565,20 @@ function compileOrderBy(model, alias, orderBy) {
545
565
  if (!isPlainObject(item)) throw new CyphraValidationError("orderBy entries must be objects.");
546
566
  for (const [key, dir] of Object.entries(item)) {
547
567
  if (dir === void 0) continue;
548
- scalarOrThrow(model, key);
549
- if (dir !== "asc" && dir !== "desc") {
550
- throw new CyphraValidationError(`orderBy ${model.name}.${key} must be "asc" or "desc".`);
568
+ const rel = relationField(model, key);
569
+ if (rel) {
570
+ if (!isPlainObject(dir) || Object.keys(dir).some((k) => k !== "_count")) {
571
+ throw new CyphraValidationError(
572
+ `orderBy ${model.name}.${key} takes { _count: "asc" | "desc" }.`
573
+ );
574
+ }
575
+ if (dir._count === void 0) continue;
576
+ const d = sortDirection(dir._count, `${model.name}.${key}._count`);
577
+ parts.push(`${compileRelationCount(ctx, model, alias, rel)} ${d}`);
578
+ continue;
551
579
  }
552
- parts.push(`${alias}.${q(key)} ${dir.toUpperCase()}`);
580
+ scalarOrThrow(model, key);
581
+ parts.push(`${alias}.${q(key)} ${sortDirection(dir, `${model.name}.${key}`)}`);
553
582
  }
554
583
  }
555
584
  return parts.length ? parts.join(", ") : null;
@@ -562,7 +591,7 @@ function nonNegativeInt(v, name) {
562
591
  }
563
592
  function compilePaging(ctx, model, alias, args) {
564
593
  let s = "";
565
- const order = compileOrderBy(model, alias, args.orderBy);
594
+ const order = compileOrderBy(ctx, model, alias, args.orderBy);
566
595
  if (order) s += ` ORDER BY ${order}`;
567
596
  if (args.skip !== void 0)
568
597
  s += ` SKIP ${ctx.param(intParam(nonNegativeInt(args.skip, "skip")))}`;
@@ -580,9 +609,14 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
580
609
  const scalars = [];
581
610
  const rels = [];
582
611
  const allScalars = model.fields.filter((f) => f.kind === "scalar");
612
+ let counts;
583
613
  const takeRelations = (spec, label) => {
584
614
  for (const [key, v] of Object.entries(spec)) {
585
615
  if (v === void 0 || v === false) continue;
616
+ if (key === "_count") {
617
+ counts = relationCounts(model, v, label);
618
+ continue;
619
+ }
586
620
  const f = model.fields.find((x) => x.name === key);
587
621
  if (!f) throw new CyphraValidationError(`Unknown field "${model.name}.${key}" in ${label}.`);
588
622
  if (f.kind === "scalar") {
@@ -635,12 +669,60 @@ function compileProjection(ctx, model, alias, args, extraEntries = []) {
635
669
  ...edgeModel ? { edge: edgeModel.properties } : {}
636
670
  });
637
671
  }
672
+ if (counts) {
673
+ const map = counts.map(
674
+ ({ field, where }) => `${q(field.name)}: ${compileRelationCount(ctx, model, alias, field, where)}`
675
+ );
676
+ entries.push(`${q("_count")}: {${map.join(", ")}}`);
677
+ }
638
678
  entries.push(...extraEntries);
639
679
  return {
640
680
  expr: `${alias}{${entries.join(", ")}}`,
641
- shape: { model, scalars, relations: relShapes }
681
+ shape: {
682
+ model,
683
+ scalars,
684
+ relations: relShapes,
685
+ ...counts ? { counts: counts.map((c) => c.field) } : {}
686
+ }
642
687
  };
643
688
  }
689
+ function relationCounts(model, spec, label) {
690
+ if (spec === true) {
691
+ return model.fields.filter((f) => f.kind === "relation" && f.many).map((field) => ({ field, where: void 0 }));
692
+ }
693
+ if (!isPlainObject(spec) || Object.keys(spec).some((k) => k !== "select")) {
694
+ throw new CyphraValidationError(
695
+ `${label}._count on ${model.name} takes true or { select: { <relation>: true | { where } } }.`
696
+ );
697
+ }
698
+ if (!isPlainObject(spec.select)) {
699
+ throw new CyphraValidationError(`${label}._count.select on ${model.name} must be an object.`);
700
+ }
701
+ const out = [];
702
+ for (const [key, v] of Object.entries(spec.select)) {
703
+ if (v === void 0 || v === false) continue;
704
+ const field = relationField(model, key);
705
+ if (!field) {
706
+ throw new CyphraValidationError(
707
+ `Unknown relation "${model.name}.${key}" in ${label}._count.select.`
708
+ );
709
+ }
710
+ if (!field.many) {
711
+ throw new CyphraValidationError(
712
+ `${model.name}.${key} is a to-one relation; only to-many relations can be counted.`
713
+ );
714
+ }
715
+ if (v === true) out.push({ field, where: void 0 });
716
+ else if (isPlainObject(v) && Object.keys(v).every((k) => k === "where")) {
717
+ out.push({ field, where: v.where });
718
+ } else {
719
+ throw new CyphraValidationError(
720
+ `${label}._count.select.${key} on ${model.name} takes true or { where }.`
721
+ );
722
+ }
723
+ }
724
+ return out;
725
+ }
644
726
  function decodeRow(shape, row) {
645
727
  if (row === null || row === void 0) return null;
646
728
  const src = row;
@@ -660,6 +742,12 @@ function decodeRow(shape, row) {
660
742
  const v = src[r.field.name];
661
743
  out[r.field.name] = r.field.many ? (v ?? []).map(decodeItem) : decodeItem(v);
662
744
  }
745
+ if (shape.counts) {
746
+ const raw = src["_count"] ?? {};
747
+ const counts = {};
748
+ for (const f of shape.counts) counts[f.name] = decodeCount(raw[f.name]);
749
+ out._count = counts;
750
+ }
663
751
  return out;
664
752
  }
665
753
 
@@ -707,7 +795,7 @@ function aggExpr(alias, op, target) {
707
795
  }
708
796
  }
709
797
  function decodeAgg(op, target, v) {
710
- if (op === "_count") return isInt2(v) ? integerToNumber(v) : Number(v ?? 0);
798
+ if (op === "_count") return decodeCount(v);
711
799
  if (v === null || v === void 0) return null;
712
800
  if (op === "_avg") return isInt2(v) ? integerToNumber(v) : Number(v);
713
801
  return decodeScalar(target, v);
@@ -1040,10 +1128,311 @@ function compileGroupBy(ctx, model, args) {
1040
1128
  };
1041
1129
  }
1042
1130
 
1043
- // src/orm/engine.ts
1131
+ // src/orm/path.ts
1132
+ function compilePath(ctx, path) {
1133
+ const x = ctx.variable("x");
1134
+ const i = ctx.variable("i");
1135
+ const rel = `relationships(${path})[${i}]`;
1136
+ const nodes = `[${x} IN nodes(${path}) | {labels: labels(${x}), properties: properties(${x})}]`;
1137
+ const edges = `[${i} IN range(0, length(${path}) - 1) | {type: type(${rel}), properties: properties(${rel}), out: startNode(${rel}) = nodes(${path})[${i}]}]`;
1138
+ return `{nodes: ${nodes}, edges: ${edges}}`;
1139
+ }
1140
+ function decodeProps(fields, raw) {
1141
+ const src = raw ?? {};
1142
+ const out = {};
1143
+ for (const f of fields) out[f.name] = decodeScalar(f, src[f.name]);
1144
+ return out;
1145
+ }
1146
+ function scalarsOf(model) {
1147
+ return model.fields.filter((f) => f.kind === "scalar");
1148
+ }
1149
+ function decodePath(schema, raw) {
1150
+ const src = raw ?? {};
1151
+ const rawNodes = src.nodes ?? [];
1152
+ const models = rawNodes.map((n) => schema.nodes.find((m) => (n.labels ?? []).includes(m.label)));
1153
+ const nodes = rawNodes.map((n, i) => {
1154
+ const model = models[i];
1155
+ return model ? decodeProps(scalarsOf(model), n.properties) : toNative(n.properties ?? {});
1156
+ });
1157
+ const rawEdges = src.edges ?? [];
1158
+ const edges = rawEdges.map((e, i) => {
1159
+ const type = String(e.type);
1160
+ const out = e.out === true;
1161
+ const start = models[out ? i : i + 1]?.name;
1162
+ const end = models[out ? i + 1 : i]?.name;
1163
+ const candidates = schema.relationships.filter((r) => r.relType === type);
1164
+ const edgeModel = candidates.find((r) => r.from === start && r.to === end) ?? (candidates.length === 1 ? candidates[0] : void 0);
1165
+ return {
1166
+ type,
1167
+ direction: out ? "out" : "in",
1168
+ properties: edgeModel ? decodeProps(edgeModel.properties, e.properties) : {}
1169
+ };
1170
+ });
1171
+ return { nodes, edges };
1172
+ }
1173
+
1174
+ // src/orm/traverse.ts
1175
+ var DEFAULT_MAX_TRAVERSAL_DEPTH = 10;
1176
+ var ARG_KEYS = /* @__PURE__ */ new Set([
1177
+ "from",
1178
+ "via",
1179
+ "direction",
1180
+ "depth",
1181
+ "where",
1182
+ "edgeWhere",
1183
+ "distinct",
1184
+ "select",
1185
+ "include",
1186
+ "orderBy",
1187
+ "skip",
1188
+ "take",
1189
+ "returnPaths"
1190
+ ]);
1044
1191
  function isPlainObject3(v) {
1045
1192
  return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1046
1193
  }
1194
+ function hopBound(v, name, min, cap, op = "traverse") {
1195
+ if (typeof v !== "number" || !Number.isInteger(v) || v < min) {
1196
+ throw new CyphraValidationError(`${op}: ${name} must be an integer >= ${min}.`);
1197
+ }
1198
+ if (cap !== void 0 && v > cap) {
1199
+ throw new CyphraValidationError(
1200
+ `${op}: ${name} is ${v}, above the maximum traversal depth of ${cap} (client option maxTraversalDepth).`
1201
+ );
1202
+ }
1203
+ return v;
1204
+ }
1205
+ function parseDepth(depth, cap) {
1206
+ if (!isPlainObject3(depth) || depth.max === void 0) {
1207
+ throw new CyphraValidationError(
1208
+ "traverse: depth.max is required (depth: { min?: number, max: number })."
1209
+ );
1210
+ }
1211
+ for (const k of Object.keys(depth)) {
1212
+ if (k !== "min" && k !== "max") {
1213
+ throw new CyphraValidationError(`traverse: unknown depth option "${k}".`);
1214
+ }
1215
+ }
1216
+ const max = hopBound(depth.max, "depth.max", 1, cap);
1217
+ const min = depth.min === void 0 ? 1 : hopBound(depth.min, "depth.min", 0);
1218
+ if (min > max) {
1219
+ throw new CyphraValidationError(`traverse: depth.min (${min}) is above depth.max (${max}).`);
1220
+ }
1221
+ return { min, max };
1222
+ }
1223
+ function viaRelations(model, via, op = "traverse") {
1224
+ const names = Array.isArray(via) ? via : [via];
1225
+ if (via === void 0 || names.length === 0) {
1226
+ throw new CyphraValidationError(
1227
+ `${op} on ${model.name}: via is required (a relation name or a list of them).`
1228
+ );
1229
+ }
1230
+ const out = [];
1231
+ for (const name of names) {
1232
+ const rel = typeof name === "string" ? relationField(model, name) : void 0;
1233
+ if (!rel) {
1234
+ throw new CyphraValidationError(
1235
+ `${op}: unknown relation "${model.name}.${String(name)}" in via.`
1236
+ );
1237
+ }
1238
+ if (rel.target !== model.name) {
1239
+ throw new CyphraValidationError(
1240
+ `${op}: ${model.name}.${rel.name} leads to ${rel.target}; via takes relations from ${model.name} to ${model.name}.`
1241
+ );
1242
+ }
1243
+ if (!out.includes(rel)) out.push(rel);
1244
+ }
1245
+ return out;
1246
+ }
1247
+ function compileHop(ctx, model, rels, direction, edgePredicate, target, op = "traverse") {
1248
+ if (direction !== void 0 && direction !== "out" && direction !== "in" && direction !== "both") {
1249
+ throw new CyphraValidationError(`${op}: direction must be "out", "in" or "both".`);
1250
+ }
1251
+ const byType = /* @__PURE__ */ new Map();
1252
+ for (const rel of rels) {
1253
+ const dirs = byType.get(rel.relType) ?? /* @__PURE__ */ new Set();
1254
+ if (direction === "both") dirs.add("OUT").add("IN");
1255
+ else dirs.add(direction === "out" ? "OUT" : direction === "in" ? "IN" : rel.direction);
1256
+ byType.set(rel.relType, dirs);
1257
+ }
1258
+ const kinds = new Set([...byType.values()].map((d) => d.size === 2 ? "BOTH" : [...d][0]));
1259
+ const e = ctx.variable("e");
1260
+ const types = [...byType.keys()].map(q).join("|");
1261
+ const label = `:${q(model.label)}`;
1262
+ const preds = [];
1263
+ let pattern;
1264
+ if (kinds.size === 1) {
1265
+ const kind = [...kinds][0];
1266
+ const edge = `[${e}:${types}]`;
1267
+ const arrow = kind === "OUT" ? `-${edge}->` : kind === "IN" ? `<-${edge}-` : `-${edge}-`;
1268
+ pattern = `(${label})${arrow}(${target ?? ""}${label})`;
1269
+ } else {
1270
+ const x = ctx.variable("x");
1271
+ const y = target ?? ctx.variable("y");
1272
+ pattern = `(${x}${label})-[${e}:${types}]-(${y}${label})`;
1273
+ const alts = [...byType].map(([type, dirs]) => {
1274
+ const t = `type(${e}) = ${ctx.param(type)}`;
1275
+ if (dirs.size === 2) return t;
1276
+ return `${t} AND ${dirs.has("OUT") ? "startNode" : "endNode"}(${e}) = ${x}`;
1277
+ });
1278
+ preds.push(alts.map((a) => `(${a})`).join(" OR "));
1279
+ }
1280
+ const edgeWhere = edgePredicate(e);
1281
+ if (edgeWhere) preds.push(edgeWhere);
1282
+ const where = preds.length === 0 ? "" : ` WHERE ${preds.map((p) => `(${p})`).join(" AND ")}`;
1283
+ return `${pattern}${where}`;
1284
+ }
1285
+ function edgeWhereModel(schema, model, rels, op = "traverse") {
1286
+ const names = new Set(rels.map((r) => r.edge));
1287
+ const name = rels[0].edge;
1288
+ const edge = name ? schema.relationships.find((r) => r.name === name) : void 0;
1289
+ if (!edge || names.size !== 1) {
1290
+ throw new CyphraValidationError(
1291
+ `${op}: edgeWhere needs every relation in via (${rels.map((r) => `${model.name}.${r.name}`).join(", ")}) to share one relationship { \u2026 } model.`
1292
+ );
1293
+ }
1294
+ return { name: edge.name, label: edge.relType, uniqueFields: [], fields: edge.properties };
1295
+ }
1296
+ function compileTraverse(ctx, model, args, maxDepth) {
1297
+ for (const k of Object.keys(args)) {
1298
+ if (!ARG_KEYS.has(k)) throw new CyphraValidationError(`traverse: unknown argument "${k}".`);
1299
+ }
1300
+ if (!isPlainObject3(args.from)) {
1301
+ throw new CyphraValidationError(
1302
+ `traverse on ${model.name}: from is required (a where filter on the start nodes).`
1303
+ );
1304
+ }
1305
+ const rels = viaRelations(model, args.via);
1306
+ const { min, max } = parseDepth(args.depth, maxDepth);
1307
+ const distinct = args.distinct ?? true;
1308
+ const returnPaths = args.returnPaths ?? false;
1309
+ if (typeof distinct !== "boolean") throw new CyphraValidationError("distinct must be a boolean.");
1310
+ if (typeof returnPaths !== "boolean") {
1311
+ throw new CyphraValidationError("returnPaths must be a boolean.");
1312
+ }
1313
+ const label = q(model.label);
1314
+ const from = compileWhere(ctx, model, "s", args.from);
1315
+ const hop = compileHop(
1316
+ ctx,
1317
+ model,
1318
+ rels,
1319
+ args.direction,
1320
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels), e, args.edgeWhere)
1321
+ );
1322
+ const reached = [min > 0 ? "n <> s" : null, compileWhere(ctx, model, "n", args.where)].filter(
1323
+ (x) => Boolean(x)
1324
+ );
1325
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1326
+ text += `MATCH ${returnPaths ? "p = " : ""}(s)(${hop}){${min},${max}}(n:${label})`;
1327
+ if (reached.length) text += ` WHERE ${reached.map((x) => `(${x})`).join(" AND ")}`;
1328
+ const paging = compilePaging(ctx, model, "n", args);
1329
+ const keep = returnPaths ? "n, p" : "n";
1330
+ if (returnPaths && distinct) {
1331
+ const x = ctx.variable("x");
1332
+ text += ` WITH n, collect(p) AS ps, min(length(p)) AS d`;
1333
+ text += ` WITH n, [${x} IN ps WHERE length(${x}) = d][0] AS p`;
1334
+ if (paging) text += ` WITH n, p${paging}`;
1335
+ } else {
1336
+ text += ` WITH ${distinct ? "DISTINCT " : ""}${keep}${paging}`;
1337
+ }
1338
+ const { expr, shape } = compileProjection(ctx, model, "n", args);
1339
+ text += ` RETURN ${expr} AS row`;
1340
+ if (returnPaths) text += `, ${compilePath(ctx, "p")} AS path`;
1341
+ const order = compileOrderBy(ctx, model, "n", args.orderBy);
1342
+ if (order) text += ` ORDER BY ${order}`;
1343
+ return {
1344
+ text,
1345
+ params: ctx.params,
1346
+ decode: (rows) => rows.map((r) => {
1347
+ const node = decodeRow(shape, r.row);
1348
+ return returnPaths ? { node, path: decodePath(ctx.schema, r.path) } : node;
1349
+ })
1350
+ };
1351
+ }
1352
+
1353
+ // src/orm/shortest.ts
1354
+ var ARG_KEYS2 = /* @__PURE__ */ new Set([
1355
+ "from",
1356
+ "to",
1357
+ "via",
1358
+ "direction",
1359
+ "maxDepth",
1360
+ "where",
1361
+ "edgeWhere",
1362
+ "select",
1363
+ "include"
1364
+ ]);
1365
+ function isPlainObject4(v) {
1366
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1367
+ }
1368
+ function compileShortestPath(ctx, model, args, cap, all) {
1369
+ const op = all ? "allShortestPaths" : "shortestPath";
1370
+ for (const k of Object.keys(args)) {
1371
+ if (!ARG_KEYS2.has(k) && !(all && k === "take")) {
1372
+ throw new CyphraValidationError(`${op}: unknown argument "${k}".`);
1373
+ }
1374
+ }
1375
+ for (const end of ["from", "to"]) {
1376
+ if (!isPlainObject4(args[end])) {
1377
+ throw new CyphraValidationError(
1378
+ `${op} on ${model.name}: ${end} is required (a where filter on the ${end === "from" ? "start" : "end"} nodes).`
1379
+ );
1380
+ }
1381
+ }
1382
+ if (args.maxDepth === void 0) {
1383
+ throw new CyphraValidationError(`${op} on ${model.name}: maxDepth is required.`);
1384
+ }
1385
+ const max = hopBound(args.maxDepth, "maxDepth", 1, cap, op);
1386
+ const rels = viaRelations(model, args.via, op);
1387
+ const label = q(model.label);
1388
+ const from = compileWhere(ctx, model, "s", args.from);
1389
+ const to = compileWhere(ctx, model, "t", args.to);
1390
+ const y = args.where === void 0 ? void 0 : ctx.variable("y");
1391
+ const hop = compileHop(
1392
+ ctx,
1393
+ model,
1394
+ rels,
1395
+ args.direction,
1396
+ (e) => args.edgeWhere === void 0 ? null : compileWhere(ctx, edgeWhereModel(ctx.schema, model, rels, op), e, args.edgeWhere),
1397
+ y,
1398
+ op
1399
+ );
1400
+ let pattern = `(s)(${hop}){0,${max}}(t)`;
1401
+ if (y) {
1402
+ const x = ctx.variable("x");
1403
+ const where = compileWhere(ctx, model, x, args.where);
1404
+ if (where) pattern = `(${pattern} WHERE all(${x} IN ${y}[..-1] WHERE ${where}))`;
1405
+ }
1406
+ let text = `MATCH (s:${label})${from ? ` WHERE ${from}` : ""} `;
1407
+ text += `MATCH (t:${label})${to ? ` WHERE ${to}` : ""} `;
1408
+ text += `MATCH p = ${all ? "ALL SHORTEST" : "SHORTEST 1"} ${pattern}`;
1409
+ if (all) {
1410
+ const x = ctx.variable("x");
1411
+ text += ` WITH collect(p) AS ps, min(length(p)) AS d`;
1412
+ text += ` UNWIND [${x} IN ps WHERE length(${x}) = d] AS p`;
1413
+ if (args.take !== void 0) {
1414
+ text += ` WITH p LIMIT ${ctx.param(intParam(nonNegativeInt(args.take, "take")))}`;
1415
+ }
1416
+ } else {
1417
+ text += ` WITH p ORDER BY length(p) LIMIT 1`;
1418
+ }
1419
+ const n = ctx.variable("n");
1420
+ const { expr, shape } = compileProjection(ctx, model, n, args);
1421
+ text += ` RETURN [${n} IN nodes(p) | ${expr}] AS nodes, ${compilePath(ctx, "p")} AS path`;
1422
+ return {
1423
+ text,
1424
+ params: ctx.params,
1425
+ decode: (rows) => rows.map((r) => ({
1426
+ nodes: (r.nodes ?? []).map((node) => decodeRow(shape, node)),
1427
+ edges: decodePath(ctx.schema, r.path).edges
1428
+ }))
1429
+ };
1430
+ }
1431
+
1432
+ // src/orm/engine.ts
1433
+ function isPlainObject5(v) {
1434
+ return typeof v === "object" && v !== null && !Array.isArray(v) && !(v instanceof Date);
1435
+ }
1047
1436
  function toCount(v) {
1048
1437
  return isInt3(v) ? integerToNumber(v) : Number(v ?? 0);
1049
1438
  }
@@ -1065,14 +1454,16 @@ function asArray(v) {
1065
1454
  return Array.isArray(v) ? v : [v];
1066
1455
  }
1067
1456
  var ModelEngine = class _ModelEngine {
1068
- constructor(schema, model, runner) {
1457
+ constructor(schema, model, runner, options = {}) {
1069
1458
  this.schema = schema;
1070
1459
  this.model = model;
1071
1460
  this.runner = runner;
1461
+ this.options = options;
1072
1462
  }
1073
1463
  schema;
1074
1464
  model;
1075
1465
  runner;
1466
+ options;
1076
1467
  ctx() {
1077
1468
  return new QueryContext(this.schema);
1078
1469
  }
@@ -1091,7 +1482,7 @@ var ModelEngine = class _ModelEngine {
1091
1482
  if (where) text += ` WHERE ${where}`;
1092
1483
  if (paging) text += ` WITH n${paging}`;
1093
1484
  text += ` RETURN ${expr} AS row`;
1094
- const order = compileOrderBy(this.model, "n", args.orderBy);
1485
+ const order = compileOrderBy(ctx, this.model, "n", args.orderBy);
1095
1486
  if (order) text += ` ORDER BY ${order}`;
1096
1487
  const rows = await exec(text, ctx.params);
1097
1488
  return rows.map((r) => decodeRow(shape, r.row));
@@ -1107,9 +1498,9 @@ var ModelEngine = class _ModelEngine {
1107
1498
  return decodeRow(shape, rows[0].row);
1108
1499
  }
1109
1500
  assertUnique(where, op) {
1110
- const ok = isPlainObject3(where) && this.model.uniqueFields.some((k) => {
1501
+ const ok = isPlainObject5(where) && this.model.uniqueFields.some((k) => {
1111
1502
  const v = where[k];
1112
- return v !== void 0 && v !== null && !isPlainObject3(v);
1503
+ return v !== void 0 && v !== null && !isPlainObject5(v);
1113
1504
  });
1114
1505
  if (!ok) {
1115
1506
  throw new CyphraValidationError(
@@ -1159,7 +1550,7 @@ var ModelEngine = class _ModelEngine {
1159
1550
  /** One statement; see {@link compileAggregate}. */
1160
1551
  aggregate(args = {}) {
1161
1552
  return this.runner.read(async (exec) => {
1162
- if (!isPlainObject3(args))
1553
+ if (!isPlainObject5(args))
1163
1554
  throw new CyphraValidationError("aggregate args must be an object.");
1164
1555
  const c = compileAggregate(this.ctx(), this.model, args);
1165
1556
  return c.decode(await exec(c.text, c.params));
@@ -1168,11 +1559,40 @@ var ModelEngine = class _ModelEngine {
1168
1559
  /** One statement; see {@link compileGroupBy}. */
1169
1560
  groupBy(args) {
1170
1561
  return this.runner.read(async (exec) => {
1171
- if (!isPlainObject3(args)) throw new CyphraValidationError("groupBy args must be an object.");
1562
+ if (!isPlainObject5(args)) throw new CyphraValidationError("groupBy args must be an object.");
1172
1563
  const c = compileGroupBy(this.ctx(), this.model, args);
1173
1564
  return c.decode(await exec(c.text, c.params));
1174
1565
  });
1175
1566
  }
1567
+ /** One statement; see {@link compileTraverse}. */
1568
+ traverse(args) {
1569
+ return this.runner.read(async (exec) => {
1570
+ if (!isPlainObject5(args)) throw new CyphraValidationError("traverse args must be an object.");
1571
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1572
+ const c = compileTraverse(this.ctx(), this.model, args, max);
1573
+ return c.decode(await exec(c.text, c.params));
1574
+ });
1575
+ }
1576
+ /** One statement; see {@link compileShortestPath}. */
1577
+ async shortestPath(args) {
1578
+ return (await this.shortest(args, false))[0] ?? null;
1579
+ }
1580
+ /** One statement; see {@link compileShortestPath}. */
1581
+ allShortestPaths(args) {
1582
+ return this.shortest(args, true);
1583
+ }
1584
+ shortest(args, all) {
1585
+ return this.runner.read(async (exec) => {
1586
+ if (!isPlainObject5(args)) {
1587
+ throw new CyphraValidationError(
1588
+ `${all ? "allShortestPaths" : "shortestPath"} args must be an object.`
1589
+ );
1590
+ }
1591
+ const max = this.options.maxTraversalDepth ?? DEFAULT_MAX_TRAVERSAL_DEPTH;
1592
+ const c = compileShortestPath(this.ctx(), this.model, args, max, all);
1593
+ return c.decode(await exec(c.text, c.params));
1594
+ });
1595
+ }
1176
1596
  // -------------------------------------------------------------------------
1177
1597
  // Write helpers
1178
1598
  // -------------------------------------------------------------------------
@@ -1180,7 +1600,7 @@ var ModelEngine = class _ModelEngine {
1180
1600
  return new QueryContext(this.schema).node(name);
1181
1601
  }
1182
1602
  engineFor(model) {
1183
- return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner);
1603
+ return model === this.model ? this : new _ModelEngine(this.schema, model, this.runner, this.options);
1184
1604
  }
1185
1605
  /** Encode scalar data for CREATE, applying defaults and checking required fields. */
1186
1606
  static createProps(owner, fields, data) {
@@ -1207,7 +1627,7 @@ var ModelEngine = class _ModelEngine {
1207
1627
  return props;
1208
1628
  }
1209
1629
  splitData(data, op) {
1210
- if (!isPlainObject3(data))
1630
+ if (!isPlainObject5(data))
1211
1631
  throw new CyphraValidationError(`${this.model.name}.${op}: data must be an object.`);
1212
1632
  const scalars = {};
1213
1633
  const relations = {};
@@ -1231,7 +1651,7 @@ var ModelEngine = class _ModelEngine {
1231
1651
  `${this.model.name}.${rel.name}: $edge given but no relationship model types this edge.`
1232
1652
  );
1233
1653
  }
1234
- if (!isPlainObject3(input)) throw new CyphraValidationError("$edge must be an object.");
1654
+ if (!isPlainObject5(input)) throw new CyphraValidationError("$edge must be an object.");
1235
1655
  for (const k of Object.keys(input)) {
1236
1656
  if (!edgeModel.properties.some((p) => p.name === k)) {
1237
1657
  throw new CyphraValidationError(`Unknown edge property "${edgeModel.name}.${k}".`);
@@ -1250,7 +1670,7 @@ var ModelEngine = class _ModelEngine {
1250
1670
  }
1251
1671
  /** Only the `$edge` properties the caller set (no defaults), for updating an existing edge. */
1252
1672
  explicitEdgeProps(rel, input) {
1253
- if (!rel.edge || !isPlainObject3(input)) return {};
1673
+ if (!rel.edge || !isPlainObject5(input)) return {};
1254
1674
  const edgeModel = this.schema.relationships.find((r) => r.name === rel.edge);
1255
1675
  const props = {};
1256
1676
  for (const f of edgeModel.properties) {
@@ -1287,7 +1707,7 @@ var ModelEngine = class _ModelEngine {
1287
1707
  * defaults, e.g. `@default(now())`, are kept).
1288
1708
  */
1289
1709
  async connect(exec, id, rel, item) {
1290
- if (!isPlainObject3(item))
1710
+ if (!isPlainObject5(item))
1291
1711
  throw new CyphraValidationError(`${rel.name}.connect expects unique where objects.`);
1292
1712
  const { $edge, ...where } = item;
1293
1713
  const target = this.node(rel.target);
@@ -1320,7 +1740,7 @@ var ModelEngine = class _ModelEngine {
1320
1740
  }
1321
1741
  }
1322
1742
  async createRelated(exec, id, rel, item) {
1323
- if (!isPlainObject3(item))
1743
+ if (!isPlainObject5(item))
1324
1744
  throw new CyphraValidationError(`${rel.name}.create expects objects.`);
1325
1745
  const { $edge, ...data } = item;
1326
1746
  const props = this.edgeProps(rel, $edge);
@@ -1342,7 +1762,7 @@ var ModelEngine = class _ModelEngine {
1342
1762
  return toCount(rows[0]?.c);
1343
1763
  }
1344
1764
  async writeRelation(exec, id, rel, spec, mode) {
1345
- if (!isPlainObject3(spec)) {
1765
+ if (!isPlainObject5(spec)) {
1346
1766
  throw new CyphraValidationError(
1347
1767
  `${this.model.name}.${rel.name}: relation writes take { create, connect, \u2026 }.`
1348
1768
  );
@@ -1375,7 +1795,7 @@ var ModelEngine = class _ModelEngine {
1375
1795
  if (rel.many) {
1376
1796
  if (disconnect !== void 0) {
1377
1797
  for (const item of asArray(disconnect)) {
1378
- if (!isPlainObject3(item))
1798
+ if (!isPlainObject5(item))
1379
1799
  throw new CyphraValidationError(`${rel.name}.disconnect expects unique where objects.`);
1380
1800
  this.engineFor(this.node(rel.target)).assertUnique(
1381
1801
  item,
@@ -1408,7 +1828,7 @@ var ModelEngine = class _ModelEngine {
1408
1828
  for (const [k, v] of Object.entries(scalars)) {
1409
1829
  const f = scalarField(this.model, k);
1410
1830
  const ref = `n.${q(k)}`;
1411
- if (isPlainObject3(v) && !f.list) {
1831
+ if (isPlainObject5(v) && !f.list) {
1412
1832
  if (f.type !== "Int" && f.type !== "Float") {
1413
1833
  throw new CyphraValidationError(
1414
1834
  `${this.model.name}.${k}: object updates are only for numbers.`
@@ -1515,7 +1935,7 @@ var ModelEngine = class _ModelEngine {
1515
1935
  const where = args.where;
1516
1936
  const key = this.model.uniqueFields.find((k) => {
1517
1937
  const v = where[k];
1518
- return v !== void 0 && v !== null && !isPlainObject3(v);
1938
+ return v !== void 0 && v !== null && !isPlainObject5(v);
1519
1939
  });
1520
1940
  const keyField = scalarField(this.model, key);
1521
1941
  const create = this.splitData(args.create, "upsert create");
@@ -1609,12 +2029,12 @@ function txExecutor(tx, debug) {
1609
2029
  return res.records.map((r) => r.toObject());
1610
2030
  };
1611
2031
  }
1612
- function buildDelegates(schema, runner) {
2032
+ function buildDelegates(schema, runner, options) {
1613
2033
  const out = {};
1614
2034
  for (const node of schema.nodes) {
1615
2035
  const key = delegateKey(node.name);
1616
2036
  if (key.startsWith("$")) throw new Error(`Model name "${node.name}" is reserved.`);
1617
- out[key] = new ModelEngine(schema, node, runner);
2037
+ out[key] = new ModelEngine(schema, node, runner, options);
1618
2038
  }
1619
2039
  return out;
1620
2040
  }
@@ -1626,6 +2046,11 @@ function rawFor(runner) {
1626
2046
  };
1627
2047
  }
1628
2048
  function createOrm(schema, options) {
2049
+ const { maxTraversalDepth } = options;
2050
+ if (maxTraversalDepth !== void 0 && (!Number.isInteger(maxTraversalDepth) || maxTraversalDepth < 1)) {
2051
+ throw new CyphraValidationError("maxTraversalDepth must be a positive integer.");
2052
+ }
2053
+ const engineOptions = { maxTraversalDepth };
1629
2054
  const owns = !("client" in options);
1630
2055
  const client = "client" in options ? options.client : new CyphraClient(options);
1631
2056
  const debug = options.debug ?? false;
@@ -1636,11 +2061,11 @@ function createOrm(schema, options) {
1636
2061
  const transaction = (fn) => client.withWriteTransaction((tx) => {
1637
2062
  const exec = txExecutor(tx, debug);
1638
2063
  const inTx = { read: (f) => f(exec), write: (f) => f(exec) };
1639
- const txClient = { ...buildDelegates(schema, inTx), $cypher: rawFor(inTx) };
2064
+ const txClient = { ...buildDelegates(schema, inTx, engineOptions), $cypher: rawFor(inTx) };
1640
2065
  return fn(txClient);
1641
2066
  });
1642
2067
  return {
1643
- ...buildDelegates(schema, runner),
2068
+ ...buildDelegates(schema, runner, engineOptions),
1644
2069
  $cypher: rawFor(runner),
1645
2070
  $transaction: transaction,
1646
2071
  $client: client,