@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
@@ -15,6 +15,110 @@ import { normalizeValue, } from "./hydration";
15
15
  * Rust endpoint. Recursively converts included relation values (which come
16
16
  * back as plain JSON objects) into proper model class instances.
17
17
  */
18
+ /**
19
+ * Key under which the executor returns a polymorphically-hydrated instance's
20
+ * concrete class.
21
+ *
22
+ * Half of a wire contract: the writer is `SUBJECT_CLASS_KEY` in
23
+ * `rust-executor/src/perspectives/model_query/relations.rs`, and the two are
24
+ * separate literals in separate languages. Renaming one alone does not fail to
25
+ * compile — it degrades to every instance staying plain JSON, which looks
26
+ * identical to a relation that declared no classes to build.
27
+ * `tests/js/tests/model/model-polymorphic.test.ts` drives both ends against one
28
+ * executor, so the drift fails a test rather than a user's query.
29
+ *
30
+ * The executor also returns `__subjectClasses`, the whole set this one names the
31
+ * head of. Nothing here reads it — it rides onto the instance with every other
32
+ * JSON key, for a caller that wants to know a choice was made.
33
+ */
34
+ const SUBJECT_CLASS_KEY = '__subjectClass';
35
+ /**
36
+ * Turn on `polymorphic` for every relation that declares it, at every depth of
37
+ * an include map.
38
+ *
39
+ * A relation being heterogeneous is a fact about the data, not about one query,
40
+ * so the declaration lives on the model and the call site writes
41
+ * `include: { children: true }`. That has to hold just as much one level down:
42
+ * in `include: { posts: { include: { children: true } } }`, `children` is a
43
+ * relation on `Post`, so the walk carries the class it is reading against down
44
+ * with it. Without that, a nested include of an untyped polymorphic relation
45
+ * reaches the executor with no shape to resolve and fails the query outright.
46
+ *
47
+ * An explicit `polymorphic: false` at any level still wins — `undefined` is the
48
+ * only state the default fills in.
49
+ *
50
+ * The walk stops descending *through* a polymorphic relation, because there is
51
+ * nothing to descend into: its targets are of several classes by definition, so
52
+ * no single class's metadata could say what a deeper include means. The
53
+ * executor resolves those nested includes against each concrete class instead.
54
+ */
55
+ function applyPolymorphicIncludeDefaults(includes, ctor) {
56
+ const relMeta = getRelationsMetadata(ctor);
57
+ for (const [relName, val] of Object.entries(includes)) {
58
+ // `$`-prefixed keys are projections, not relations.
59
+ if (relName.startsWith('$'))
60
+ continue;
61
+ const meta = relMeta[relName];
62
+ if (!meta)
63
+ continue;
64
+ let subQuery = val;
65
+ if (meta.polymorphic) {
66
+ if (val === true) {
67
+ subQuery = { polymorphic: true };
68
+ includes[relName] = subQuery;
69
+ }
70
+ else if (typeof val === 'object' && val !== null && subQuery.polymorphic === undefined) {
71
+ subQuery.polymorphic = true;
72
+ }
73
+ // The classes this call site can build are also the classes it wants its
74
+ // targets read as, so the declaration answers both questions and the call
75
+ // site repeats neither. Sent as part of the query rather than applied to
76
+ // the results: a preference in the request is reproducible by anyone who
77
+ // sends it, where one applied afterwards would make the same data read
78
+ // differently depending on which classes the caller happened to import.
79
+ //
80
+ // It ranks and does not narrow — a target matching none of them still
81
+ // arrives — so declaring what you can construct never costs you a member
82
+ // of a relation that is heterogeneous by definition.
83
+ if (typeof subQuery === 'object' &&
84
+ subQuery !== null &&
85
+ subQuery.polymorphic &&
86
+ subQuery.preferClasses === undefined &&
87
+ meta.instantiateAs) {
88
+ const names = (meta.instantiateAs() ?? [])
89
+ .map((cls) => cls?.className)
90
+ .filter((name) => typeof name === 'string');
91
+ if (names.length)
92
+ subQuery.preferClasses = names;
93
+ }
94
+ }
95
+ if (typeof subQuery !== 'object' || subQuery === null)
96
+ continue;
97
+ const nested = subQuery.include;
98
+ if (!nested || subQuery.polymorphic)
99
+ continue;
100
+ // The thunk is only evaluated here, at query time, so a self-referential or
101
+ // circularly-imported target that is not yet defined costs the nested
102
+ // default rather than the whole query.
103
+ let TargetClass;
104
+ try {
105
+ TargetClass = meta.target?.();
106
+ }
107
+ catch (e) {
108
+ // A class not yet initialised throws `ReferenceError` from the temporal
109
+ // dead zone, which is the expected cost of an import cycle and not worth
110
+ // saying anything about. Anything else — a thunk closing over nothing,
111
+ // typically — is a broken declaration that would otherwise cost the nested
112
+ // default in silence, so it gets said out loud.
113
+ const circularImport = e instanceof ReferenceError;
114
+ const say = circularImport ? console.debug : console.warn;
115
+ say(`prepareModelQueryParams: target class unavailable for include '${relName}':`, e);
116
+ continue;
117
+ }
118
+ if (TargetClass)
119
+ applyPolymorphicIncludeDefaults(nested, TargetClass);
120
+ }
121
+ }
18
122
  function jsonToModelInstance(ModelClass, perspective, json, include, properties) {
19
123
  const instance = new ModelClass(perspective, json.id || json.baseExpression);
20
124
  // When a properties projection is active, remove own properties set by the
@@ -61,9 +165,62 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
61
165
  if (!includeVal)
62
166
  continue;
63
167
  const meta = relMeta[relName];
64
- if (!meta?.target)
168
+ // A polymorphic relation may legitimately declare no target at all —
169
+ // that is the case it exists for — so it must not be gated on one.
170
+ if (!meta)
65
171
  continue;
66
- const TargetClass = meta.target();
172
+ if (!meta.target && !meta.polymorphic)
173
+ continue;
174
+ const TargetClass = meta.target?.();
175
+ // For a polymorphic relation the executor sends each child's concrete
176
+ // class back on the instance, because it had to know it in order to
177
+ // hydrate against the right shape at all. What it cannot send is the
178
+ // constructor, so `instantiateAs` names the classes this side can build
179
+ // and the name → class map is derived from them: `@Model` records each
180
+ // class's name on the class itself, so listing the classes and listing
181
+ // their names would be the same list written twice, free to disagree.
182
+ //
183
+ // Built on first use rather than at decoration time, because the thunk
184
+ // exists to be called late: a class defined further round a circular
185
+ // import graph is not there yet when the decorator runs.
186
+ let byClassName;
187
+ // May resolve to nothing: a polymorphic relation is allowed to declare no
188
+ // target at all, and the list may not name the class that arrived — it
189
+ // says what this call site can construct, not what the relation may hold.
190
+ // The item then stays plain JSON — correct data, carrying its class name
191
+ // for a caller that wants to dispatch on it — rather than being forced
192
+ // through a constructor that does not exist.
193
+ const resolveChildClass = (item) => {
194
+ if (!meta.polymorphic)
195
+ return TargetClass;
196
+ const concrete = item?.[SUBJECT_CLASS_KEY];
197
+ // No concrete class means this was not read polymorphically after all —
198
+ // an explicit `polymorphic: false` at the call site — so the relation's
199
+ // own declared target is the right shape.
200
+ if (typeof concrete !== 'string')
201
+ return TargetClass;
202
+ if (meta.instantiateAs) {
203
+ if (!byClassName) {
204
+ byClassName = {};
205
+ for (const cls of meta.instantiateAs() ?? []) {
206
+ const name = cls?.className;
207
+ if (typeof name === 'string')
208
+ byClassName[name] = cls;
209
+ }
210
+ }
211
+ if (byClassName[concrete])
212
+ return byClassName[concrete];
213
+ }
214
+ // The declared target is not a fallback, and having named no classes to
215
+ // build does not make it one. Where a relation both declares a target
216
+ // and reads polymorphically, a child of some third class was hydrated
217
+ // against *its own* shape, so constructing the declared class over that
218
+ // JSON produces an instance that answers `instanceof` for a class it is
219
+ // not, carrying fields that class never declared — the exact
220
+ // mislabelling polymorphic reads exist to prevent. It fits only when it
221
+ // is the class the executor named.
222
+ return TargetClass?.className === concrete ? TargetClass : undefined;
223
+ };
67
224
  const nestedInclude = typeof includeVal === 'object' && includeVal !== null
68
225
  ? includeVal.include
69
226
  : undefined;
@@ -73,14 +230,18 @@ function jsonToModelInstance(ModelClass, perspective, json, include, properties)
73
230
  const raw = instance[relName];
74
231
  if (Array.isArray(raw)) {
75
232
  instance[relName] = raw.map((item) => {
76
- if (typeof item === 'object' && item !== null && item.id) {
77
- return jsonToModelInstance(TargetClass, perspective, item, nestedInclude, nestedProperties);
233
+ const ChildClass = resolveChildClass(item);
234
+ if (ChildClass && typeof item === 'object' && item !== null && item.id) {
235
+ return jsonToModelInstance(ChildClass, perspective, item, nestedInclude, nestedProperties);
78
236
  }
79
237
  return item;
80
238
  });
81
239
  }
82
240
  else if (typeof raw === 'object' && raw !== null && raw.id) {
83
- instance[relName] = jsonToModelInstance(TargetClass, perspective, raw, nestedInclude, nestedProperties);
241
+ const ChildClass = resolveChildClass(raw);
242
+ if (ChildClass) {
243
+ instance[relName] = jsonToModelInstance(ChildClass, perspective, raw, nestedInclude, nestedProperties);
244
+ }
84
245
  }
85
246
  }
86
247
  }
