@coasys/ad4m 0.13.0-test-interpretation-2 → 0.13.0-test-model-layer

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 (254) hide show
  1. package/lib/index.cjs +1982 -498
  2. package/lib/index.js +1982 -499
  3. package/lib/src/ai/AIClient.js +6 -3
  4. package/lib/src/apiClient.d.ts +40 -4
  5. package/lib/src/apiClient.js +149 -9
  6. package/lib/src/index.d.ts +3 -1
  7. package/lib/src/index.js +2 -0
  8. package/lib/src/model/Ad4mModel.d.ts +6 -5
  9. package/lib/src/model/Ad4mModel.js +246 -29
  10. package/lib/src/model/Ad4mModel.test.js +480 -735
  11. package/lib/src/model/decorators.d.ts +147 -4
  12. package/lib/src/model/decorators.js +70 -24
  13. package/lib/src/model/model-manifest.d.ts +41 -0
  14. package/lib/src/model/model-manifest.js +11 -0
  15. package/lib/src/model/query-sparql.test.js +92 -10
  16. package/lib/src/model/shacl-gen.js +33 -0
  17. package/lib/src/model/types.d.ts +9 -0
  18. package/lib/src/neighbourhood/NeighbourhoodProxy.test.js +33 -33
  19. package/lib/src/perspectives/AutoProcessor.d.ts +90 -24
  20. package/lib/src/perspectives/FlowInstance.d.ts +187 -0
  21. package/lib/src/perspectives/FlowInstance.js +336 -0
  22. package/lib/src/perspectives/FlowModels.d.ts +94 -0
  23. package/lib/src/perspectives/FlowModels.js +182 -0
  24. package/lib/src/perspectives/InterpretationModels.d.ts +12 -22
  25. package/lib/src/perspectives/InterpretationModels.js +2 -6
  26. package/lib/src/perspectives/PerspectiveClient.d.ts +68 -7
  27. package/lib/src/perspectives/PerspectiveClient.js +105 -10
  28. package/lib/src/perspectives/PerspectiveProxy.d.ts +142 -57
  29. package/lib/src/perspectives/PerspectiveProxy.js +388 -274
  30. package/lib/src/shacl/SHACLFlow.d.ts +273 -47
  31. package/lib/src/shacl/SHACLFlow.js +397 -88
  32. package/lib/src/shacl/SHACLShape.d.ts +8 -0
  33. package/lib/src/shacl/SHACLShape.js +17 -0
  34. package/lib/src/shacl/SHACLShape.test.js +82 -0
  35. package/package.json +2 -2
  36. package/src/ai/AIClient.ts +6 -3
  37. package/src/apiClient.test.ts +227 -0
  38. package/src/apiClient.ts +185 -9
  39. package/src/index.ts +3 -1
  40. package/src/model/Ad4mModel.test.ts +645 -0
  41. package/src/model/Ad4mModel.ts +245 -26
  42. package/src/model/decorators.ts +216 -35
  43. package/src/model/relation-filtering.test.ts +70 -20
  44. package/src/model/shacl-gen.ts +36 -0
  45. package/src/model/shacl-roundtrip.test.ts +130 -0
  46. package/src/model/types.ts +7 -0
  47. package/src/perspectives/AutoProcessor.ts +94 -24
  48. package/src/perspectives/FlowInstance.ts +369 -0
  49. package/src/perspectives/FlowModels.ts +157 -0
  50. package/src/perspectives/InterpretationModels.ts +13 -25
  51. package/src/perspectives/PerspectiveClient.test.ts +67 -6
  52. package/src/perspectives/PerspectiveClient.ts +142 -12
  53. package/src/perspectives/PerspectiveProxy.test.ts +406 -0
  54. package/src/perspectives/PerspectiveProxy.ts +459 -289
  55. package/src/perspectives/shacl-rpc.test.ts +258 -0
  56. package/src/shacl/SHACLFlow.test.ts +762 -35
  57. package/src/shacl/SHACLFlow.ts +680 -112
  58. package/src/shacl/SHACLShape.ts +31 -0
  59. package/lib/src/generated/rest/AIModelLoadingStatus.d.ts +0 -7
  60. package/lib/src/generated/rest/AIModelLoadingStatus.js +0 -2
  61. package/lib/src/generated/rest/AddAgentInfosRequest.d.ts +0 -3
  62. package/lib/src/generated/rest/AddAgentInfosRequest.js +0 -2
  63. package/lib/src/generated/rest/AddLinkExpressionRequest.d.ts +0 -6
  64. package/lib/src/generated/rest/AddLinkExpressionRequest.js +0 -1
  65. package/lib/src/generated/rest/AddLinkRequest.d.ts +0 -6
  66. package/lib/src/generated/rest/AddLinkRequest.js +0 -1
  67. package/lib/src/generated/rest/AddLinksBulkRequest.d.ts +0 -6
  68. package/lib/src/generated/rest/AddLinksBulkRequest.js +0 -1
  69. package/lib/src/generated/rest/AddSdnaRequest.d.ts +0 -6
  70. package/lib/src/generated/rest/AddSdnaRequest.js +0 -2
  71. package/lib/src/generated/rest/ApplyTemplateRequest.d.ts +0 -4
  72. package/lib/src/generated/rest/ApplyTemplateRequest.js +0 -2
  73. package/lib/src/generated/rest/AuthInfoInput.d.ts +0 -10
  74. package/lib/src/generated/rest/AuthInfoInput.js +0 -1
  75. package/lib/src/generated/rest/BroadcastRequest.d.ts +0 -6
  76. package/lib/src/generated/rest/BroadcastRequest.js +0 -1
  77. package/lib/src/generated/rest/CapabilityInput.d.ts +0 -5
  78. package/lib/src/generated/rest/CapabilityInput.js +0 -1
  79. package/lib/src/generated/rest/CommitBatchRequest.d.ts +0 -3
  80. package/lib/src/generated/rest/CommitBatchRequest.js +0 -2
  81. package/lib/src/generated/rest/ComputeLogEntry.d.ts +0 -9
  82. package/lib/src/generated/rest/ComputeLogEntry.js +0 -2
  83. package/lib/src/generated/rest/CreateExpressionRequest.d.ts +0 -4
  84. package/lib/src/generated/rest/CreateExpressionRequest.js +0 -2
  85. package/lib/src/generated/rest/CreatePerspectiveRequest.d.ts +0 -3
  86. package/lib/src/generated/rest/CreatePerspectiveRequest.js +0 -2
  87. package/lib/src/generated/rest/CreateSubjectRequest.d.ts +0 -6
  88. package/lib/src/generated/rest/CreateSubjectRequest.js +0 -2
  89. package/lib/src/generated/rest/CreateUserRequest.d.ts +0 -4
  90. package/lib/src/generated/rest/CreateUserRequest.js +0 -2
  91. package/lib/src/generated/rest/CreateUserResponse.d.ts +0 -5
  92. package/lib/src/generated/rest/CreateUserResponse.js +0 -2
  93. package/lib/src/generated/rest/DecoratedExpressionProof.d.ts +0 -6
  94. package/lib/src/generated/rest/DecoratedExpressionProof.js +0 -2
  95. package/lib/src/generated/rest/DecoratedLinkExpression.d.ts +0 -10
  96. package/lib/src/generated/rest/DecoratedLinkExpression.js +0 -1
  97. package/lib/src/generated/rest/DisposeQueryRequest.d.ts +0 -3
  98. package/lib/src/generated/rest/DisposeQueryRequest.js +0 -2
  99. package/lib/src/generated/rest/EmailTestRequest.d.ts +0 -6
  100. package/lib/src/generated/rest/EmailTestRequest.js +0 -2
  101. package/lib/src/generated/rest/EmbedRequest.d.ts +0 -4
  102. package/lib/src/generated/rest/EmbedRequest.js +0 -2
  103. package/lib/src/generated/rest/EntanglementProofInput.d.ts +0 -6
  104. package/lib/src/generated/rest/EntanglementProofInput.js +0 -2
  105. package/lib/src/generated/rest/EntanglementProofPreflightRequest.d.ts +0 -4
  106. package/lib/src/generated/rest/EntanglementProofPreflightRequest.js +0 -2
  107. package/lib/src/generated/rest/ExecuteCommandsRequest.d.ts +0 -4
  108. package/lib/src/generated/rest/ExecuteCommandsRequest.js +0 -2
  109. package/lib/src/generated/rest/ExportRequest.d.ts +0 -5
  110. package/lib/src/generated/rest/ExportRequest.js +0 -2
  111. package/lib/src/generated/rest/ExpressionManyRequest.d.ts +0 -3
  112. package/lib/src/generated/rest/ExpressionManyRequest.js +0 -2
  113. package/lib/src/generated/rest/ExpressionProof.d.ts +0 -4
  114. package/lib/src/generated/rest/ExpressionProof.js +0 -2
  115. package/lib/src/generated/rest/ExpressionProofInput.d.ts +0 -6
  116. package/lib/src/generated/rest/ExpressionProofInput.js +0 -2
  117. package/lib/src/generated/rest/FriendSendMessageRequest.d.ts +0 -3
  118. package/lib/src/generated/rest/FriendSendMessageRequest.js +0 -2
  119. package/lib/src/generated/rest/FriendsListRequest.d.ts +0 -3
  120. package/lib/src/generated/rest/FriendsListRequest.js +0 -2
  121. package/lib/src/generated/rest/GenerateAgentRequest.d.ts +0 -3
  122. package/lib/src/generated/rest/GenerateAgentRequest.js +0 -2
  123. package/lib/src/generated/rest/GenerateJwtRequest.d.ts +0 -4
  124. package/lib/src/generated/rest/GenerateJwtRequest.js +0 -2
  125. package/lib/src/generated/rest/GetSubjectDataRequest.d.ts +0 -4
  126. package/lib/src/generated/rest/GetSubjectDataRequest.js +0 -2
  127. package/lib/src/generated/rest/HostingInfoResponse.d.ts +0 -5
  128. package/lib/src/generated/rest/HostingInfoResponse.js +0 -2
  129. package/lib/src/generated/rest/HostingWalletResponse.d.ts +0 -4
  130. package/lib/src/generated/rest/HostingWalletResponse.js +0 -2
  131. package/lib/src/generated/rest/ImportAgentRequest.d.ts +0 -6
  132. package/lib/src/generated/rest/ImportAgentRequest.js +0 -2
  133. package/lib/src/generated/rest/ImportRequest.d.ts +0 -4
  134. package/lib/src/generated/rest/ImportRequest.js +0 -2
  135. package/lib/src/generated/rest/JoinNeighbourhoodRequest.d.ts +0 -3
  136. package/lib/src/generated/rest/JoinNeighbourhoodRequest.js +0 -2
  137. package/lib/src/generated/rest/KeepAliveQueryRequest.d.ts +0 -3
  138. package/lib/src/generated/rest/KeepAliveQueryRequest.js +0 -2
  139. package/lib/src/generated/rest/LanguageMetaInput.d.ts +0 -6
  140. package/lib/src/generated/rest/LanguageMetaInput.js +0 -2
  141. package/lib/src/generated/rest/Link.d.ts +0 -5
  142. package/lib/src/generated/rest/Link.js +0 -2
  143. package/lib/src/generated/rest/LinkExpression.d.ts +0 -10
  144. package/lib/src/generated/rest/LinkExpression.js +0 -1
  145. package/lib/src/generated/rest/LinkExpressionInput.d.ts +0 -10
  146. package/lib/src/generated/rest/LinkExpressionInput.js +0 -1
  147. package/lib/src/generated/rest/LinkInput.d.ts +0 -5
  148. package/lib/src/generated/rest/LinkInput.js +0 -2
  149. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.d.ts +0 -3
  150. package/lib/src/generated/rest/LinkLanguageTemplatesRequest.js +0 -2
  151. package/lib/src/generated/rest/LinkMutationRequest.d.ts +0 -12
  152. package/lib/src/generated/rest/LinkMutationRequest.js +0 -1
  153. package/lib/src/generated/rest/LinkMutationResponse.d.ts +0 -9
  154. package/lib/src/generated/rest/LinkMutationResponse.js +0 -1
  155. package/lib/src/generated/rest/LinkMutations.d.ts +0 -6
  156. package/lib/src/generated/rest/LinkMutations.js +0 -1
  157. package/lib/src/generated/rest/LinkMutationsRequest.d.ts +0 -5
  158. package/lib/src/generated/rest/LinkMutationsRequest.js +0 -1
  159. package/lib/src/generated/rest/LinkStatus.d.ts +0 -1
  160. package/lib/src/generated/rest/LinkStatus.js +0 -2
  161. package/lib/src/generated/rest/LinkUpdateInput.d.ts +0 -5
  162. package/lib/src/generated/rest/LinkUpdateInput.js +0 -1
  163. package/lib/src/generated/rest/LockAgentRequest.d.ts +0 -3
  164. package/lib/src/generated/rest/LockAgentRequest.js +0 -2
  165. package/lib/src/generated/rest/LoginUserRequest.d.ts +0 -5
  166. package/lib/src/generated/rest/LoginUserRequest.js +0 -2
  167. package/lib/src/generated/rest/ModelType.d.ts +0 -1
  168. package/lib/src/generated/rest/ModelType.js +0 -2
  169. package/lib/src/generated/rest/NotificationGrantRequest.d.ts +0 -3
  170. package/lib/src/generated/rest/NotificationGrantRequest.js +0 -2
  171. package/lib/src/generated/rest/NotificationInput.d.ts +0 -10
  172. package/lib/src/generated/rest/NotificationInput.js +0 -2
  173. package/lib/src/generated/rest/OpenLinkRequest.d.ts +0 -3
  174. package/lib/src/generated/rest/OpenLinkRequest.js +0 -2
  175. package/lib/src/generated/rest/PermitCapabilityRequest.d.ts +0 -3
  176. package/lib/src/generated/rest/PermitCapabilityRequest.js +0 -2
  177. package/lib/src/generated/rest/PerspectiveInput.d.ts +0 -4
  178. package/lib/src/generated/rest/PerspectiveInput.js +0 -1
  179. package/lib/src/generated/rest/PromptRequest.d.ts +0 -4
  180. package/lib/src/generated/rest/PromptRequest.js +0 -2
  181. package/lib/src/generated/rest/PublicPerspectiveInput.d.ts +0 -4
  182. package/lib/src/generated/rest/PublicPerspectiveInput.js +0 -1
  183. package/lib/src/generated/rest/PublishLanguageRequest.d.ts +0 -5
  184. package/lib/src/generated/rest/PublishLanguageRequest.js +0 -1
  185. package/lib/src/generated/rest/PublishNeighbourhoodRequest.d.ts +0 -6
  186. package/lib/src/generated/rest/PublishNeighbourhoodRequest.js +0 -1
  187. package/lib/src/generated/rest/QueryRequest.d.ts +0 -7
  188. package/lib/src/generated/rest/QueryRequest.js +0 -2
  189. package/lib/src/generated/rest/RemoveLinkRequest.d.ts +0 -5
  190. package/lib/src/generated/rest/RemoveLinkRequest.js +0 -1
  191. package/lib/src/generated/rest/RemoveLinksBulkRequest.d.ts +0 -5
  192. package/lib/src/generated/rest/RemoveLinksBulkRequest.js +0 -1
  193. package/lib/src/generated/rest/RequestCapabilityRequest.d.ts +0 -4
  194. package/lib/src/generated/rest/RequestCapabilityRequest.js +0 -1
  195. package/lib/src/generated/rest/RequestPaymentRequest.d.ts +0 -3
  196. package/lib/src/generated/rest/RequestPaymentRequest.js +0 -2
  197. package/lib/src/generated/rest/RequestVerificationRequest.d.ts +0 -4
  198. package/lib/src/generated/rest/RequestVerificationRequest.js +0 -2
  199. package/lib/src/generated/rest/ResourceInput.d.ts +0 -4
  200. package/lib/src/generated/rest/ResourceInput.js +0 -2
  201. package/lib/src/generated/rest/SetDefaultModelRequest.d.ts +0 -4
  202. package/lib/src/generated/rest/SetDefaultModelRequest.js +0 -1
  203. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.d.ts +0 -3
  204. package/lib/src/generated/rest/SetFreeHostingEnabledRequest.js +0 -2
  205. package/lib/src/generated/rest/SetHotWalletAddressRequest.d.ts +0 -3
  206. package/lib/src/generated/rest/SetHotWalletAddressRequest.js +0 -2
  207. package/lib/src/generated/rest/SetMultiUserRequest.d.ts +0 -3
  208. package/lib/src/generated/rest/SetMultiUserRequest.js +0 -2
  209. package/lib/src/generated/rest/SetOnlineStatusRequest.d.ts +0 -5
  210. package/lib/src/generated/rest/SetOnlineStatusRequest.js +0 -1
  211. package/lib/src/generated/rest/SetStatusRequest.d.ts +0 -3
  212. package/lib/src/generated/rest/SetStatusRequest.js +0 -2
  213. package/lib/src/generated/rest/SetUserFreeAccessRequest.d.ts +0 -4
  214. package/lib/src/generated/rest/SetUserFreeAccessRequest.js +0 -2
  215. package/lib/src/generated/rest/SignMessageRequest.d.ts +0 -3
  216. package/lib/src/generated/rest/SignMessageRequest.js +0 -2
  217. package/lib/src/generated/rest/SignalRequest.d.ts +0 -6
  218. package/lib/src/generated/rest/SignalRequest.js +0 -1
  219. package/lib/src/generated/rest/SubscribeQueryRequest.d.ts +0 -3
  220. package/lib/src/generated/rest/SubscribeQueryRequest.js +0 -2
  221. package/lib/src/generated/rest/SubscribeQueryResponse.d.ts +0 -4
  222. package/lib/src/generated/rest/SubscribeQueryResponse.js +0 -2
  223. package/lib/src/generated/rest/TrustedAgentsRequest.d.ts +0 -3
  224. package/lib/src/generated/rest/TrustedAgentsRequest.js +0 -2
  225. package/lib/src/generated/rest/UnlockAgentRequest.d.ts +0 -4
  226. package/lib/src/generated/rest/UnlockAgentRequest.js +0 -2
  227. package/lib/src/generated/rest/UpdateLinkRequest.d.ts +0 -7
  228. package/lib/src/generated/rest/UpdateLinkRequest.js +0 -1
  229. package/lib/src/generated/rest/UpdatePerspectiveRequest.d.ts +0 -3
  230. package/lib/src/generated/rest/UpdatePerspectiveRequest.js +0 -2
  231. package/lib/src/generated/rest/UpdateProfileRequest.d.ts +0 -5
  232. package/lib/src/generated/rest/UpdateProfileRequest.js +0 -1
  233. package/lib/src/generated/rest/UserStatistics.d.ts +0 -9
  234. package/lib/src/generated/rest/UserStatistics.js +0 -2
  235. package/lib/src/generated/rest/VerificationRequestResult.d.ts +0 -6
  236. package/lib/src/generated/rest/VerificationRequestResult.js +0 -2
  237. package/lib/src/generated/rest/VerifyEmailRequest.d.ts +0 -6
  238. package/lib/src/generated/rest/VerifyEmailRequest.js +0 -2
  239. package/lib/src/generated/rest/VerifySignatureRequest.d.ts +0 -5
  240. package/lib/src/generated/rest/VerifySignatureRequest.js +0 -2
  241. package/lib/src/generated/rest/WriteSettingsRequest.d.ts +0 -3
  242. package/lib/src/generated/rest/WriteSettingsRequest.js +0 -2
  243. package/lib/src/generated/rest/index.d.ts +0 -73
  244. package/lib/src/generated/rest/index.js +0 -8
  245. package/lib/src/generated/rest/routes.d.ts +0 -587
  246. package/lib/src/generated/rest/routes.js +0 -3
  247. package/lib/src/model/query-surreal.d.ts +0 -44
  248. package/lib/src/model/query-surreal.js +0 -249
  249. package/lib/src/model/surreal-utils.d.ts +0 -42
  250. package/lib/src/model/surreal-utils.js +0 -128
  251. package/lib/src/perspectives/PerspectiveProxy.test.d.ts +0 -1
  252. package/lib/src/perspectives/PerspectiveProxy.test.js +0 -34
  253. package/lib/src/restClient.d.ts +0 -52
  254. package/lib/src/restClient.js +0 -227
