@coasys/ad4m 0.13.0-test-model-layer → 0.13.0-test-flows-1

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.
Files changed (55) hide show
  1. package/lib/index.cjs +817 -65
  2. package/lib/index.js +814 -66
  3. package/lib/src/ai/AIClient.d.ts +13 -0
  4. package/lib/src/ai/AIClient.js +15 -0
  5. package/lib/src/ai/AITypes.d.ts +5 -0
  6. package/lib/src/index.js +2 -0
  7. package/lib/src/model/Ad4mModel.d.ts +6 -1
  8. package/lib/src/model/Ad4mModel.js +41 -6
  9. package/lib/src/model/ModelQueryBuilder.d.ts +47 -3
  10. package/lib/src/model/ModelQueryBuilder.js +97 -6
  11. package/lib/src/model/query-common.d.ts +10 -1
  12. package/lib/src/model/query-common.js +16 -0
  13. package/lib/src/model/query-sparql.d.ts +11 -0
  14. package/lib/src/model/query-sparql.js +93 -1
  15. package/lib/src/model/query-utils.js +16 -0
  16. package/lib/src/model/shacl-gen.js +12 -0
  17. package/lib/src/model/types.d.ts +320 -3
  18. package/lib/src/model/types.js +9 -0
  19. package/lib/src/perspectives/AutoProcessor.d.ts +8 -0
  20. package/lib/src/perspectives/FlowInstance.d.ts +176 -12
  21. package/lib/src/perspectives/FlowInstance.js +77 -13
  22. package/lib/src/perspectives/FlowModels.d.ts +40 -9
  23. package/lib/src/perspectives/FlowModels.js +59 -13
  24. package/lib/src/perspectives/PerspectiveClient.d.ts +18 -0
  25. package/lib/src/perspectives/PerspectiveClient.js +30 -0
  26. package/lib/src/perspectives/PerspectiveProxy.d.ts +69 -2
  27. package/lib/src/perspectives/PerspectiveProxy.js +157 -7
  28. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +55 -5
  29. package/lib/src/perspectives/WakerSubscriptionManager.js +183 -8
  30. package/lib/src/shacl/SHACLFlow.d.ts +43 -0
  31. package/package.json +1 -1
  32. package/src/ai/AIClient.ts +16 -0
  33. package/src/ai/AITypes.ts +5 -0
  34. package/src/index.ts +2 -0
  35. package/src/model/Ad4mModel.test.ts +442 -0
  36. package/src/model/Ad4mModel.ts +39 -7
  37. package/src/model/ModelQueryBuilder.ts +101 -10
  38. package/src/model/query-common.ts +20 -1
  39. package/src/model/query-sparql.test.ts +115 -0
  40. package/src/model/query-sparql.ts +97 -1
  41. package/src/model/query-utils.ts +18 -0
  42. package/src/model/relation-filtering.test.ts +7 -0
  43. package/src/model/shacl-gen.ts +12 -0
  44. package/src/model/shacl-roundtrip.test.ts +71 -0
  45. package/src/model/types-typed-query.test.ts +42 -0
  46. package/src/model/types.ts +316 -6
  47. package/src/perspectives/AutoProcessor.ts +8 -0
  48. package/src/perspectives/FlowInstance.ts +194 -13
  49. package/src/perspectives/FlowModels.ts +53 -13
  50. package/src/perspectives/PerspectiveClient.ts +62 -0
  51. package/src/perspectives/PerspectiveProxy.test.ts +272 -0
  52. package/src/perspectives/PerspectiveProxy.ts +163 -7
  53. package/src/perspectives/WakerSubscriptionManager.test.ts +199 -0
  54. package/src/perspectives/WakerSubscriptionManager.ts +197 -9
  55. package/src/shacl/SHACLFlow.ts +44 -0
@@ -1448,6 +1448,301 @@ describe("ModelQueryBuilder paginateSubscribe", () => {
1448
1448
  expect(callArg).toHaveProperty("pageSize", 10);
1449
1449
  expect(callArg).toHaveProperty("pageNumber", 1);
1450
1450
  });
