@coasys/ad4m 0.12.0-rc1-dev.4 → 0.12.0-rc1-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/index.cjs +565 -122
- package/lib/index.js +565 -123
- package/lib/src/model/Ad4mModel.d.ts +33 -3
- package/lib/src/model/Ad4mModel.js +155 -37
- package/lib/src/model/decorators.d.ts +73 -7
- package/lib/src/model/decorators.js +188 -34
- package/lib/src/model/relation-filtering.test.d.ts +1 -0
- package/lib/src/model/relation-filtering.test.js +838 -0
- package/lib/src/model/surreal-utils.d.ts +42 -0
- package/lib/src/model/surreal-utils.js +128 -0
- package/lib/src/shacl/SHACLShape.d.ts +23 -0
- package/lib/src/shacl/SHACLShape.js +45 -0
- package/package.json +1 -1
- package/src/model/Ad4mModel.ts +177 -40
- package/src/model/decorators.ts +268 -45
- package/src/model/relation-filtering.test.ts +804 -0
- package/src/model/surreal-utils.ts +147 -0
- package/src/shacl/SHACLShape.ts +83 -0
package/lib/index.js
CHANGED
|
@@ -4932,6 +4932,27 @@ class SHACLShape {
|
|
|
4932
4932
|
target: `literal://string:${JSON.stringify(prop.remover)}`
|
|
4933
4933
|
});
|
|
4934
4934
|
}
|
|
4935
|
+
if (prop.getter) {
|
|
4936
|
+
links.push({
|
|
4937
|
+
source: propShapeId,
|
|
4938
|
+
predicate: "ad4m://getter",
|
|
4939
|
+
target: `literal://string:${prop.getter}`
|
|
4940
|
+
});
|
|
4941
|
+
}
|
|
4942
|
+
if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
|
|
4943
|
+
links.push({
|
|
4944
|
+
source: propShapeId,
|
|
4945
|
+
predicate: "ad4m://conformanceConditions",
|
|
4946
|
+
target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
|
|
4947
|
+
});
|
|
4948
|
+
}
|
|
4949
|
+
if (prop.class) {
|
|
4950
|
+
links.push({
|
|
4951
|
+
source: propShapeId,
|
|
4952
|
+
predicate: "sh://class",
|
|
4953
|
+
target: prop.class
|
|
4954
|
+
});
|
|
4955
|
+
}
|
|
4935
4956
|
}
|
|
4936
4957
|
return links;
|
|
4937
4958
|
}
|
|
@@ -5085,6 +5106,24 @@ class SHACLShape {
|
|
|
5085
5106
|
// Ignore parse errors
|
|
5086
5107
|
}
|
|
5087
5108
|
}
|
|
5109
|
+
const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
|
|
5110
|
+
if (getterLink) {
|
|
5111
|
+
prop.getter = getterLink.target.replace('literal://string:', '');
|
|
5112
|
+
}
|
|
5113
|
+
const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
|
|
5114
|
+
if (conditionsLink) {
|
|
5115
|
+
try {
|
|
5116
|
+
const jsonStr = conditionsLink.target.replace('literal://string:', '');
|
|
5117
|
+
prop.conformanceConditions = JSON.parse(jsonStr);
|
|
5118
|
+
}
|
|
5119
|
+
catch (e) {
|
|
5120
|
+
// Ignore parse errors
|
|
5121
|
+
}
|
|
5122
|
+
}
|
|
5123
|
+
const classLink = links.find(l => l.source === propShapeId && l.predicate === "sh://class");
|
|
5124
|
+
if (classLink) {
|
|
5125
|
+
prop.class = classLink.target;
|
|
5126
|
+
}
|
|
5088
5127
|
shape.addProperty(prop);
|
|
5089
5128
|
}
|
|
5090
5129
|
return shape;
|
|
@@ -5117,6 +5156,9 @@ class SHACLShape {
|
|
|
5117
5156
|
setter: p.setter,
|
|
5118
5157
|
adder: p.adder,
|
|
5119
5158
|
remover: p.remover,
|
|
5159
|
+
getter: p.getter,
|
|
5160
|
+
conformance_conditions: p.conformanceConditions,
|
|
5161
|
+
class: p.class,
|
|
5120
5162
|
})),
|
|
5121
5163
|
constructor_actions: this.constructor_actions,
|
|
5122
5164
|
destructor_actions: this.destructor_actions,
|
|
@@ -5147,6 +5189,9 @@ class SHACLShape {
|
|
|
5147
5189
|
setter: p.setter,
|
|
5148
5190
|
adder: p.adder,
|
|
5149
5191
|
remover: p.remover,
|
|
5192
|
+
getter: p.getter,
|
|
5193
|
+
conformanceConditions: p.conformance_conditions,
|
|
5194
|
+
class: p.class,
|
|
5150
5195
|
});
|
|
5151
5196
|
}
|
|
5152
5197
|
if (json.constructor_actions) {
|
|
@@ -5164,6 +5209,186 @@ class SHACLShape {
|
|
|
5164
5209
|
}
|
|
5165
5210
|
}
|
|
5166
5211
|
|
|
5212
|
+
function formatList(list) {
|
|
5213
|
+
if (!list?.length) {
|
|
5214
|
+
return "";
|
|
5215
|
+
}
|
|
5216
|
+
if (list.length === 1) {
|
|
5217
|
+
return list.toString();
|
|
5218
|
+
}
|
|
5219
|
+
if (list.length === 2) {
|
|
5220
|
+
return list.join(' and ');
|
|
5221
|
+
}
|
|
5222
|
+
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
5223
|
+
}
|
|
5224
|
+
function capSentence(cap) {
|
|
5225
|
+
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
5226
|
+
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
5227
|
+
const pointers = cap.with.pointers.includes("*")
|
|
5228
|
+
? ["all AD4M data"]
|
|
5229
|
+
: cap.with.pointers;
|
|
5230
|
+
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
5231
|
+
}
|
|
5232
|
+
/**
|
|
5233
|
+
* Escapes a string value for safe use in SurrealQL queries.
|
|
5234
|
+
*
|
|
5235
|
+
* @description
|
|
5236
|
+
* Prevents SQL injection by properly escaping special characters in string values
|
|
5237
|
+
* that will be interpolated into SurrealQL queries. This handles the most common
|
|
5238
|
+
* special characters that could break SQL queries or enable injection attacks.
|
|
5239
|
+
*
|
|
5240
|
+
* Single quotes, backslashes, and other special characters are escaped using
|
|
5241
|
+
* backslash notation, which is the standard escaping mechanism for SurrealQL.
|
|
5242
|
+
*
|
|
5243
|
+
* @param value - The string value to escape
|
|
5244
|
+
* @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
|
|
5245
|
+
*
|
|
5246
|
+
* @example
|
|
5247
|
+
* ```typescript
|
|
5248
|
+
* const userInput = "user's input with 'quotes'";
|
|
5249
|
+
* const escaped = escapeSurrealString(userInput);
|
|
5250
|
+
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
5251
|
+
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
5252
|
+
* ```
|
|
5253
|
+
*/
|
|
5254
|
+
function escapeSurrealString(value) {
|
|
5255
|
+
return value
|
|
5256
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
5257
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
5258
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
5259
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
5260
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
5261
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
5262
|
+
}
|
|
5263
|
+
|
|
5264
|
+
/**
|
|
5265
|
+
* Shared SurrealQL compilation utilities.
|
|
5266
|
+
*
|
|
5267
|
+
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
5268
|
+
* the compile-time SHACL generator (`decorators.ts`).
|
|
5269
|
+
*/
|
|
5270
|
+
/**
|
|
5271
|
+
* Format a JavaScript value for embedding in a SurrealQL expression.
|
|
5272
|
+
*
|
|
5273
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
5274
|
+
* - Numbers and booleans are passed through as-is
|
|
5275
|
+
* - Arrays are recursed
|
|
5276
|
+
*/
|
|
5277
|
+
function formatSurrealValue(value) {
|
|
5278
|
+
if (typeof value === 'string') {
|
|
5279
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
5280
|
+
const escaped = value
|
|
5281
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
5282
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
5283
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
5284
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
5285
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
5286
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
5287
|
+
return `'${escaped}'`;
|
|
5288
|
+
}
|
|
5289
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
5290
|
+
return String(value);
|
|
5291
|
+
}
|
|
5292
|
+
else if (Array.isArray(value)) {
|
|
5293
|
+
return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
|
|
5294
|
+
}
|
|
5295
|
+
else {
|
|
5296
|
+
return String(value);
|
|
5297
|
+
}
|
|
5298
|
+
}
|
|
5299
|
+
/**
|
|
5300
|
+
* Compile a single Where condition for a property into a SurrealQL
|
|
5301
|
+
* graph-traversal sub-expression.
|
|
5302
|
+
*
|
|
5303
|
+
* Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
|
|
5304
|
+
* style checks that can be used inside a `[WHERE ...]` filter on nodes.
|
|
5305
|
+
*
|
|
5306
|
+
* @param predicate - The predicate URI for the property
|
|
5307
|
+
* @param condition - The Where condition value
|
|
5308
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
5309
|
+
* @returns A single SurrealQL condition string
|
|
5310
|
+
*/
|
|
5311
|
+
function buildWhereCondition(predicate, condition, opts) {
|
|
5312
|
+
const escapedPredicate = escapeSurrealString(predicate);
|
|
5313
|
+
const targetField = opts?.resolveLanguage === 'literal'
|
|
5314
|
+
? 'fn::parse_literal(out.uri)'
|
|
5315
|
+
: 'out.uri';
|
|
5316
|
+
if (Array.isArray(condition)) {
|
|
5317
|
+
// Array values → IN clause
|
|
5318
|
+
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
5319
|
+
return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
|
|
5320
|
+
}
|
|
5321
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
5322
|
+
// Operator object
|
|
5323
|
+
const ops = condition;
|
|
5324
|
+
const parts = [];
|
|
5325
|
+
if (ops.not !== undefined) {
|
|
5326
|
+
if (Array.isArray(ops.not)) {
|
|
5327
|
+
const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
|
|
5328
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
5329
|
+
}
|
|
5330
|
+
else {
|
|
5331
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
5332
|
+
}
|
|
5333
|
+
}
|
|
5334
|
+
// Comparison operators — ensure property exists (actual comparison
|
|
5335
|
+
// may be post-filtered in JS at runtime, but the SurrealQL condition
|
|
5336
|
+
// is valid for compile-time getter generation too).
|
|
5337
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
5338
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
5339
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
5340
|
+
if (hasComparisonOps) {
|
|
5341
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
|
|
5342
|
+
}
|
|
5343
|
+
return parts.join(' AND ');
|
|
5344
|
+
}
|
|
5345
|
+
else {
|
|
5346
|
+
// Simple equality
|
|
5347
|
+
return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
|
|
5348
|
+
}
|
|
5349
|
+
}
|
|
5350
|
+
/**
|
|
5351
|
+
* Compile a full `Where` clause to an array of SurrealQL condition strings.
|
|
5352
|
+
*
|
|
5353
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
5354
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
5355
|
+
* names are treated as raw predicate URIs.
|
|
5356
|
+
*
|
|
5357
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
5358
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
5359
|
+
* runtime query time, not for compile-time getter generation).
|
|
5360
|
+
*/
|
|
5361
|
+
function compileWhereClause(where, metadata) {
|
|
5362
|
+
const conditions = [];
|
|
5363
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
5364
|
+
// Skip special fields that don't apply at compile time
|
|
5365
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
5366
|
+
continue;
|
|
5367
|
+
let predicate;
|
|
5368
|
+
let resolveLanguage;
|
|
5369
|
+
if (metadata) {
|
|
5370
|
+
const propMeta = metadata.properties[propertyName];
|
|
5371
|
+
if (propMeta) {
|
|
5372
|
+
predicate = propMeta.predicate;
|
|
5373
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
5374
|
+
}
|
|
5375
|
+
else {
|
|
5376
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
5377
|
+
predicate = propertyName;
|
|
5378
|
+
}
|
|
5379
|
+
}
|
|
5380
|
+
else {
|
|
5381
|
+
// No metadata — treat name as raw predicate URI
|
|
5382
|
+
predicate = propertyName;
|
|
5383
|
+
}
|
|
5384
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
|
|
5385
|
+
if (cond) {
|
|
5386
|
+
conditions.push(cond);
|
|
5387
|
+
}
|
|
5388
|
+
}
|
|
5389
|
+
return conditions;
|
|
5390
|
+
}
|
|
5391
|
+
|
|
5167
5392
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
5168
5393
|
const propertyRegistry = new WeakMap();
|
|
5169
5394
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
@@ -5224,6 +5449,57 @@ function setRelationRegistryEntry(ctor, relName, meta) {
|
|
|
5224
5449
|
relationRegistry.set(ctor, {});
|
|
5225
5450
|
relationRegistry.get(ctor)[relName] = meta;
|
|
5226
5451
|
}
|
|
5452
|
+
/**
|
|
5453
|
+
* Build a conformance filter for a relation whose target model is known.
|
|
5454
|
+
*
|
|
5455
|
+
* Inspects the target class's property metadata to derive:
|
|
5456
|
+
* - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
|
|
5457
|
+
* - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
|
|
5458
|
+
* target nodes to only those conforming to the target shape.
|
|
5459
|
+
*
|
|
5460
|
+
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
5461
|
+
* @param targetClass - The target model class (resolved from the target() thunk)
|
|
5462
|
+
* @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived
|
|
5463
|
+
*/
|
|
5464
|
+
function buildConformanceFilter(relationPredicate, targetClass) {
|
|
5465
|
+
try {
|
|
5466
|
+
const targetProps = getPropertiesMetadata(targetClass);
|
|
5467
|
+
const conditions = [];
|
|
5468
|
+
const surrealConditions = [];
|
|
5469
|
+
// 1. Flags — check predicate + value
|
|
5470
|
+
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
5471
|
+
if (propMeta.flag && propMeta.initial && propMeta.through) {
|
|
5472
|
+
conditions.push({
|
|
5473
|
+
type: 'flag',
|
|
5474
|
+
predicate: propMeta.through,
|
|
5475
|
+
value: propMeta.initial,
|
|
5476
|
+
});
|
|
5477
|
+
surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
5478
|
+
}
|
|
5479
|
+
}
|
|
5480
|
+
// 2. Required (non-flag) properties — check predicate exists
|
|
5481
|
+
// Skip properties with custom getters (they don't follow the standard link pattern)
|
|
5482
|
+
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
5483
|
+
if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {
|
|
5484
|
+
conditions.push({
|
|
5485
|
+
type: 'required',
|
|
5486
|
+
predicate: propMeta.through,
|
|
5487
|
+
});
|
|
5488
|
+
surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`);
|
|
5489
|
+
}
|
|
5490
|
+
}
|
|
5491
|
+
if (conditions.length === 0) {
|
|
5492
|
+
return undefined;
|
|
5493
|
+
}
|
|
5494
|
+
const escapedPredicate = escapeSurrealString(relationPredicate);
|
|
5495
|
+
const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
|
|
5496
|
+
return { getter, conformanceConditions: conditions };
|
|
5497
|
+
}
|
|
5498
|
+
catch (e) {
|
|
5499
|
+
// Target class may not have property metadata
|
|
5500
|
+
return undefined;
|
|
5501
|
+
}
|
|
5502
|
+
}
|
|
5227
5503
|
/**
|
|
5228
5504
|
* Convert a model instance to a plain serializable object.
|
|
5229
5505
|
* Reads the property metadata and extracts values from the instance.
|
|
@@ -5762,6 +6038,60 @@ function Model(opts) {
|
|
|
5762
6038
|
target: "value",
|
|
5763
6039
|
...(relMeta.local && { local: true })
|
|
5764
6040
|
}];
|
|
6041
|
+
// === Build Getter (conformance filter) ===
|
|
6042
|
+
// Priority chain:
|
|
6043
|
+
// 1. Explicit getter string → use verbatim
|
|
6044
|
+
// 2. `where` clause → compile DSL to SurrealQL getter
|
|
6045
|
+
// 3. target + filter !== false → auto-derive from shape
|
|
6046
|
+
if (relMeta.getter) {
|
|
6047
|
+
relShape.getter = relMeta.getter;
|
|
6048
|
+
}
|
|
6049
|
+
else if (relMeta.where) {
|
|
6050
|
+
// Compile Where DSL → SurrealQL getter
|
|
6051
|
+
try {
|
|
6052
|
+
const TargetClass = relMeta.target?.();
|
|
6053
|
+
const targetMetadata = TargetClass
|
|
6054
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
6055
|
+
: null;
|
|
6056
|
+
const conditions = compileWhereClause(relMeta.where, targetMetadata);
|
|
6057
|
+
if (conditions.length > 0) {
|
|
6058
|
+
const escapedPredicate = escapeSurrealString(relMeta.predicate);
|
|
6059
|
+
relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
|
|
6060
|
+
}
|
|
6061
|
+
}
|
|
6062
|
+
catch (e) {
|
|
6063
|
+
// Target metadata may not be available yet
|
|
6064
|
+
}
|
|
6065
|
+
}
|
|
6066
|
+
else if (relMeta.target && relMeta.filter !== false) {
|
|
6067
|
+
try {
|
|
6068
|
+
const TargetClass = relMeta.target();
|
|
6069
|
+
const filter = buildConformanceFilter(relMeta.predicate, TargetClass);
|
|
6070
|
+
if (filter) {
|
|
6071
|
+
relShape.getter = filter.getter;
|
|
6072
|
+
relShape.conformanceConditions = filter.conformanceConditions;
|
|
6073
|
+
}
|
|
6074
|
+
}
|
|
6075
|
+
catch (e) {
|
|
6076
|
+
// Target class may not be available yet — getter will be
|
|
6077
|
+
// absent and runtime will fall back to unfiltered get_links
|
|
6078
|
+
}
|
|
6079
|
+
}
|
|
6080
|
+
// === sh:class — target shape reference ===
|
|
6081
|
+
// Always set when a target model is declared, regardless of filter.
|
|
6082
|
+
// This enables typed construction on the Rust/MCP side.
|
|
6083
|
+
if (relMeta.target) {
|
|
6084
|
+
try {
|
|
6085
|
+
const TargetClass = relMeta.target();
|
|
6086
|
+
const targetSHACL = TargetClass.generateSHACL?.();
|
|
6087
|
+
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
6088
|
+
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
6089
|
+
}
|
|
6090
|
+
}
|
|
6091
|
+
catch (e) {
|
|
6092
|
+
// Target class may not be available yet
|
|
6093
|
+
}
|
|
6094
|
+
}
|
|
5765
6095
|
shape.addProperty(relShape);
|
|
5766
6096
|
}
|
|
5767
6097
|
// Always set constructor and destructor actions on the shape, even
|
|
@@ -5922,10 +6252,36 @@ function ReadOnly(opts) {
|
|
|
5922
6252
|
*/
|
|
5923
6253
|
function resolveRelationArgs(first, second) {
|
|
5924
6254
|
const opts = typeof first === 'function'
|
|
5925
|
-
? { ...second, target: first }
|
|
6255
|
+
? { ...(second || {}), target: first }
|
|
5926
6256
|
: first;
|
|
6257
|
+
// getter is mutually exclusive with through, target, and where
|
|
6258
|
+
if (opts.getter) {
|
|
6259
|
+
if (opts.through) {
|
|
6260
|
+
throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
|
|
6261
|
+
'Use `getter` alone for custom read-only relations, or `through` ' +
|
|
6262
|
+
'(with optional `target`) for standard link-based relations.');
|
|
6263
|
+
}
|
|
6264
|
+
if (opts.target) {
|
|
6265
|
+
throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +
|
|
6266
|
+
'`target` auto-generates a conformance getter from the model shape; ' +
|
|
6267
|
+
'providing both is contradictory.');
|
|
6268
|
+
}
|
|
6269
|
+
if (opts.where) {
|
|
6270
|
+
throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
|
|
6271
|
+
'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.');
|
|
6272
|
+
}
|
|
6273
|
+
return opts;
|
|
6274
|
+
}
|
|
6275
|
+
// Default predicate when not provided
|
|
5927
6276
|
if (!opts.through) {
|
|
5928
|
-
|
|
6277
|
+
opts.through = 'ad4m://has_child';
|
|
6278
|
+
}
|
|
6279
|
+
// where validation
|
|
6280
|
+
if (opts.where) {
|
|
6281
|
+
if (opts.filter === false) {
|
|
6282
|
+
throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
|
|
6283
|
+
'`where` adds filtering constraints; `filter: false` disables filtering.');
|
|
6284
|
+
}
|
|
5929
6285
|
}
|
|
5930
6286
|
return opts;
|
|
5931
6287
|
}
|
|
@@ -5943,18 +6299,23 @@ function HasMany(first, second) {
|
|
|
5943
6299
|
kind: 'hasMany',
|
|
5944
6300
|
local: opts.local,
|
|
5945
6301
|
...(opts.getter && { getter: opts.getter }),
|
|
6302
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6303
|
+
...(opts.where && { where: opts.where }),
|
|
5946
6304
|
};
|
|
5947
|
-
// Add prototype methods for add/remove/set
|
|
5948
6305
|
const relKey = key;
|
|
5949
|
-
|
|
5950
|
-
|
|
5951
|
-
|
|
5952
|
-
|
|
5953
|
-
|
|
5954
|
-
|
|
5955
|
-
|
|
5956
|
-
|
|
5957
|
-
|
|
6306
|
+
// Only add mutation methods when a predicate is available
|
|
6307
|
+
// (getter-only relations are read-only)
|
|
6308
|
+
if (opts.through) {
|
|
6309
|
+
target[`add${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6310
|
+
return this.addRelationValue(relKey, arg, batchId);
|
|
6311
|
+
};
|
|
6312
|
+
target[`remove${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6313
|
+
return this.removeRelationValue(relKey, arg, batchId);
|
|
6314
|
+
};
|
|
6315
|
+
target[`set${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6316
|
+
return this.setRelationValues(relKey, arg, batchId);
|
|
6317
|
+
};
|
|
6318
|
+
}
|
|
5958
6319
|
Object.defineProperty(target, relKey, { configurable: true, writable: true });
|
|
5959
6320
|
};
|
|
5960
6321
|
}
|
|
@@ -5971,24 +6332,31 @@ function HasOne(first, second) {
|
|
|
5971
6332
|
kind: 'hasOne',
|
|
5972
6333
|
maxCount: 1,
|
|
5973
6334
|
local: opts.local,
|
|
6335
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6336
|
+
...(opts.where && { where: opts.where }),
|
|
5974
6337
|
};
|
|
5975
|
-
// Register as a writable property
|
|
5976
|
-
applyPropertyMetadata({
|
|
5977
|
-
through: opts.through,
|
|
5978
|
-
readOnly: false,
|
|
5979
|
-
local: opts.local,
|
|
5980
|
-
})(target, key);
|
|
5981
|
-
// Add prototype methods for add/remove/set (mirroring @HasMany)
|
|
5982
6338
|
const relKey = key;
|
|
5983
|
-
|
|
5984
|
-
|
|
5985
|
-
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
6339
|
+
if (opts.through) {
|
|
6340
|
+
// Register as a writable property
|
|
6341
|
+
applyPropertyMetadata({
|
|
6342
|
+
through: opts.through,
|
|
6343
|
+
readOnly: false,
|
|
6344
|
+
local: opts.local,
|
|
6345
|
+
})(target, key);
|
|
6346
|
+
// Add prototype methods for add/remove/set (mirroring @HasMany)
|
|
6347
|
+
target[`add${capitalize$1(relKey)}`] = async function (arg) {
|
|
6348
|
+
return this.addRelationValue(relKey, arg);
|
|
6349
|
+
};
|
|
6350
|
+
target[`remove${capitalize$1(relKey)}`] = async function (arg) {
|
|
6351
|
+
return this.removeRelationValue(relKey, arg);
|
|
6352
|
+
};
|
|
6353
|
+
target[`set${capitalize$1(relKey)}`] = async function (arg) {
|
|
6354
|
+
return this.setRelationValues(relKey, arg);
|
|
6355
|
+
};
|
|
6356
|
+
}
|
|
6357
|
+
else {
|
|
6358
|
+
Object.defineProperty(target, relKey, { configurable: true, writable: true });
|
|
6359
|
+
}
|
|
5992
6360
|
};
|
|
5993
6361
|
}
|
|
5994
6362
|
function BelongsToOne(first, second) {
|
|
@@ -6004,13 +6372,20 @@ function BelongsToOne(first, second) {
|
|
|
6004
6372
|
kind: 'belongsToOne',
|
|
6005
6373
|
maxCount: 1,
|
|
6006
6374
|
local: opts.local,
|
|
6375
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6376
|
+
...(opts.where && { where: opts.where }),
|
|
6007
6377
|
};
|
|
6008
|
-
|
|
6009
|
-
|
|
6010
|
-
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
|
|
6378
|
+
if (opts.through) {
|
|
6379
|
+
// Read-only property (the owning side manages the link)
|
|
6380
|
+
applyPropertyMetadata({
|
|
6381
|
+
through: opts.through,
|
|
6382
|
+
readOnly: true,
|
|
6383
|
+
local: opts.local,
|
|
6384
|
+
})(target, key);
|
|
6385
|
+
}
|
|
6386
|
+
else {
|
|
6387
|
+
Object.defineProperty(target, key, { configurable: true, writable: true });
|
|
6388
|
+
}
|
|
6014
6389
|
};
|
|
6015
6390
|
}
|
|
6016
6391
|
function BelongsToMany(first, second) {
|
|
@@ -6026,6 +6401,8 @@ function BelongsToMany(first, second) {
|
|
|
6026
6401
|
kind: 'belongsToMany',
|
|
6027
6402
|
local: opts.local,
|
|
6028
6403
|
...(opts.getter && { getter: opts.getter }),
|
|
6404
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6405
|
+
...(opts.where && { where: opts.where }),
|
|
6029
6406
|
};
|
|
6030
6407
|
// @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
|
|
6031
6408
|
// prototype methods. Mutation must go through the owning side's @HasMany decorator.
|
|
@@ -6034,58 +6411,6 @@ function BelongsToMany(first, second) {
|
|
|
6034
6411
|
};
|
|
6035
6412
|
}
|
|
6036
6413
|
|
|
6037
|
-
function formatList(list) {
|
|
6038
|
-
if (!list?.length) {
|
|
6039
|
-
return "";
|
|
6040
|
-
}
|
|
6041
|
-
if (list.length === 1) {
|
|
6042
|
-
return list.toString();
|
|
6043
|
-
}
|
|
6044
|
-
if (list.length === 2) {
|
|
6045
|
-
return list.join(' and ');
|
|
6046
|
-
}
|
|
6047
|
-
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
6048
|
-
}
|
|
6049
|
-
function capSentence(cap) {
|
|
6050
|
-
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
6051
|
-
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
6052
|
-
const pointers = cap.with.pointers.includes("*")
|
|
6053
|
-
? ["all AD4M data"]
|
|
6054
|
-
: cap.with.pointers;
|
|
6055
|
-
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
6056
|
-
}
|
|
6057
|
-
/**
|
|
6058
|
-
* Escapes a string value for safe use in SurrealQL queries.
|
|
6059
|
-
*
|
|
6060
|
-
* @description
|
|
6061
|
-
* Prevents SQL injection by properly escaping special characters in string values
|
|
6062
|
-
* that will be interpolated into SurrealQL queries. This handles the most common
|
|
6063
|
-
* special characters that could break SQL queries or enable injection attacks.
|
|
6064
|
-
*
|
|
6065
|
-
* Single quotes, backslashes, and other special characters are escaped using
|
|
6066
|
-
* backslash notation, which is the standard escaping mechanism for SurrealQL.
|
|
6067
|
-
*
|
|
6068
|
-
* @param value - The string value to escape
|
|
6069
|
-
* @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
|
|
6070
|
-
*
|
|
6071
|
-
* @example
|
|
6072
|
-
* ```typescript
|
|
6073
|
-
* const userInput = "user's input with 'quotes'";
|
|
6074
|
-
* const escaped = escapeSurrealString(userInput);
|
|
6075
|
-
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
6076
|
-
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
6077
|
-
* ```
|
|
6078
|
-
*/
|
|
6079
|
-
function escapeSurrealString(value) {
|
|
6080
|
-
return value
|
|
6081
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
6082
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
6083
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
6084
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
6085
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
6086
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
6087
|
-
}
|
|
6088
|
-
|
|
6089
6414
|
/**
|
|
6090
6415
|
* SHACL Flow - represents a state machine for AD4M expressions
|
|
6091
6416
|
*
|
|
@@ -20440,6 +20765,9 @@ class Ad4mModel {
|
|
|
20440
20765
|
...(options.local !== undefined && { local: options.local }),
|
|
20441
20766
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
20442
20767
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
20768
|
+
...(options.target !== undefined && { target: options.target }),
|
|
20769
|
+
...(options.filter !== undefined && { filter: options.filter }),
|
|
20770
|
+
...(options.where !== undefined && { where: options.where }),
|
|
20443
20771
|
};
|
|
20444
20772
|
}
|
|
20445
20773
|
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
@@ -20703,11 +21031,29 @@ class Ad4mModel {
|
|
|
20703
21031
|
predToProperty.set(propMeta.predicate, [propName, propMeta]);
|
|
20704
21032
|
}
|
|
20705
21033
|
const predToRelation = new Map();
|
|
21034
|
+
// Two-pass approach: first add all non-getter, non-target-filtered relations,
|
|
21035
|
+
// then try to add target+filter relations only if their predicate isn't
|
|
21036
|
+
// already claimed. This prevents predicate collisions (e.g. entries +
|
|
21037
|
+
// messages sharing the same predicate) while still populating unique-
|
|
21038
|
+
// predicate relations normally via link hydration.
|
|
21039
|
+
const deferredTargetRelations = [];
|
|
20706
21040
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
20707
21041
|
if (relMeta.getter)
|
|
21042
|
+
continue; // Handled via explicit custom getter evaluation
|
|
21043
|
+
if (relMeta.target && relMeta.filter !== false) {
|
|
21044
|
+
deferredTargetRelations.push([relName, relMeta]);
|
|
20708
21045
|
continue;
|
|
21046
|
+
}
|
|
20709
21047
|
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
20710
21048
|
}
|
|
21049
|
+
// Second pass: add deferred target+filter relations only if their predicate
|
|
21050
|
+
// is not already claimed by a base relation. When a collision exists, the
|
|
21051
|
+
// conformance getter will handle the filtered view instead.
|
|
21052
|
+
for (const [relName, relMeta] of deferredTargetRelations) {
|
|
21053
|
+
if (!predToRelation.has(relMeta.predicate)) {
|
|
21054
|
+
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
21055
|
+
}
|
|
21056
|
+
}
|
|
20711
21057
|
// Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
|
|
20712
21058
|
const propertyLatest = new Map();
|
|
20713
21059
|
// Per-relation accumulator: ordered targets with metadata for sorting
|
|
@@ -21025,7 +21371,10 @@ class Ad4mModel {
|
|
|
21025
21371
|
}
|
|
21026
21372
|
}
|
|
21027
21373
|
// Evaluate SurrealQL getters
|
|
21028
|
-
|
|
21374
|
+
const getterOpts = opts?.properties || opts?.include
|
|
21375
|
+
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
21376
|
+
: undefined;
|
|
21377
|
+
await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
21029
21378
|
// Eager-load relations if requested
|
|
21030
21379
|
if (opts?.include) {
|
|
21031
21380
|
await ctor.hydrateRelations([this], this._perspective, opts.include);
|
|
@@ -21062,14 +21411,49 @@ class Ad4mModel {
|
|
|
21062
21411
|
`;
|
|
21063
21412
|
return fullQuery;
|
|
21064
21413
|
}
|
|
21414
|
+
/**
|
|
21415
|
+
* Builds a SurrealQL conformance getter for a relation whose `target` model
|
|
21416
|
+
* is known but no explicit `getter` string was supplied.
|
|
21417
|
+
*
|
|
21418
|
+
* The generated getter traverses outgoing links matching the relation's
|
|
21419
|
+
* predicate and then filters the target nodes to only those that conform to
|
|
21420
|
+
* the target model's shape (required properties / flags).
|
|
21421
|
+
*
|
|
21422
|
+
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
21423
|
+
* so the same logic is used at shape-definition time and at query time.
|
|
21424
|
+
*
|
|
21425
|
+
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
21426
|
+
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
21427
|
+
* @returns A SurrealQL expression string, or `undefined` if no conformance
|
|
21428
|
+
* conditions could be derived from the target model.
|
|
21429
|
+
* @private
|
|
21430
|
+
*/
|
|
21431
|
+
static buildConformanceGetter(relationPredicate, targetClass) {
|
|
21432
|
+
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
21433
|
+
if (!filter) {
|
|
21434
|
+
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
21435
|
+
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
21436
|
+
return undefined;
|
|
21437
|
+
}
|
|
21438
|
+
return filter.getter;
|
|
21439
|
+
}
|
|
21065
21440
|
/**
|
|
21066
21441
|
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
21442
|
+
*
|
|
21443
|
+
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
21444
|
+
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
21067
21445
|
* @private
|
|
21068
21446
|
*/
|
|
21069
|
-
static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
|
|
21447
|
+
static async evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
21070
21448
|
const safeBaseExpression = this.formatSurrealValue(instance.id);
|
|
21449
|
+
// Build projection filter — when requestedProperties is active, only
|
|
21450
|
+
// evaluate getters for fields that are requested (or included).
|
|
21451
|
+
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
21452
|
+
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
21071
21453
|
// Evaluate property getters
|
|
21072
21454
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
21455
|
+
if (projectionSet && !projectionSet.has(propName))
|
|
21456
|
+
continue;
|
|
21073
21457
|
if (propMeta.getter) {
|
|
21074
21458
|
try {
|
|
21075
21459
|
// Replace 'Base' placeholder with actual base expression
|
|
@@ -21085,14 +21469,56 @@ class Ad4mModel {
|
|
|
21085
21469
|
}
|
|
21086
21470
|
}
|
|
21087
21471
|
}
|
|
21088
|
-
// Evaluate relation getters
|
|
21472
|
+
// Evaluate relation getters (explicit or auto-generated from target)
|
|
21089
21473
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
21090
|
-
|
|
21474
|
+
// Skip relations excluded by property projection (unless in include map)
|
|
21475
|
+
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
|
|
21476
|
+
continue;
|
|
21477
|
+
const meta = relMeta;
|
|
21478
|
+
// Determine the getter to execute:
|
|
21479
|
+
// 1. Explicit `getter` always wins
|
|
21480
|
+
// 2. `where` clause → compile DSL to SurrealQL getter
|
|
21481
|
+
// 3. If `target` is set and `filter !== false`, auto-generate from target metadata
|
|
21482
|
+
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
21483
|
+
// because buildConformanceGetter traverses outgoing links (->link) which is
|
|
21484
|
+
// wrong for reverse relations. Their values are already populated by the
|
|
21485
|
+
// reverse link lookup in instancesFromSurrealResult / getData.
|
|
21486
|
+
let getter = meta.getter;
|
|
21487
|
+
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
21488
|
+
try {
|
|
21489
|
+
const TargetClass = meta.target?.();
|
|
21490
|
+
const targetMetadata = TargetClass
|
|
21491
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
21492
|
+
: null;
|
|
21493
|
+
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
21494
|
+
if (conditions.length > 0) {
|
|
21495
|
+
const escapedPred = escapeSurrealString(meta.predicate);
|
|
21496
|
+
getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
|
|
21497
|
+
}
|
|
21498
|
+
}
|
|
21499
|
+
catch (e) {
|
|
21500
|
+
// Target metadata may not be available yet
|
|
21501
|
+
}
|
|
21502
|
+
}
|
|
21503
|
+
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
21504
|
+
try {
|
|
21505
|
+
const TargetClass = meta.target();
|
|
21506
|
+
getter = this.buildConformanceGetter(meta.predicate, TargetClass);
|
|
21507
|
+
if (!getter) {
|
|
21508
|
+
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
21509
|
+
}
|
|
21510
|
+
}
|
|
21511
|
+
catch (e) {
|
|
21512
|
+
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
21513
|
+
}
|
|
21514
|
+
}
|
|
21515
|
+
if (getter) {
|
|
21091
21516
|
try {
|
|
21092
21517
|
// Replace 'Base' placeholder with actual base expression
|
|
21093
|
-
const query =
|
|
21518
|
+
const query = getter.replace(/Base/g, safeBaseExpression);
|
|
21519
|
+
const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
|
|
21094
21520
|
// Query from node table to have graph traversal context
|
|
21095
|
-
const result = await perspective.querySurrealDB(
|
|
21521
|
+
const result = await perspective.querySurrealDB(fullQuery);
|
|
21096
21522
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
|
|
21097
21523
|
// Filter out 'None' from relation results
|
|
21098
21524
|
const value = result[0].value;
|
|
@@ -21872,26 +22298,7 @@ FETCH links
|
|
|
21872
22298
|
* @private
|
|
21873
22299
|
*/
|
|
21874
22300
|
static formatSurrealValue(value) {
|
|
21875
|
-
|
|
21876
|
-
// Escape backslashes first, then single quotes and other special characters
|
|
21877
|
-
const escaped = value
|
|
21878
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
21879
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
21880
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
21881
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
21882
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
21883
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
21884
|
-
return `'${escaped}'`;
|
|
21885
|
-
}
|
|
21886
|
-
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
21887
|
-
return String(value);
|
|
21888
|
-
}
|
|
21889
|
-
else if (Array.isArray(value)) {
|
|
21890
|
-
return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
|
|
21891
|
-
}
|
|
21892
|
-
else {
|
|
21893
|
-
return String(value);
|
|
21894
|
-
}
|
|
22301
|
+
return formatSurrealValue(value);
|
|
21895
22302
|
}
|
|
21896
22303
|
static async instancesFromPrologResult(perspective, query, result) {
|
|
21897
22304
|
if (!result?.[0]?.AllInstances)
|
|
@@ -22019,8 +22426,11 @@ FETCH links
|
|
|
22019
22426
|
}));
|
|
22020
22427
|
}
|
|
22021
22428
|
// Evaluate custom getters for all instances (single pass)
|
|
22429
|
+
const getterOpts = requestedProperties.length > 0 || query.include
|
|
22430
|
+
? { requestedProperties, include: query.include }
|
|
22431
|
+
: undefined;
|
|
22022
22432
|
for (const instance of instances) {
|
|
22023
|
-
await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
22433
|
+
await this.evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
22024
22434
|
}
|
|
22025
22435
|
// Filter by where conditions that couldn't be filtered in SQL
|
|
22026
22436
|
// This includes:
|
|
@@ -22616,6 +23026,22 @@ FETCH links
|
|
|
22616
23026
|
// Skip unchanged fields when a snapshot is available
|
|
22617
23027
|
if (dirty && !dirty.has(key))
|
|
22618
23028
|
continue;
|
|
23029
|
+
// Skip read-only computed relations — explicit getters never write links.
|
|
23030
|
+
// For target+filter relations, skip only when another relation on this
|
|
23031
|
+
// model claims the same predicate (i.e., this is a filtered *view* of a
|
|
23032
|
+
// base relation and writing would collide).
|
|
23033
|
+
const relMeta = metadata.relations[key];
|
|
23034
|
+
if (relMeta) {
|
|
23035
|
+
if (relMeta.getter)
|
|
23036
|
+
continue;
|
|
23037
|
+
if (relMeta.target && relMeta.filter !== false) {
|
|
23038
|
+
// Check for predicate collision with a sibling relation
|
|
23039
|
+
const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&
|
|
23040
|
+
otherMeta.predicate === relMeta.predicate);
|
|
23041
|
+
if (hasCollision)
|
|
23042
|
+
continue;
|
|
23043
|
+
}
|
|
23044
|
+
}
|
|
22619
23045
|
if (value !== undefined && value !== null) {
|
|
22620
23046
|
if (value?.action) {
|
|
22621
23047
|
switch (value.action) {
|
|
@@ -22712,11 +23138,6 @@ FETCH links
|
|
|
22712
23138
|
* ```
|
|
22713
23139
|
*/
|
|
22714
23140
|
async delete(batchId) {
|
|
22715
|
-
// Check if the model has a destructor (required properties, flags, or
|
|
22716
|
-
// properties with initial values). Models whose properties are all
|
|
22717
|
-
// optional, have no @Flag, and have no initial values produce an empty
|
|
22718
|
-
// SHACL destructor, so calling removeSubject would fail. In that case
|
|
22719
|
-
// we skip the destructor and just remove all outgoing links directly.
|
|
22720
23141
|
const metadata = this.constructor.getModelMetadata();
|
|
22721
23142
|
const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
|
|
22722
23143
|
if (hasDestructor) {
|
|
@@ -22724,18 +23145,39 @@ FETCH links
|
|
|
22724
23145
|
await this._perspective.removeSubject(this, this._baseExpression, batchId);
|
|
22725
23146
|
}
|
|
22726
23147
|
else {
|
|
22727
|
-
// No destructor
|
|
23148
|
+
// No destructor (all-optional model).
|
|
23149
|
+
// SAFETY: We must NOT remove all outgoing links because another model
|
|
23150
|
+
// class may be instantiated on the same base expression. Removing
|
|
23151
|
+
// everything would silently destroy that other instance's data — and
|
|
23152
|
+
// if that instance has a destructor, it can no longer be called
|
|
23153
|
+
// cleanly, leaving link debris.
|
|
23154
|
+
//
|
|
23155
|
+
// Instead we only remove outgoing links whose predicate is declared
|
|
23156
|
+
// by THIS model's schema (properties + relations).
|
|
22728
23157
|
try {
|
|
23158
|
+
const knownPredicates = new Set();
|
|
23159
|
+
for (const p of Object.values(metadata.properties)) {
|
|
23160
|
+
if (p.predicate)
|
|
23161
|
+
knownPredicates.add(p.predicate);
|
|
23162
|
+
}
|
|
23163
|
+
for (const r of Object.values(metadata.relations)) {
|
|
23164
|
+
if (r.predicate)
|
|
23165
|
+
knownPredicates.add(r.predicate);
|
|
23166
|
+
}
|
|
22729
23167
|
const outgoingLinks = await this._perspective.get(new LinkQuery({ source: this._baseExpression }));
|
|
22730
|
-
|
|
22731
|
-
|
|
23168
|
+
const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));
|
|
23169
|
+
if (ownLinks.length > 0) {
|
|
23170
|
+
await this._perspective.removeLinks(ownLinks, batchId);
|
|
22732
23171
|
}
|
|
22733
23172
|
}
|
|
22734
23173
|
catch (e) {
|
|
22735
23174
|
console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
|
|
22736
23175
|
}
|
|
22737
23176
|
}
|
|
22738
|
-
// Clean up incoming links — remove any links that point **to** this instance
|
|
23177
|
+
// Clean up incoming links — remove any links that point **to** this instance.
|
|
23178
|
+
// Unlike outgoing links (scoped above), incoming links originate from OTHER
|
|
23179
|
+
// nodes. Removing them doesn't damage sibling models on this node; it
|
|
23180
|
+
// prevents dangling references elsewhere (e.g. a parent's has_child link).
|
|
22739
23181
|
try {
|
|
22740
23182
|
const incomingLinks = await this._perspective.get(new LinkQuery({ target: this._baseExpression }));
|
|
22741
23183
|
if (incomingLinks.length > 0) {
|
|
@@ -23930,4 +24372,4 @@ function generatePrologFacts(ModelClass) {
|
|
|
23930
24372
|
return lines.join("\n");
|
|
23931
24373
|
}
|
|
23932
24374
|
|
|
23933
|
-
export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, capSentence, escapeSurrealString, exprRef2String, formatList, generatePrologFacts, getPropertiesMetadata, getRelationsMetadata, hasLink, instanceToSerializable, isExpression, isLink, linkEqual, makeRandomId, parseExprUrl, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
|
|
24375
|
+
export { AIClient, AIModelLoadingStatus, AIPromptExamples, AIPromptExamplesInput, AITask, AITaskInput, Ad4mClient, Ad4mModel, Agent, AgentClient, AgentExpression, AgentSignature, AgentStatus, Apps, AuthInfo, AuthInfoInput, BelongsToMany, BelongsToOne, Capability, CapabilityInput, Dna, EntanglementProof, EntanglementProofInput, ExceptionInfo, ExceptionType, Expression, ExpressionGeneric, ExpressionGenericInput, ExpressionProof, ExpressionProofInput, ExpressionRef, ExpressionRendered, Flag, HasMany, HasOne, Icon, ImportResult, ImportStats, InteractionCall, InteractionMeta, InteractionParameter, LanguageExpression, LanguageHandle, LanguageLanguageInput, LanguageMeta, LanguageMetaInput, LanguageMetaInternal, LanguageRef, Link, LinkExpression, LinkExpressionInput, LinkExpressionMutations, LinkExpressionUpdated, LinkInput, LinkMutations, LinkQuery, Literal, Model, ModelQueryBuilder, Neighbourhood, NeighbourhoodExpression, NeighbourhoodProxy, Notification, NotificationInput, OnlineAgent, Optional, Perspective, PerspectiveAction, PerspectiveDiff, PerspectiveDiffExpression, PerspectiveExpression, PerspectiveHandle, PerspectiveInput, PerspectiveProxy, PerspectiveState, PerspectiveUnsignedInput, Property, QuerySubscriptionProxy, ReadOnly, Resource, ResourceInput, RuntimeInfo, SHACLFlow, SHACLShape, SMART_LITERAL_CONTENT_PREDICATE, SentMessage, SmartLiteral, Subject, TriggeredNotification, UserCreationResult, UserStatistics, VerificationRequestResult, addLink, buildConformanceFilter, capSentence, escapeSurrealString, exprRef2String, formatList, generatePrologFacts, getPropertiesMetadata, getRelationsMetadata, hasLink, instanceToSerializable, isExpression, isLink, linkEqual, makeRandomId, parseExprUrl, setPropertyRegistryEntry, setRelationRegistryEntry, typeDefsString };
|