@@ -2,6 +2,7 @@ import { Literal } from "../Literal";
2
2
  import { Link } from "../links/Links";
3
3
  import { LinkQuery } from "../perspectives/LinkQuery";
4
4
  import { PerspectiveProxy } from "../perspectives/PerspectiveProxy";
5
+ import { CallOptions } from "../apiClient";
5
6
  import { makeRandomId } from "./util";
6
7
  import { getPropertiesMetadata, getRelationsMetadata, setPropertyRegistryEntry, setRelationRegistryEntry, Model } from "./decorators";
7
8
  import type { PropertyOptions, PropertyMetadataEntry, RelationMetadataEntry } from "./decorators";
@@ -35,6 +36,109 @@ import type {
35
36
  * Rust endpoint. Recursively converts included relation values (which come
36
37
  * back as plain JSON objects) into proper model class instances.
37
38
  */
39
+ /**
40
+ * Key under which the executor returns a polymorphically-hydrated instance's
41
+ * concrete class.
42
+ *
43
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
44
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
45
+ * separate literals in separate languages. Renaming one alone does not fail to
46
+ * compile — it degrades to every instance staying plain JSON, which looks
47
+ * identical to a relation that declared no classes to build.
48
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
49
+ * executor, so the drift fails a test rather than a user's query.
50
+ *
51
+ * The executor also returns `__subjectClasses`, the whole set this one names the
52
+ * head of. Nothing here reads it — it rides onto the instance with every other
53
+ * JSON key, for a caller that wants to know a choice was made.
54
+ */
55
+ const SUBJECT_CLASS_KEY = '__subjectClass';
56
+
57
+ /**
58
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
59
+ * an include map.
60
+ *
61
+ * A relation being heterogeneous is a fact about the data, not about one query,
62
+ * so the declaration lives on the model and the call site writes
63
+ * `include: { children: true }`. That has to hold just as much one level down:
64
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
65
+ * relation on `Post`, so the walk carries the class it is reading against down
66
+ * with it. Without that, a nested include of an untyped polymorphic relation
67
+ * reaches the executor with no shape to resolve and fails the query outright.
68
+ *
69
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
70
+ * only state the default fills in.
71
+ *
72
+ * The walk stops descending *through* a polymorphic relation, because there is
73
+ * nothing to descend into: its targets are of several classes by definition, so
74
+ * no single class's metadata could say what a deeper include means. The
75
+ * executor resolves those nested includes against each concrete class instead.
76
+ */
77
+ function applyPolymorphicIncludeDefaults(includes: IncludeMap, ctor: Function): void {
78
+ const relMeta = getRelationsMetadata(ctor);
79
+ for (const [relName, val] of Object.entries(includes)) {
80
+ // `$`-prefixed keys are projections, not relations.
81
+ if (relName.startsWith('$')) continue;
82
+ const meta = relMeta[relName];
83
+ if (!meta) continue;
84
+
85
+ let subQuery = val as any;
86
+ if (meta.polymorphic) {
87
+ if (val === true) {
88
+ subQuery = { polymorphic: true };
89
+ includes[relName] = subQuery;
90
+ } else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
91
+ subQuery.polymorphic = true;
92
+ }
93
+ // The classes this call site can build are also the classes it wants its
94
+ // targets read as, so the declaration answers both questions and the call
95
+ // site repeats neither. Sent as part of the query rather than applied to
96
+ // the results: a preference in the request is reproducible by anyone who
97
+ // sends it, where one applied afterwards would make the same data read
98
+ // differently depending on which classes the caller happened to import.
99
+ //
100
+ // It ranks and does not narrow — a target matching none of them still
101
+ // arrives — so declaring what you can construct never costs you a member
102
+ // of a relation that is heterogeneous by definition.
103
+ if (
104
+ typeof subQuery === 'object' &&
105
+ subQuery !== null &&
106
+ subQuery.polymorphic &&
107
+ subQuery.preferClasses === undefined &&
108
+ meta.instantiateAs
109
+ ) {
110
+ const names = (meta.instantiateAs() ?? [])
111
+ .map((cls) => (cls as any)?.className)
112
+ .filter((name): name is string => typeof name === 'string');
113
+ if (names.length) subQuery.preferClasses = names;
114
+ }
115
+ }
116
+
117
+ if (typeof subQuery !== 'object' || subQuery === null) continue;
118
+ const nested = subQuery.include as IncludeMap | undefined;
119
+ if (!nested || subQuery.polymorphic) continue;
120
+
121
+ // The thunk is only evaluated here, at query time, so a self-referential or
122
+ // circularly-imported target that is not yet defined costs the nested
123
+ // default rather than the whole query.
124
+ let TargetClass: any;
125
+ try {
126
+ TargetClass = meta.target?.();
127
+ } catch (e) {
128
+ // A class not yet initialised throws `ReferenceError` from the temporal
129
+ // dead zone, which is the expected cost of an import cycle and not worth
130
+ // saying anything about. Anything else — a thunk closing over nothing,
131
+ // typically — is a broken declaration that would otherwise cost the nested
132
+ // default in silence, so it gets said out loud.
133
+ const circularImport = e instanceof ReferenceError;
134
+ const say = circularImport ? console.debug : console.warn;
135
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
136
+ continue;
137
+ }
138
+ if (TargetClass) applyPolymorphicIncludeDefaults(nested, TargetClass);
139
+ }
140
+ }
141
+
38
142
  function jsonToModelInstance<T extends Ad4mModel>(
39
143
  ModelClass: typeof Ad4mModel & (new (...args: any[]) => T),
40
144
  perspective: PerspectiveProxy,
@@ -87,8 +191,56 @@ function jsonToModelInstance<T extends Ad4mModel>(
87
191
  for (const [relName, includeVal] of Object.entries(include)) {
88
192
  if (!includeVal) continue;
89
193
  const meta = relMeta[relName];
90
- if (!meta?.target) continue;
91
- const TargetClass = meta.target() as any;
194
+ // A polymorphic relation may legitimately declare no target at all —
195
+ // that is the case it exists for — so it must not be gated on one.
196
+ if (!meta) continue;
197
+ if (!meta.target && !meta.polymorphic) continue;
198
+ const TargetClass = meta.target?.() as any;
199
+ // For a polymorphic relation the executor sends each child's concrete
200
+ // class back on the instance, because it had to know it in order to
201
+ // hydrate against the right shape at all. What it cannot send is the
202
+ // constructor, so `instantiateAs` names the classes this side can build
203
+ // and the name → class map is derived from them: `@Model` records each
204
+ // class's name on the class itself, so listing the classes and listing
205
+ // their names would be the same list written twice, free to disagree.
206
+ //
207
+ // Built on first use rather than at decoration time, because the thunk
208
+ // exists to be called late: a class defined further round a circular
209
+ // import graph is not there yet when the decorator runs.
210
+ let byClassName: Record<string, any> | undefined;
211
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
212
+ // target at all, and the list may not name the class that arrived — it
213
+ // says what this call site can construct, not what the relation may hold.
214
+ // The item then stays plain JSON — correct data, carrying its class name
215
+ // for a caller that wants to dispatch on it — rather than being forced
216
+ // through a constructor that does not exist.
217
+ const resolveChildClass = (item: any): any => {
218
+ if (!meta.polymorphic) return TargetClass;
219
+ const concrete = item?.[SUBJECT_CLASS_KEY];
220
+ // No concrete class means this was not read polymorphically after all —
221
+ // an explicit `polymorphic: false` at the call site — so the relation's
222
+ // own declared target is the right shape.
223
+ if (typeof concrete !== 'string') return TargetClass;
224
+ if (meta.instantiateAs) {
225
+ if (!byClassName) {
226
+ byClassName = {};
227
+ for (const cls of meta.instantiateAs() ?? []) {
228
+ const name = (cls as any)?.className;
229
+ if (typeof name === 'string') byClassName[name] = cls;
230
+ }
231
+ }
232
+ if (byClassName[concrete]) return byClassName[concrete];
233
+ }
234
+ // The declared target is not a fallback, and having named no classes to
235
+ // build does not make it one. Where a relation both declares a target
236
+ // and reads polymorphically, a child of some third class was hydrated
237
+ // against *its own* shape, so constructing the declared class over that
238
+ // JSON produces an instance that answers `instanceof` for a class it is
239
+ // not, carrying fields that class never declared — the exact
240
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
241
+ // is the class the executor named.
242
+ return (TargetClass as any)?.className === concrete ? TargetClass : undefined;
243
+ };
92
244
  const nestedInclude =
93
245
  typeof includeVal === 'object' && includeVal !== null
94
246
  ? (includeVal as any).include
@@ -101,15 +253,19 @@ function jsonToModelInstance<T extends Ad4mModel>(
101
253
  const raw = instance[relName];
102
254
  if (Array.isArray(raw)) {
103
255
  instance[relName] = raw.map((item: any) => {
104
- if (typeof item === 'object' && item !== null && item.id) {
105
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
256
+ const ChildClass = resolveChildClass(item);
257
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
258
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
106
259
  }
107
260
  return item;
108
261
  });
109
262
  } else if (typeof raw === 'object' && raw !== null && raw.id) {
110
- instance[relName] = jsonToModelInstance(
111
- TargetClass, perspective, raw, nestedInclude, nestedProperties,
112
- );
263
+ const ChildClass = resolveChildClass(raw);
264
+ if (ChildClass) {
265
+ instance[relName] = jsonToModelInstance(
266
+ ChildClass, perspective, raw, nestedInclude, nestedProperties,
267
+ );
268
+ }
113
269
  }
114
270
  }
115
271
  }
@@ -382,6 +538,7 @@ export class Ad4mModel {
382
538
  ...(options.target !== undefined && { target: options.target }),
383
539
  ...(options.filter !== undefined && { filter: options.filter }),
384
540
  ...(options.where !== undefined && { where: options.where }),
541
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
385
542
  };
386
543
  }
387
544
 
@@ -691,10 +848,22 @@ export class Ad4mModel {
691
848
  const original = this._snapshot[field];
692
849
 
693
850
  if (Array.isArray(current) || Array.isArray(original)) {
694
- // Order-insensitive comparison (sorted) so reordering alone
695
- // doesn't mark a relation as dirty.
696
- const a = Array.isArray(current) ? [...current].sort() : [];
697
- const b = Array.isArray(original) ? [...original].sort() : [];
851
+ // For an ordered relation the sequence *is* the state, so a reorder is
852
+ // the whole change and must mark the field dirty — sorting first would
853
+ // make `save()` a no-op for the one edit the ordering feature exists to
854
+ // support.
855
+ //
856
+ // Everything else compares order-insensitively, because an unordered
857
+ // relation is a set: the executor returns its members by link timestamp,
858
+ // and a caller who assigned the same members in another order has not
859
+ // changed anything.
860
+ const ordered = !!(metadata.relations as any)[field]?.ordering;
861
+ const a = Array.isArray(current) ? [...current] : [];
862
+ const b = Array.isArray(original) ? [...original] : [];
863
+ if (!ordered) {
864
+ a.sort();
865
+ b.sort();
866
+ }
698
867
  if (a.length !== b.length || a.some((v: any, i: number) => v !== b[i])) {
699
868
  changed.push(field);
700
869
  }
@@ -836,7 +1005,17 @@ export class Ad4mModel {
836
1005
  normalIncludes[key] = val;
837
1006
  }
838
1007
  }
839
- if (Object.keys(normalIncludes).length > 0) queryInput.include = normalIncludes;
1008
+ // A relation declared `polymorphic` reads that way by default, so the
1009
+ // caller writes `include: { children: true }` and still gets each child
1010
+ // hydrated as the class it actually is. Declaring it on the model rather
1011
+ // than repeating it at every call site is the point — the relation being
1012
+ // heterogeneous is a fact about the data, not about one query — but an
1013
+ // explicit `polymorphic: false` at the call site still wins. Applied at
1014
+ // every depth, since a nested include is a fact about the data too.
1015
+ if (Object.keys(normalIncludes).length > 0) {
1016
+ applyPolymorphicIncludeDefaults(normalIncludes, this as any);
1017
+ queryInput.include = normalIncludes;
1018
+ }
840
1019
  if (Object.keys(projections).length > 0) {
841
1020
  // Tag each projection with its target class name so the executor can
842
1021
  // resolve the target shape through its in-memory cache when applying
@@ -911,6 +1090,7 @@ export class Ad4mModel {
911
1090
  perspective: PerspectiveProxy,
912
1091
  query: Query = {},
913
1092
  classNameOverride?: string | null,
1093
+ options?: CallOptions,
914
1094
  ): Promise<ResultsWithTotalCount<T>> {
915
1095
  // Delegate query input building to the shared prepareModelQueryParams
916
1096
  // helper. The executor resolves the shape from SHACL server-side.
@@ -918,7 +1098,7 @@ export class Ad4mModel {
918
1098
  query, classNameOverride,
919
1099
  );
920
1100
 
921
- const result = await perspective.modelQuery(className, queryJson);
1101
+ const result = await perspective.modelQuery(className, queryJson, options);
922
1102
 
923
1103
  // Convert JSON instances to model class instances, recursively constructing
924
1104
  // class instances for any included relations resolved by Rust.
@@ -969,13 +1149,14 @@ export class Ad4mModel {
969
1149
  this: typeof Ad4mModel & (new (...args: any[]) => T),
970
1150
  perspective: PerspectiveProxy,
971
1151
  query?: Q,
1152
+ options?: CallOptions,
972
1153
  ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>)[]> {
973
1154
  const q = (query ?? {}) as Query;
974
1155
  if (q.properties && q.properties.length === 0) {
975
1156
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
976
1157
  }
977
1158
 
978
- const { results } = await this.executeModelQuery(perspective, q);
1159
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
979
1160
  return results as (T & IncludeExtras<T, IncludeOf<Q>>)[];
980
1161
  }
981
1162
 
@@ -1003,9 +1184,10 @@ export class Ad4mModel {
1003
1184
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1004
1185
  perspective: PerspectiveProxy,
1005
1186
  query?: Q,
1187
+ options?: CallOptions,
1006
1188
  ): Promise<(T & IncludeExtras<T, IncludeOf<Q>>) | null> {
1007
1189
  const limitedQuery = { ...((query ?? {}) as Query), limit: 1 } as Q;
1008
- const results = await this.findAll<T, Q>(perspective, limitedQuery);
1190
+ const results = await this.findAll<T, Q>(perspective, limitedQuery, options);
1009
1191
  return results[0] ?? null;
1010
1192
  }
1011
1193
 
@@ -1030,8 +1212,9 @@ export class Ad4mModel {
1030
1212
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1031
1213
  perspective: PerspectiveProxy,
1032
1214
  query?: Q,
1215
+ options?: CallOptions,
1033
1216
  ): Promise<ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>> {
1034
- const out = await this.executeModelQuery(perspective, (query ?? {}) as Query);
1217
+ const out = await this.executeModelQuery(perspective, (query ?? {}) as Query, undefined, options);
1035
1218
  return out as ResultsWithTotalCount<T & IncludeExtras<T, IncludeOf<Q>>>;
1036
1219
  }
1037
1220
 
@@ -1058,9 +1241,10 @@ export class Ad4mModel {
1058
1241
  pageSize: number,
1059
1242
  pageNumber: number,
1060
1243
  query?: Q,
1244
+ options?: CallOptions,
1061
1245
  ): Promise<PaginationResult<T & IncludeExtras<T, IncludeOf<Q>>>> {
1062
1246
  const paginationQuery = { ...((query ?? {}) as Query), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
1063
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1247
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
1064
1248
  return { results: results as (T & IncludeExtras<T, IncludeOf<Q>>)[], totalCount, pageSize, pageNumber };
1065
1249
  }
1066
1250
 
@@ -1094,8 +1278,9 @@ export class Ad4mModel {
1094
1278
  this: typeof Ad4mModel & (new (...args: any[]) => T),
1095
1279
  perspective: PerspectiveProxy,
1096
1280
  query?: TypedQuery<T>,
1281
+ options?: CallOptions,
1097
1282
  ): Promise<number> {
1098
- const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 });
1283
+ const { totalCount } = await this.executeModelQuery(perspective, { ...((query ?? {}) as Query), limit: 0 }, undefined, options);
1099
1284
  return totalCount;
1100
1285
  }
1101
1286
 
@@ -1277,7 +1462,18 @@ export class Ad4mModel {
1277
1462
  for (const [key, value] of Object.entries(this)) {
1278
1463
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
1279
1464
  const propMeta = metadata.properties[key];
1280
- if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1465
+ // Only offer keys with a declared, settable model property. This
1466
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
1467
+ // enumerable instance fields, not model properties), HasMany
1468
+ // relations (tracked in a separate registry, never in
1469
+ // `metadata.properties`), and read-only properties/flags
1470
+ // (readOnly: true). None of these have an `ad4m://setter` on the
1471
+ // Rust side, which otherwise logs a "declares no setter" warning
1472
+ // per key on every save().
1473
+ if (!propMeta || propMeta.readOnly) {
1474
+ continue;
1475
+ }
1476
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1281
1477
  deferredExpressionProps.push(key);
1282
1478
  continue;
1283
1479
  }
@@ -1401,14 +1597,37 @@ export class Ad4mModel {
1401
1597
  // Handle all arrays as relations, including empty ones (which clears the relation)
1402
1598
  await this.setRelationValues(key, value, batchId);
1403
1599
  } else if (value !== undefined && value !== null && value !== "") {
1404
- if (setProperties) {
1405
- // Check if this is a relation property (has relation metadata)
1406
- const relationMeta = this.getRelationOptions(key);
1407
- if (relationMeta) {
1408
- // Skip - it's a relation, not a regular property
1409
- continue;
1410
- }
1600
+ // A scalar handed to a relation field is a single-member relation.
1601
+ //
1602
+ // This used to `continue` — "Skip, it's a relation, not a regular
1603
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
1604
+ // ran, resolved, and wrote no link. The record was created with the
1605
+ // relation empty and nothing anywhere said so, which surfaces later as
1606
+ // a *reader* complaining about a malformed instance: a Relationship
1607
+ // with no endpoints, a Placement pointing at nothing. Both look like
1608
+ // rendering bugs from the outside, because the record exists and the
1609
+ // thing that should reference it does not.
1610
+ //
1611
+ // The array form is the documented path and stays correct; the problem
1612
+ // is that the scalar form is plausible, typechecks against a field
1613
+ // declared `string`, and fails silently. Coercing matches what a caller
1614
+ // reaching for it meant. A value `setRelationValues` cannot use now
1615
+ // fails there, loudly, instead of vanishing here.
1616
+ //
1617
+ // Deliberately outside the `setProperties` gate, mirroring the array
1618
+ // branch above. `create` passes `setProperties: false` when the class
1619
+ // has a constructor, because `create_subject` writes the values map —
1620
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
1621
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
1622
+ // Relations have to be written here in both cases or they are lost by
1623
+ // both paths at once.
1624
+ const relationMeta = this.getRelationOptions(key);
1625
+ if (relationMeta) {
1626
+ await this.setRelationValues(key, [value], batchId);
1627
+ continue;
1628
+ }
1411
1629
 
1630
+ if (setProperties) {
1412
1631
  // Skip flag properties — they are immutable after creation
1413
1632
  const propMeta = this.getPropertyMetadata(key);
1414
1633
  if (propMeta?.flag) {