@@ -328,6 +489,7 @@ export class Ad4mModel {
328
489
  ...(options.target !== undefined && { target: options.target }),
329
490
  ...(options.filter !== undefined && { filter: options.filter }),
330
491
  ...(options.where !== undefined && { where: options.where }),
492
+ ...(options.ordering !== undefined && { ordering: options.ordering }),
331
493
  };
332
494
  }
333
495
  // Fallback: If both structures are empty but a JSON schema is attached, derive from it
@@ -595,10 +757,22 @@ export class Ad4mModel {
595
757
  const current = normalizeValue(this[field]);
596
758
  const original = this._snapshot[field];
597
759
  if (Array.isArray(current) || Array.isArray(original)) {
598
- // Order-insensitive comparison (sorted) so reordering alone
599
- // doesn't mark a relation as dirty.
600
- const a = Array.isArray(current) ? [...current].sort() : [];
601
- const b = Array.isArray(original) ? [...original].sort() : [];
760
+ // For an ordered relation the sequence *is* the state, so a reorder is
761
+ // the whole change and must mark the field dirty — sorting first would
762
+ // make `save()` a no-op for the one edit the ordering feature exists to
763
+ // support.
764
+ //
765
+ // Everything else compares order-insensitively, because an unordered
766
+ // relation is a set: the executor returns its members by link timestamp,
767
+ // and a caller who assigned the same members in another order has not
768
+ // changed anything.
769
+ const ordered = !!metadata.relations[field]?.ordering;
770
+ const a = Array.isArray(current) ? [...current] : [];
771
+ const b = Array.isArray(original) ? [...original] : [];
772
+ if (!ordered) {
773
+ a.sort();
774
+ b.sort();
775
+ }
602
776
  if (a.length !== b.length || a.some((v, i) => v !== b[i])) {
603
777
  changed.push(field);
604
778
  }
@@ -738,8 +912,17 @@ export class Ad4mModel {
738
912
  normalIncludes[key] = val;
739
913
  }
740
914
  }
741
- if (Object.keys(normalIncludes).length > 0)
915
+ // A relation declared `polymorphic` reads that way by default, so the
916
+ // caller writes `include: { children: true }` and still gets each child
917
+ // hydrated as the class it actually is. Declaring it on the model rather
918
+ // than repeating it at every call site is the point — the relation being
919
+ // heterogeneous is a fact about the data, not about one query — but an
920
+ // explicit `polymorphic: false` at the call site still wins. Applied at
921
+ // every depth, since a nested include is a fact about the data too.
922
+ if (Object.keys(normalIncludes).length > 0) {
923
+ applyPolymorphicIncludeDefaults(normalIncludes, this);
742
924
  queryInput.include = normalIncludes;
925
+ }
743
926
  if (Object.keys(projections).length > 0) {
744
927
  // Tag each projection with its target class name so the executor can
745
928
  // resolve the target shape through its in-memory cache when applying
@@ -805,11 +988,11 @@ export class Ad4mModel {
805
988
  *
806
989
  * @internal
807
990
  */
808
- static async executeModelQuery(perspective, query = {}, classNameOverride) {
991
+ static async executeModelQuery(perspective, query = {}, classNameOverride, options) {
809
992
  // Delegate query input building to the shared prepareModelQueryParams
810
993
  // helper. The executor resolves the shape from SHACL server-side.
811
994
  const { className, queryJson } = this.prepareModelQueryParams(query, classNameOverride);
812
- const result = await perspective.modelQuery(className, queryJson);
995
+ const result = await perspective.modelQuery(className, queryJson, options);
813
996
  // Convert JSON instances to model class instances, recursively constructing
814
997
  // class instances for any included relations resolved by Rust.
815
998
  const instances = result.instances.map((json) => {
@@ -850,12 +1033,12 @@ export class Ad4mModel {
850
1033
  * });
851
1034
  * ```
852
1035
  */
853
- static async findAll(perspective, query) {
1036
+ static async findAll(perspective, query, options) {
854
1037
  const q = (query ?? {});
855
1038
  if (q.properties && q.properties.length === 0) {
856
1039
  throw new Error("properties[] must not be empty — omit the field to return all properties, or specify at least one field name");
857
1040
  }
858
- const { results } = await this.executeModelQuery(perspective, q);
1041
+ const { results } = await this.executeModelQuery(perspective, q, undefined, options);
859
1042
  return results;
860
1043
  }
861
1044
  /**
@@ -878,9 +1061,9 @@ export class Ad4mModel {
878
1061
  * }
879
1062
  * ```
880
1063
  */
881
- static async findOne(perspective, query) {
1064
+ static async findOne(perspective, query, options) {
882
1065
  const limitedQuery = { ...(query ?? {}), limit: 1 };
883
- const results = await this.findAll(perspective, limitedQuery);
1066
+ const results = await this.findAll(perspective, limitedQuery, options);
884
1067
  return results[0] ?? null;
885
1068
  }
886
1069
  /**
@@ -900,8 +1083,8 @@ export class Ad4mModel {
900
1083
  * console.log(`Showing 10 of ${totalCount} dessert recipes`);
901
1084
  * ```
902
1085
  */
903
- static async findAllAndCount(perspective, query) {
904
- const out = await this.executeModelQuery(perspective, (query ?? {}));
1086
+ static async findAllAndCount(perspective, query, options) {
1087
+ const out = await this.executeModelQuery(perspective, (query ?? {}), undefined, options);
905
1088
  return out;
906
1089
  }
907
1090
  /**
@@ -921,9 +1104,9 @@ export class Ad4mModel {
921
1104
  * console.log(`Page ${page.pageNumber} of recipes, ${page.results.length} items`);
922
1105
  * ```
923
1106
  */
924
- static async paginate(perspective, pageSize, pageNumber, query) {
1107
+ static async paginate(perspective, pageSize, pageNumber, query, options) {
925
1108
  const paginationQuery = { ...(query ?? {}), limit: pageSize, offset: pageSize * (pageNumber - 1), count: true };
926
- const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery);
1109
+ const { results, totalCount } = await this.executeModelQuery(perspective, paginationQuery, undefined, options);
927
1110
  return { results: results, totalCount, pageSize, pageNumber };
928
1111
  }
929
1112
  /**
@@ -951,8 +1134,8 @@ export class Ad4mModel {
951
1134
  * });
952
1135
  * ```
953
1136
  */
954
- static async count(perspective, query) {
955
- const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 });
1137
+ static async count(perspective, query, options) {
1138
+ const { totalCount } = await this.executeModelQuery(perspective, { ...(query ?? {}), limit: 0 }, undefined, options);
956
1139
  return totalCount;
957
1140
  }
958
1141
  async setProperty(key, value, batchId) {
@@ -1106,7 +1289,18 @@ export class Ad4mModel {
1106
1289
  for (const [key, value] of Object.entries(this)) {
1107
1290
  if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
1108
1291
  const propMeta = metadata.properties[key];
1109
- if (propMeta && effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1292
+ // Only offer keys with a declared, settable model property. This
1293
+ // excludes ORM bookkeeping fields (_baseExpression, _perspective —
1294
+ // enumerable instance fields, not model properties), HasMany
1295
+ // relations (tracked in a separate registry, never in
1296
+ // `metadata.properties`), and read-only properties/flags
1297
+ // (readOnly: true). None of these have an `ad4m://setter` on the
1298
+ // Rust side, which otherwise logs a "declares no setter" warning
1299
+ // per key on every save().
1300
+ if (!propMeta || propMeta.readOnly) {
1301
+ continue;
1302
+ }
1303
+ if (effectiveLiteralStorage(propMeta).kind !== "deterministic") {
1110
1304
  deferredExpressionProps.push(key);
1111
1305
  continue;
1112
1306
  }
@@ -1215,13 +1409,36 @@ export class Ad4mModel {
1215
1409
  await this.setRelationValues(key, value, batchId);
1216
1410
  }
1217
1411
  else if (value !== undefined && value !== null && value !== "") {
1412
+ // A scalar handed to a relation field is a single-member relation.
1413
+ //
1414
+ // This used to `continue` — "Skip, it's a relation, not a regular
1415
+ // property" — so `Model.create(p, { source: 'uri://x' })` typechecked,
1416
+ // ran, resolved, and wrote no link. The record was created with the
1417
+ // relation empty and nothing anywhere said so, which surfaces later as
1418
+ // a *reader* complaining about a malformed instance: a Relationship
1419
+ // with no endpoints, a Placement pointing at nothing. Both look like
1420
+ // rendering bugs from the outside, because the record exists and the
1421
+ // thing that should reference it does not.
1422
+ //
1423
+ // The array form is the documented path and stays correct; the problem
1424
+ // is that the scalar form is plausible, typechecks against a field
1425
+ // declared `string`, and fails silently. Coercing matches what a caller
1426
+ // reaching for it meant. A value `setRelationValues` cannot use now
1427
+ // fails there, loudly, instead of vanishing here.
1428
+ //
1429
+ // Deliberately outside the `setProperties` gate, mirroring the array
1430
+ // branch above. `create` passes `setProperties: false` when the class
1431
+ // has a constructor, because `create_subject` writes the values map —
1432
+ // but a relation carries `ad4m://adder`, not `ad4m://setter`, so
1433
+ // `create_subject` drops it (see the warning added in 3ee2b5bc6).
1434
+ // Relations have to be written here in both cases or they are lost by
1435
+ // both paths at once.
1436
+ const relationMeta = this.getRelationOptions(key);
1437
+ if (relationMeta) {
1438
+ await this.setRelationValues(key, [value], batchId);
1439
+ continue;
1440
+ }
1218
1441
  if (setProperties) {
1219
- // Check if this is a relation property (has relation metadata)
1220
- const relationMeta = this.getRelationOptions(key);
1221
- if (relationMeta) {
1222
- // Skip - it's a relation, not a regular property
1223
- continue;
1224
- }
1225
1442
  // Skip flag properties — they are immutable after creation
1226
1443
  const propMeta = this.getPropertyMetadata(key);
1227
1444
  if (propMeta?.flag) {