1451
+
1452
+ it("paginateSubscribe coalesces overlapping dispatches into a trailing fetch", async () => {
1453
+ // Two server dispatches arrive while the first re-fetch is still in
1454
+ // flight. A generation counter (#1020) would start both and could keep
1455
+ // the one that read 1 model while dropping the one that read 2. The
1456
+ // server then has nothing further to dispatch — "Paginate callback did
1457
+ // not see second model save". Coalesce: one in-flight read, then a
1458
+ // trailing fetch after the last dispatch.
1459
+ const mockSubscriptionId = "paginate-stale-sub";
1460
+ let capturedCallback: ((result: any) => void) | null = null;
1461
+
1462
+ const mockClient = {
1463
+ modelSubscribe: jest.fn().mockResolvedValue({
1464
+ subscriptionId: mockSubscriptionId,
1465
+ result: { instances: [], totalCount: 0 },
1466
+ }),
1467
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1468
+ capturedCallback = cb;
1469
+ return () => {};
1470
+ }),
1471
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1472
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1473
+ };
1474
+
1475
+ // First call is the initial fetch (resolves immediately, empty). Later
1476
+ // re-fetches are deferred so the test can see coalescing.
1477
+ const deferred: Array<(v: any) => void> = [];
1478
+ let call = 0;
1479
+ const mockPerspective = {
1480
+ uuid: "test-uuid",
1481
+ client: mockClient,
1482
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1483
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1484
+ }),
1485
+ modelQuery: jest.fn().mockImplementation(() => {
1486
+ call++;
1487
+ if (call === 1) return Promise.resolve({ instances: [], totalCount: 0 });
1488
+ return new Promise(resolve => { deferred.push(resolve); });
1489
+ }),
1490
+ } as any;
1491
+
1492
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1493
+
1494
+ @Model({ name: "StaleTest" })
1495
+ class StaleTest extends Ad4mModel {
1496
+ @Flag({ through: "test://type", value: "test://stale" })
1497
+ type: string = "test://stale";
1498
+ @Property({ through: "test://name" })
1499
+ name: string = "";
1500
+ }
1501
+
1502
+ const userCallback = jest.fn();
1503
+ const builder = StaleTest.query(mockPerspective);
1504
+ await builder.paginateSubscribe(10, 1, userCallback);
1505
+
1506
+ capturedCallback!({});
1507
+ capturedCallback!({});
1508
+ await new Promise(r => setTimeout(r, 10));
1509
+ expect(deferred.length).toBe(1);
1510
+
1511
+ // In-flight read saw only the first model.
1512
+ deferred[0]({ instances: [{ id: "m1" }], totalCount: 1 });
1513
+ await new Promise(r => setTimeout(r, 10));
1514
+ // Trailing fetch started because a dispatch arrived during that read.
1515
+ expect(deferred.length).toBe(2);
1516
+
1517
+ deferred[1]({ instances: [{ id: "m1" }, { id: "m2" }], totalCount: 2 });
1518
+ await new Promise(r => setTimeout(r, 10));
1519
+
1520
+ const lastArg = userCallback.mock.calls[userCallback.mock.calls.length - 1][0];
1521
+ expect(lastArg.totalCount).toBe(2);
1522
+ expect(lastArg.results.length).toBe(2);
1523
+
1524
+ builder.dispose();
1525
+ });
1526
+
1527
+ it("paginateSubscribe still runs the trailing fetch when the in-flight read rejects", async () => {
1528
+ const mockSubscriptionId = "paginate-reject-sub";
1529
+ let capturedCallback: ((result: any) => void) | null = null;
1530
+
1531
+ const mockClient = {
1532
+ modelSubscribe: jest.fn().mockResolvedValue({
1533
+ subscriptionId: mockSubscriptionId,
1534
+ result: { instances: [], totalCount: 0 },
1535
+ }),
1536
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1537
+ capturedCallback = cb;
1538
+ return () => {};
1539
+ }),
1540
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1541
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1542
+ };
1543
+
1544
+ const deferred: Array<{ resolve: (v: any) => void; reject: (e: any) => void }> = [];
1545
+ let call = 0;
1546
+ const mockPerspective = {
1547
+ uuid: "test-uuid",
1548
+ client: mockClient,
1549
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1550
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1551
+ }),
1552
+ modelQuery: jest.fn().mockImplementation(() => {
1553
+ call++;
1554
+ if (call === 1) return Promise.resolve({ instances: [], totalCount: 0 });
1555
+ return new Promise((resolve, reject) => { deferred.push({ resolve, reject }); });
1556
+ }),
1557
+ } as any;
1558
+
1559
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1560
+
1561
+ @Model({ name: "RejectTest" })
1562
+ class RejectTest extends Ad4mModel {
1563
+ @Flag({ through: "test://type", value: "test://reject" })
1564
+ type: string = "test://reject";
1565
+ @Property({ through: "test://name" })
1566
+ name: string = "";
1567
+ }
1568
+
1569
+ const userCallback = jest.fn();
1570
+ const builder = RejectTest.query(mockPerspective);
1571
+ await builder.paginateSubscribe(10, 1, userCallback);
1572
+
1573
+ capturedCallback!({});
1574
+ capturedCallback!({});
1575
+ await new Promise(r => setTimeout(r, 10));
1576
+ expect(deferred.length).toBe(1);
1577
+
1578
+ deferred[0].reject(new Error("re-fetch failed"));
1579
+ await new Promise(r => setTimeout(r, 10));
1580
+ expect(deferred.length).toBe(2);
1581
+
1582
+ deferred[1].resolve({ instances: [{ id: "m1" }, { id: "m2" }], totalCount: 2 });
1583
+ await new Promise(r => setTimeout(r, 10));
1584
+
1585
+ expect(userCallback).toHaveBeenCalled();
1586
+ const lastArg = userCallback.mock.calls[userCallback.mock.calls.length - 1][0];
1587
+ expect(lastArg.totalCount).toBe(2);
1588
+ expect(lastArg.results.length).toBe(2);
1589
+
1590
+ builder.dispose();
1591
+ });
1592
+
1593
+ it("paginateSubscribe handles a rejection from the trailing fetch", async () => {
1594
+ // The trailing fetch is started from the in-flight read's finally block,
1595
+ // detached from any caller. If it also rejects, only its own .catch()
1596
+ // observes the error; without one it is an unhandled rejection.
1597
+ const errorSpy = jest.spyOn(console, "error").mockImplementation(() => {});
1598
+ try {
1599
+ const mockSubscriptionId = "paginate-reject-twice-sub";
1600
+ let capturedCallback: ((result: any) => void) | null = null;
1601
+
1602
+ const mockClient = {
1603
+ modelSubscribe: jest.fn().mockResolvedValue({
1604
+ subscriptionId: mockSubscriptionId,
1605
+ result: { instances: [], totalCount: 0 },
1606
+ }),
1607
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1608
+ capturedCallback = cb;
1609
+ return () => {};
1610
+ }),
1611
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1612
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1613
+ };
1614
+
1615
+ const deferred: Array<{ resolve: (v: any) => void; reject: (e: any) => void }> = [];
1616
+ let call = 0;
1617
+ const mockPerspective = {
1618
+ uuid: "test-uuid",
1619
+ client: mockClient,
1620
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1621
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1622
+ }),
1623
+ modelQuery: jest.fn().mockImplementation(() => {
1624
+ call++;
1625
+ if (call === 1) return Promise.resolve({ instances: [], totalCount: 0 });
1626
+ return new Promise((resolve, reject) => { deferred.push({ resolve, reject }); });
1627
+ }),
1628
+ } as any;
1629
+
1630
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1631
+
1632
+ @Model({ name: "RejectTwiceTest" })
1633
+ class RejectTwiceTest extends Ad4mModel {
1634
+ @Flag({ through: "test://type", value: "test://reject-twice" })
1635
+ type: string = "test://reject-twice";
1636
+ @Property({ through: "test://name" })
1637
+ name: string = "";
1638
+ }
1639
+
1640
+ const userCallback = jest.fn();
1641
+ const builder = RejectTwiceTest.query(mockPerspective);
1642
+ await builder.paginateSubscribe(10, 1, userCallback);
1643
+
1644
+ capturedCallback!({});
1645
+ capturedCallback!({});
1646
+ await new Promise(r => setTimeout(r, 10));
1647
+ expect(deferred.length).toBe(1);
1648
+
1649
+ deferred[0].reject(new Error("in-flight read failed"));
1650
+ await new Promise(r => setTimeout(r, 10));
1651
+ expect(deferred.length).toBe(2);
1652
+
1653
+ deferred[1].reject(new Error("trailing read failed"));
1654
+ await new Promise(r => setTimeout(r, 10));
1655
+
1656
+ const logged = errorSpy.mock.calls
1657
+ .filter(args => args[0] === "Paginate subscription error:")
1658
+ .map(args => (args[1] as Error).message);
1659
+ expect(logged).toEqual(["in-flight read failed", "trailing read failed"]);
1660
+ expect(userCallback).not.toHaveBeenCalled();
1661
+
1662
+ builder.dispose();
1663
+ } finally {
1664
+ errorSpy.mockRestore();
1665
+ }
1666
+ });
1667
+
1668
+ it("paginateSubscribe delivers nothing and starts no trailing fetch after dispose", async () => {
1669
+ // dispose() while a read is in flight and a trailing fetch is pending.
1670
+ const mockSubscriptionId = "paginate-dispose-sub";
1671
+ let capturedCallback: ((result: any) => void) | null = null;
1672
+
1673
+ const mockClient = {
1674
+ modelSubscribe: jest.fn().mockResolvedValue({
1675
+ subscriptionId: mockSubscriptionId,
1676
+ result: { instances: [], totalCount: 0 },
1677
+ }),
1678
+ subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1679
+ capturedCallback = cb;
1680
+ return () => {};
1681
+ }),
1682
+ keepAliveQuery: jest.fn().mockResolvedValue(true),
1683
+ disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1684
+ };
1685
+
1686
+ const deferred: Array<{ resolve: (v: any) => void; reject: (e: any) => void }> = [];
1687
+ let call = 0;
1688
+ const mockPerspective = {
1689
+ uuid: "test-uuid",
1690
+ client: mockClient,
1691
+ modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string) => {
1692
+ return mockClient.modelSubscribe("test-uuid", className, queryJson);
1693
+ }),
1694
+ modelQuery: jest.fn().mockImplementation(() => {
1695
+ call++;
1696
+ if (call === 1) return Promise.resolve({ instances: [], totalCount: 0 });
1697
+ return new Promise((resolve, reject) => { deferred.push({ resolve, reject }); });
1698
+ }),
1699
+ } as any;
1700
+
1701
+ const { Ad4mModel, Model, Flag, Property } = require("./index");
1702
+
1703
+ @Model({ name: "DisposeMidReadTest" })
1704
+ class DisposeMidReadTest extends Ad4mModel {
1705
+ @Flag({ through: "test://type", value: "test://dispose-mid-read" })
1706
+ type: string = "test://dispose-mid-read";
1707
+ @Property({ through: "test://name" })
1708
+ name: string = "";
1709
+ }
1710
+
1711
+ const userCallback = jest.fn();
1712
+ const builder = DisposeMidReadTest.query(mockPerspective);
1713
+ await builder.paginateSubscribe(10, 1, userCallback);
1714
+
1715
+ capturedCallback!({});
1716
+ capturedCallback!({});
1717
+ await new Promise(r => setTimeout(r, 10));
1718
+ expect(deferred.length).toBe(1);
1719
+
1720
+ builder.dispose();
1721
+
1722
+ // The in-flight read's finally block still sees pending === true, so the
1723
+ // coalescing log must not claim a trailing fetch that the disposed guard
1724
+ // then drops.
1725
+ const debugSpy = jest.spyOn(console, "debug").mockImplementation(() => {});
1726
+ try {
1727
+ deferred[0].resolve({ instances: [{ id: "m1" }], totalCount: 1 });
1728
+ await new Promise(r => setTimeout(r, 10));
1729
+
1730
+ expect(userCallback).not.toHaveBeenCalled();
1731
+ expect(deferred.length).toBe(1);
1732
+ expect(
1733
+ debugSpy.mock.calls.filter(args =>
1734
+ String(args[0]).includes("coalesced into one trailing fetch")
1735
+ )
1736
+ ).toEqual([]);
1737
+
1738
+ // A dispatch that races the unsubscribe starts no read either.
1739
+ capturedCallback!({});
1740
+ await new Promise(r => setTimeout(r, 10));
1741
+ expect(deferred.length).toBe(1);
1742
+ } finally {
1743
+ debugSpy.mockRestore();
1744
+ }
1745
+ });
1451
1746
  });
1452
1747
 
1453
1748
  // ============================================================================
@@ -3139,3 +3434,150 @@ describe("Ordered relations", () => {
3139
3434
  expect(tasks!.ordering).toBe("linkedList");
3140
3435
  });
3141
3436
  });
3437
+
3438
+ /**
3439
+ * A traversal names its predicate the same two ways every other scope does.
3440
+ *
3441
+ * The feature shipped with only the raw spelling, so every caller reading a
3442
+ * thread wrote `'test://has_comment'` by hand — the literal `resolveParentPredicate`
3443
+ * exists to keep out of call sites, reintroduced by the newest scope.
3444
+ */
3445
+ describe("Ad4mModel.prepareModelQueryParams() — traverse scope", () => {
3446
+ @Model({ name: "TraverseComment" })
3447
+ class TraverseComment extends Ad4mModel {
3448
+ @Property({ through: "test://body" })
3449
+ body: string = "";
3450
+ }
3451
+
3452
+ @Model({ name: "TraversePost" })
3453
+ class TraversePost extends Ad4mModel {
3454
+ @HasMany(() => TraverseComment, { through: "test://has_comment" })
3455
+ comments: TraverseComment[] = [];
3456
+
3457
+ @HasOne(() => TraverseComment, { through: "test://pinned_comment" })
3458
+ pinned: TraverseComment | null = null;
3459
+ }
3460
+
3461
+ const parentOf = (query: any) =>
3462
+ JSON.parse((TraverseComment as any).prepareModelQueryParams(query).queryJson).parent;
3463
+
3464
+ it("keeps the raw spelling exactly as written", () => {
3465
+ expect(
3466
+ parentOf({ parent: { ids: ["we://a", "we://b"], predicate: "test://has_comment" } }),
3467
+ ).toEqual({ ids: ["we://a", "we://b"], predicate: "test://has_comment" });
3468
+ });
3469
+
3470
+ it("resolves the predicate from the model that declares the relation", () => {
3471
+ expect(parentOf({ parent: { ids: "we://a", model: TraversePost } })).toEqual({
3472
+ ids: "we://a",
3473
+ predicate: "test://has_comment",
3474
+ });
3475
+ });
3476
+
3477
+ it("takes `field` when one parent has two relations to the same child", () => {
3478
+ // Without it the scan finds `comments` first and a request for the pinned
3479
+ // comment's subtree would quietly read the wrong edge.
3480
+ expect(
3481
+ parentOf({ parent: { ids: "we://a", model: TraversePost, field: "pinned" } }),
3482
+ ).toEqual({ ids: "we://a", predicate: "test://pinned_comment" });
3483
+ });
3484
+
3485
+ it("sends the traversal's own options and nothing else", () => {
3486
+ // `model` is a constructor; spreading the scope would put a class into a
3487
+ // query variable. What travels is the resolved predicate and the options.
3488
+ expect(
3489
+ parentOf({
3490
+ parent: {
3491
+ ids: ["we://a"],
3492
+ model: TraversePost,
3493
+ field: "comments",
3494
+ transitive: true,
3495
+ direction: "in",
3496
+ limitPerAnchor: 5,
3497
+ },
3498
+ }),
3499
+ ).toEqual({
3500
+ ids: ["we://a"],
3501
+ predicate: "test://has_comment",
3502
+ transitive: true,
3503
+ direction: "in",
3504
+ limitPerAnchor: 5,
3505
+ });
3506
+ });
3507
+
3508
+ it("omits the options the caller did not set rather than sending defaults", () => {
3509
+ // An absent `transitive` is not `false` on the wire: the executor's serde
3510
+ // defaults own that, and sending our own would be a second opinion.
3511
+ const parent = parentOf({ parent: { ids: "we://a", model: TraversePost, levels: [10, 5] } });
3512
+ expect(parent).toEqual({ ids: "we://a", predicate: "test://has_comment", levels: [10, 5] });
3513
+ expect(parent).not.toHaveProperty("transitive");
3514
+ expect(parent).not.toHaveProperty("limitPerAnchor");
3515
+ });
3516
+ });
3517
+
3518
+ // ──────────────────────────────────────────────────────────
3519
+ // linkStatus — read from links of one status only (#1116)
3520
+ // ──────────────────────────────────────────────────────────
3521
+
3522
+ describe("linkStatus — wire format", () => {
3523
+ @Model({ name: "LinkStatusWireCard" })
3524
+ class LinkStatusWireCard extends Ad4mModel {
3525
+ @Flag({ through: "lsw://type", value: "lsw://card" })
3526
+ type: string = "";
3527
+
3528
+ @Property({ through: "lsw://title" })
3529
+ title: string = "";
3530
+ }
3531
+
3532
+ it("is omitted unless the caller sets it, so both statuses are read", () => {
3533
+ const { queryJson } = (LinkStatusWireCard as any).prepareModelQueryParams({});
3534
+ expect(JSON.parse(queryJson)).not.toHaveProperty("linkStatus");
3535
+ });
3536
+
3537
+ it("drops `linkStatus: null`, which reads both statuses like unset", () => {
3538
+ const { queryJson } = (LinkStatusWireCard as any).prepareModelQueryParams({
3539
+ linkStatus: null,
3540
+ });
3541
+ expect(JSON.parse(queryJson)).not.toHaveProperty("linkStatus");
3542
+ });
3543
+
3544
+ it("travels as `linkStatus` when set, from the query and the builder", () => {
3545
+ const { queryJson } = (LinkStatusWireCard as any).prepareModelQueryParams({
3546
+ linkStatus: "shared",
3547
+ });
3548
+ expect(JSON.parse(queryJson).linkStatus).toBe("shared");
3549
+
3550
+ const builder = LinkStatusWireCard.query({} as any).linkStatus("local");
3551
+ expect((builder as any).queryParams.linkStatus).toBe("local");
3552
+ });
3553
+ });
3554
+
3555
+ // ──────────────────────────────────────────────────────────
3556
+ // includeUnverified — opt-in to links whose signature did not verify (#1113)
3557
+ // ──────────────────────────────────────────────────────────
3558
+
3559
+ describe("includeUnverified — wire format", () => {
3560
+ @Model({ name: "UnverifiedWireRecipe" })
3561
+ class UnverifiedWireRecipe extends Ad4mModel {
3562
+ @Flag({ through: "uv://type", value: "uv://recipe" })
3563
+ type: string = "";
3564
+
3565
+ @Property({ through: "uv://name" })
3566
+ name: string = "";
3567
+ }
3568
+
3569
+ it("is omitted unless the caller sets it, so the executor's default applies", () => {
3570
+ const { queryJson } = (UnverifiedWireRecipe as any).prepareModelQueryParams({});
3571
+ expect(JSON.parse(queryJson)).not.toHaveProperty("includeUnverified");
3572
+ });
3573
+
3574
+ it("travels as `includeUnverified` when set, from the query and the builder", () => {
3575
+ const { queryJson } = (UnverifiedWireRecipe as any).prepareModelQueryParams({
3576
+ includeUnverified: true,
3577
+ });
3578
+ expect(JSON.parse(queryJson).includeUnverified).toBe(true);
3579
+
3580
+ const builder = UnverifiedWireRecipe.query({} as any).includeUnverified();
3581
+ expect((builder as any).queryParams.includeUnverified).toBe(true);
3582
+ });
3583
+ });
@@ -7,7 +7,7 @@ import { makeRandomId } from "./util";
7
7
  import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
8
8
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
9
9
  import { formatQueryValue, compileWhereClause } from "./query-utils";
10
- import { resolveParentPredicate } from "./query-common";
10
+ import { requireSingleParent, resolveParentPredicate } from "./query-common";
11
11
  import { isArrayType, determinePredicate, determineNamespace, buildModelFromJSONSchema } from "./json-schema";
12
12
  import type { SHACLShape } from "../shacl/SHACLShape";
13
13
  import type { JSONSchemaProperty, JSONSchema, JSONSchemaToModelOptions } from "./json-schema";
@@ -22,8 +22,9 @@ import type {
22
22
  GetOptions, AllInstancesResult, ResultsWithTotalCount,
23
23
  PaginationResult, PropertyMetadata, RelationMetadata, ModelMetadata,
24
24
  IncludeProjection,
25
- TypedQuery, IncludeExtras, IncludeOf,
25
+ TypedQuery, IncludeExtras, IncludeOf, LinksMap,
26
26
  } from "./types";
27
+ import { isTraverseScope } from "./types";
27
28
 
28
29
 
29
30
 
@@ -392,6 +393,11 @@ export class Ad4mModel {
392
393
  author: string;
393
394
  createdAt: any;
394
395
  updatedAt: any;
396
+ /**
397
+ * Per-link rows for the entries asked for with `Query.links`, keyed as they
398
+ * were asked. Absent when the query did not ask for any.
399
+ */
400
+ declare __links?: LinksMap;
395
401
 
396
402
  /**
397
403
  * Backwards compatibility alias for createdAt.
@@ -990,7 +996,28 @@ export class Ad4mModel {
990
996
  const queryInput: any = {};
991
997
  if (query.parent) {
992
998
  const parentPredicate = resolveParentPredicate(query.parent, this);
993
- queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
999
+ // A traversal keeps its own shape on the wire: the executor reads `ids`,
1000
+ // and flattening it to one `id` here is how a request for a whole level
1001
+ // would quietly become a request for one parent's children.
1002
+ //
1003
+ // Its fields are named rather than spread, because `model` — the class
1004
+ // itself — is how the scope may name its predicate, and that is a
1005
+ // constructor, not something to put in a query variable. The predicate is
1006
+ // resolved above; what travels is the result.
1007
+ if (isTraverseScope(query.parent)) {
1008
+ const t = query.parent;
1009
+ const traverse: Record<string, unknown> = {
1010
+ ids: t.ids,
1011
+ predicate: parentPredicate,
1012
+ };
1013
+ if (t.transitive !== undefined) traverse.transitive = t.transitive;
1014
+ if (t.direction !== undefined) traverse.direction = t.direction;
1015
+ if (t.limitPerAnchor !== undefined) traverse.limitPerAnchor = t.limitPerAnchor;
1016
+ if (t.levels !== undefined) traverse.levels = t.levels;
1017
+ queryInput.parent = traverse;
1018
+ } else {
1019
+ queryInput.parent = { id: query.parent.id, predicate: parentPredicate };
1020
+ }
994
1021
  }
995
1022
  if (query.properties) queryInput.properties = query.properties;
996
1023
  if (query.include) {
@@ -1043,7 +1070,10 @@ export class Ad4mModel {
1043
1070
  if (query.offset !== undefined) queryInput.offset = query.offset;
1044
1071
  if (query.limit !== undefined) queryInput.limit = query.limit;
1045
1072
  if (query.count !== undefined) queryInput.count = query.count;
1073
+ if (query.links) queryInput.links = query.links;
1046
1074
  queryInput.deepQuery = query.deepQuery ?? true;
1075
+ if (query.linkStatus != null) queryInput.linkStatus = query.linkStatus;
1076
+ if (query.includeUnverified !== undefined) queryInput.includeUnverified = query.includeUnverified;
1047
1077
 
1048
1078
  // Conformance getters, where filters, and target shapes for includes
1049
1079
  // are all resolved by the executor from the perspective's SHACL triples
@@ -1880,9 +1910,10 @@ export class Ad4mModel {
1880
1910
  if (options?.parent && !options?.batchId) {
1881
1911
  const batchId = await perspective.createBatch();
1882
1912
  await instance.save(batchId);
1883
- const predicate = resolveParentPredicate(options.parent, this);
1913
+ const parent = requireSingleParent(options.parent);
1914
+ const predicate = resolveParentPredicate(parent, this);
1884
1915
  const link = new Link({
1885
- source: options.parent.id,
1916
+ source: parent.id,
1886
1917
  predicate,
1887
1918
  target: instance.id,
1888
1919
  });
@@ -1898,9 +1929,10 @@ export class Ad4mModel {
1898
1929
 
1899
1930
  // Create parent → child link if a parent scope was provided
1900
1931
  if (options?.parent) {
1901
- const predicate = resolveParentPredicate(options.parent, this);
1932
+ const parent = requireSingleParent(options.parent);
1933
+ const predicate = resolveParentPredicate(parent, this);
1902
1934
  const link = new Link({
1903
- source: options.parent.id,
1935
+ source: parent.id,
1904
1936
  predicate,
1905
1937
  target: instance.id,
1906
1938
  });