@coasys/ad4m 0.12.0-rc1-dev.3 → 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 +588 -122
- package/lib/index.js +588 -123
- package/lib/src/model/Ad4mModel.d.ts +33 -3
- package/lib/src/model/Ad4mModel.js +178 -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 +202 -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.cjs
CHANGED
|
@@ -4936,6 +4936,27 @@ class SHACLShape {
|
|
|
4936
4936
|
target: `literal://string:${JSON.stringify(prop.remover)}`
|
|
4937
4937
|
});
|
|
4938
4938
|
}
|
|
4939
|
+
if (prop.getter) {
|
|
4940
|
+
links.push({
|
|
4941
|
+
source: propShapeId,
|
|
4942
|
+
predicate: "ad4m://getter",
|
|
4943
|
+
target: `literal://string:${prop.getter}`
|
|
4944
|
+
});
|
|
4945
|
+
}
|
|
4946
|
+
if (prop.conformanceConditions && prop.conformanceConditions.length > 0) {
|
|
4947
|
+
links.push({
|
|
4948
|
+
source: propShapeId,
|
|
4949
|
+
predicate: "ad4m://conformanceConditions",
|
|
4950
|
+
target: `literal://string:${JSON.stringify(prop.conformanceConditions)}`
|
|
4951
|
+
});
|
|
4952
|
+
}
|
|
4953
|
+
if (prop.class) {
|
|
4954
|
+
links.push({
|
|
4955
|
+
source: propShapeId,
|
|
4956
|
+
predicate: "sh://class",
|
|
4957
|
+
target: prop.class
|
|
4958
|
+
});
|
|
4959
|
+
}
|
|
4939
4960
|
}
|
|
4940
4961
|
return links;
|
|
4941
4962
|
}
|
|
@@ -5089,6 +5110,24 @@ class SHACLShape {
|
|
|
5089
5110
|
// Ignore parse errors
|
|
5090
5111
|
}
|
|
5091
5112
|
}
|
|
5113
|
+
const getterLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://getter");
|
|
5114
|
+
if (getterLink) {
|
|
5115
|
+
prop.getter = getterLink.target.replace('literal://string:', '');
|
|
5116
|
+
}
|
|
5117
|
+
const conditionsLink = links.find(l => l.source === propShapeId && l.predicate === "ad4m://conformanceConditions");
|
|
5118
|
+
if (conditionsLink) {
|
|
5119
|
+
try {
|
|
5120
|
+
const jsonStr = conditionsLink.target.replace('literal://string:', '');
|
|
5121
|
+
prop.conformanceConditions = JSON.parse(jsonStr);
|
|
5122
|
+
}
|
|
5123
|
+
catch (e) {
|
|
5124
|
+
// Ignore parse errors
|
|
5125
|
+
}
|
|
5126
|
+
}
|
|
5127
|
+
const classLink = links.find(l => l.source === propShapeId && l.predicate === "sh://class");
|
|
5128
|
+
if (classLink) {
|
|
5129
|
+
prop.class = classLink.target;
|
|
5130
|
+
}
|
|
5092
5131
|
shape.addProperty(prop);
|
|
5093
5132
|
}
|
|
5094
5133
|
return shape;
|
|
@@ -5121,6 +5160,9 @@ class SHACLShape {
|
|
|
5121
5160
|
setter: p.setter,
|
|
5122
5161
|
adder: p.adder,
|
|
5123
5162
|
remover: p.remover,
|
|
5163
|
+
getter: p.getter,
|
|
5164
|
+
conformance_conditions: p.conformanceConditions,
|
|
5165
|
+
class: p.class,
|
|
5124
5166
|
})),
|
|
5125
5167
|
constructor_actions: this.constructor_actions,
|
|
5126
5168
|
destructor_actions: this.destructor_actions,
|
|
@@ -5151,6 +5193,9 @@ class SHACLShape {
|
|
|
5151
5193
|
setter: p.setter,
|
|
5152
5194
|
adder: p.adder,
|
|
5153
5195
|
remover: p.remover,
|
|
5196
|
+
getter: p.getter,
|
|
5197
|
+
conformanceConditions: p.conformance_conditions,
|
|
5198
|
+
class: p.class,
|
|
5154
5199
|
});
|
|
5155
5200
|
}
|
|
5156
5201
|
if (json.constructor_actions) {
|
|
@@ -5168,6 +5213,186 @@ class SHACLShape {
|
|
|
5168
5213
|
}
|
|
5169
5214
|
}
|
|
5170
5215
|
|
|
5216
|
+
function formatList(list) {
|
|
5217
|
+
if (!list?.length) {
|
|
5218
|
+
return "";
|
|
5219
|
+
}
|
|
5220
|
+
if (list.length === 1) {
|
|
5221
|
+
return list.toString();
|
|
5222
|
+
}
|
|
5223
|
+
if (list.length === 2) {
|
|
5224
|
+
return list.join(' and ');
|
|
5225
|
+
}
|
|
5226
|
+
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
5227
|
+
}
|
|
5228
|
+
function capSentence(cap) {
|
|
5229
|
+
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
5230
|
+
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
5231
|
+
const pointers = cap.with.pointers.includes("*")
|
|
5232
|
+
? ["all AD4M data"]
|
|
5233
|
+
: cap.with.pointers;
|
|
5234
|
+
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
5235
|
+
}
|
|
5236
|
+
/**
|
|
5237
|
+
* Escapes a string value for safe use in SurrealQL queries.
|
|
5238
|
+
*
|
|
5239
|
+
* @description
|
|
5240
|
+
* Prevents SQL injection by properly escaping special characters in string values
|
|
5241
|
+
* that will be interpolated into SurrealQL queries. This handles the most common
|
|
5242
|
+
* special characters that could break SQL queries or enable injection attacks.
|
|
5243
|
+
*
|
|
5244
|
+
* Single quotes, backslashes, and other special characters are escaped using
|
|
5245
|
+
* backslash notation, which is the standard escaping mechanism for SurrealQL.
|
|
5246
|
+
*
|
|
5247
|
+
* @param value - The string value to escape
|
|
5248
|
+
* @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
|
|
5249
|
+
*
|
|
5250
|
+
* @example
|
|
5251
|
+
* ```typescript
|
|
5252
|
+
* const userInput = "user's input with 'quotes'";
|
|
5253
|
+
* const escaped = escapeSurrealString(userInput);
|
|
5254
|
+
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
5255
|
+
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
5256
|
+
* ```
|
|
5257
|
+
*/
|
|
5258
|
+
function escapeSurrealString(value) {
|
|
5259
|
+
return value
|
|
5260
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
5261
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
5262
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
5263
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
5264
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
5265
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
5266
|
+
}
|
|
5267
|
+
|
|
5268
|
+
/**
|
|
5269
|
+
* Shared SurrealQL compilation utilities.
|
|
5270
|
+
*
|
|
5271
|
+
* These functions are used by both the runtime query builder (`Ad4mModel`) and
|
|
5272
|
+
* the compile-time SHACL generator (`decorators.ts`).
|
|
5273
|
+
*/
|
|
5274
|
+
/**
|
|
5275
|
+
* Format a JavaScript value for embedding in a SurrealQL expression.
|
|
5276
|
+
*
|
|
5277
|
+
* - Strings are single-quoted with backslash / quote / newline escaping
|
|
5278
|
+
* - Numbers and booleans are passed through as-is
|
|
5279
|
+
* - Arrays are recursed
|
|
5280
|
+
*/
|
|
5281
|
+
function formatSurrealValue(value) {
|
|
5282
|
+
if (typeof value === 'string') {
|
|
5283
|
+
// Escape backslashes first, then single quotes and other special characters
|
|
5284
|
+
const escaped = value
|
|
5285
|
+
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
5286
|
+
.replace(/'/g, "\\'") // Single quote -> \'
|
|
5287
|
+
.replace(/"/g, '\\"') // Double quote -> \"
|
|
5288
|
+
.replace(/\n/g, '\\n') // Newline -> \n
|
|
5289
|
+
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
5290
|
+
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
5291
|
+
return `'${escaped}'`;
|
|
5292
|
+
}
|
|
5293
|
+
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
5294
|
+
return String(value);
|
|
5295
|
+
}
|
|
5296
|
+
else if (Array.isArray(value)) {
|
|
5297
|
+
return `[${value.map(v => formatSurrealValue(v)).join(', ')}]`;
|
|
5298
|
+
}
|
|
5299
|
+
else {
|
|
5300
|
+
return String(value);
|
|
5301
|
+
}
|
|
5302
|
+
}
|
|
5303
|
+
/**
|
|
5304
|
+
* Compile a single Where condition for a property into a SurrealQL
|
|
5305
|
+
* graph-traversal sub-expression.
|
|
5306
|
+
*
|
|
5307
|
+
* Operates on the **target node** — generates `count(->link[WHERE ...]) > 0`
|
|
5308
|
+
* style checks that can be used inside a `[WHERE ...]` filter on nodes.
|
|
5309
|
+
*
|
|
5310
|
+
* @param predicate - The predicate URI for the property
|
|
5311
|
+
* @param condition - The Where condition value
|
|
5312
|
+
* @param opts - Optional settings (e.g. `resolveLanguage`)
|
|
5313
|
+
* @returns A single SurrealQL condition string
|
|
5314
|
+
*/
|
|
5315
|
+
function buildWhereCondition(predicate, condition, opts) {
|
|
5316
|
+
const escapedPredicate = escapeSurrealString(predicate);
|
|
5317
|
+
const targetField = opts?.resolveLanguage === 'literal'
|
|
5318
|
+
? 'fn::parse_literal(out.uri)'
|
|
5319
|
+
: 'out.uri';
|
|
5320
|
+
if (Array.isArray(condition)) {
|
|
5321
|
+
// Array values → IN clause
|
|
5322
|
+
const formattedValues = condition.map(v => formatSurrealValue(v)).join(', ');
|
|
5323
|
+
return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) > 0`;
|
|
5324
|
+
}
|
|
5325
|
+
else if (typeof condition === 'object' && condition !== null) {
|
|
5326
|
+
// Operator object
|
|
5327
|
+
const ops = condition;
|
|
5328
|
+
const parts = [];
|
|
5329
|
+
if (ops.not !== undefined) {
|
|
5330
|
+
if (Array.isArray(ops.not)) {
|
|
5331
|
+
const formattedValues = ops.not.map((v) => formatSurrealValue(v)).join(', ');
|
|
5332
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} IN [${formattedValues}]]) = 0`);
|
|
5333
|
+
}
|
|
5334
|
+
else {
|
|
5335
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(ops.not)}]) = 0`);
|
|
5336
|
+
}
|
|
5337
|
+
}
|
|
5338
|
+
// Comparison operators — ensure property exists (actual comparison
|
|
5339
|
+
// may be post-filtered in JS at runtime, but the SurrealQL condition
|
|
5340
|
+
// is valid for compile-time getter generation too).
|
|
5341
|
+
const hasComparisonOps = ops.gt !== undefined || ops.gte !== undefined ||
|
|
5342
|
+
ops.lt !== undefined || ops.lte !== undefined ||
|
|
5343
|
+
ops.between !== undefined || ops.contains !== undefined;
|
|
5344
|
+
if (hasComparisonOps) {
|
|
5345
|
+
parts.push(`count(->link[WHERE predicate = '${escapedPredicate}']) > 0`);
|
|
5346
|
+
}
|
|
5347
|
+
return parts.join(' AND ');
|
|
5348
|
+
}
|
|
5349
|
+
else {
|
|
5350
|
+
// Simple equality
|
|
5351
|
+
return `count(->link[WHERE predicate = '${escapedPredicate}' AND ${targetField} = ${formatSurrealValue(condition)}]) > 0`;
|
|
5352
|
+
}
|
|
5353
|
+
}
|
|
5354
|
+
/**
|
|
5355
|
+
* Compile a full `Where` clause to an array of SurrealQL condition strings.
|
|
5356
|
+
*
|
|
5357
|
+
* When `metadata` is provided, property names are resolved to predicates
|
|
5358
|
+
* using the model's property metadata. When `metadata` is `null`, property
|
|
5359
|
+
* names are treated as raw predicate URIs.
|
|
5360
|
+
*
|
|
5361
|
+
* Only handles **regular properties** — special fields (`id`, `author`,
|
|
5362
|
+
* `timestamp`) and relation fields are skipped (they are only relevant at
|
|
5363
|
+
* runtime query time, not for compile-time getter generation).
|
|
5364
|
+
*/
|
|
5365
|
+
function compileWhereClause(where, metadata) {
|
|
5366
|
+
const conditions = [];
|
|
5367
|
+
for (const [propertyName, condition] of Object.entries(where)) {
|
|
5368
|
+
// Skip special fields that don't apply at compile time
|
|
5369
|
+
if (['id', 'author', 'timestamp'].includes(propertyName))
|
|
5370
|
+
continue;
|
|
5371
|
+
let predicate;
|
|
5372
|
+
let resolveLanguage;
|
|
5373
|
+
if (metadata) {
|
|
5374
|
+
const propMeta = metadata.properties[propertyName];
|
|
5375
|
+
if (propMeta) {
|
|
5376
|
+
predicate = propMeta.predicate;
|
|
5377
|
+
resolveLanguage = propMeta.resolveLanguage;
|
|
5378
|
+
}
|
|
5379
|
+
else {
|
|
5380
|
+
// Property not found in metadata — treat name as raw predicate URI
|
|
5381
|
+
predicate = propertyName;
|
|
5382
|
+
}
|
|
5383
|
+
}
|
|
5384
|
+
else {
|
|
5385
|
+
// No metadata — treat name as raw predicate URI
|
|
5386
|
+
predicate = propertyName;
|
|
5387
|
+
}
|
|
5388
|
+
const cond = buildWhereCondition(predicate, condition, { resolveLanguage });
|
|
5389
|
+
if (cond) {
|
|
5390
|
+
conditions.push(cond);
|
|
5391
|
+
}
|
|
5392
|
+
}
|
|
5393
|
+
return conditions;
|
|
5394
|
+
}
|
|
5395
|
+
|
|
5171
5396
|
/** Registry of property metadata keyed by constructor → { propName → metadata } */
|
|
5172
5397
|
const propertyRegistry = new WeakMap();
|
|
5173
5398
|
/** Registry of relation metadata keyed by constructor → { propName → metadata } */
|
|
@@ -5228,6 +5453,57 @@ function setRelationRegistryEntry(ctor, relName, meta) {
|
|
|
5228
5453
|
relationRegistry.set(ctor, {});
|
|
5229
5454
|
relationRegistry.get(ctor)[relName] = meta;
|
|
5230
5455
|
}
|
|
5456
|
+
/**
|
|
5457
|
+
* Build a conformance filter for a relation whose target model is known.
|
|
5458
|
+
*
|
|
5459
|
+
* Inspects the target class's property metadata to derive:
|
|
5460
|
+
* - `conformanceConditions`: Structured, DB-agnostic conditions (flag & required checks)
|
|
5461
|
+
* - `getter`: Pre-computed SurrealQL expression that traverses outgoing links and filters
|
|
5462
|
+
* target nodes to only those conforming to the target shape.
|
|
5463
|
+
*
|
|
5464
|
+
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
5465
|
+
* @param targetClass - The target model class (resolved from the target() thunk)
|
|
5466
|
+
* @returns `{ getter, conformanceConditions }` or `undefined` if no conditions could be derived
|
|
5467
|
+
*/
|
|
5468
|
+
function buildConformanceFilter(relationPredicate, targetClass) {
|
|
5469
|
+
try {
|
|
5470
|
+
const targetProps = getPropertiesMetadata(targetClass);
|
|
5471
|
+
const conditions = [];
|
|
5472
|
+
const surrealConditions = [];
|
|
5473
|
+
// 1. Flags — check predicate + value
|
|
5474
|
+
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
5475
|
+
if (propMeta.flag && propMeta.initial && propMeta.through) {
|
|
5476
|
+
conditions.push({
|
|
5477
|
+
type: 'flag',
|
|
5478
|
+
predicate: propMeta.through,
|
|
5479
|
+
value: propMeta.initial,
|
|
5480
|
+
});
|
|
5481
|
+
surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}' AND out.uri = '${escapeSurrealString(propMeta.initial)}']) > 0`);
|
|
5482
|
+
}
|
|
5483
|
+
}
|
|
5484
|
+
// 2. Required (non-flag) properties — check predicate exists
|
|
5485
|
+
// Skip properties with custom getters (they don't follow the standard link pattern)
|
|
5486
|
+
for (const [_propName, propMeta] of Object.entries(targetProps)) {
|
|
5487
|
+
if (propMeta.required && !propMeta.flag && !propMeta.getter && propMeta.through) {
|
|
5488
|
+
conditions.push({
|
|
5489
|
+
type: 'required',
|
|
5490
|
+
predicate: propMeta.through,
|
|
5491
|
+
});
|
|
5492
|
+
surrealConditions.push(`count(->link[WHERE predicate = '${escapeSurrealString(propMeta.through)}']) > 0`);
|
|
5493
|
+
}
|
|
5494
|
+
}
|
|
5495
|
+
if (conditions.length === 0) {
|
|
5496
|
+
return undefined;
|
|
5497
|
+
}
|
|
5498
|
+
const escapedPredicate = escapeSurrealString(relationPredicate);
|
|
5499
|
+
const getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${surrealConditions.join(' AND ')}].uri)`;
|
|
5500
|
+
return { getter, conformanceConditions: conditions };
|
|
5501
|
+
}
|
|
5502
|
+
catch (e) {
|
|
5503
|
+
// Target class may not have property metadata
|
|
5504
|
+
return undefined;
|
|
5505
|
+
}
|
|
5506
|
+
}
|
|
5231
5507
|
/**
|
|
5232
5508
|
* Convert a model instance to a plain serializable object.
|
|
5233
5509
|
* Reads the property metadata and extracts values from the instance.
|
|
@@ -5766,6 +6042,60 @@ function Model(opts) {
|
|
|
5766
6042
|
target: "value",
|
|
5767
6043
|
...(relMeta.local && { local: true })
|
|
5768
6044
|
}];
|
|
6045
|
+
// === Build Getter (conformance filter) ===
|
|
6046
|
+
// Priority chain:
|
|
6047
|
+
// 1. Explicit getter string → use verbatim
|
|
6048
|
+
// 2. `where` clause → compile DSL to SurrealQL getter
|
|
6049
|
+
// 3. target + filter !== false → auto-derive from shape
|
|
6050
|
+
if (relMeta.getter) {
|
|
6051
|
+
relShape.getter = relMeta.getter;
|
|
6052
|
+
}
|
|
6053
|
+
else if (relMeta.where) {
|
|
6054
|
+
// Compile Where DSL → SurrealQL getter
|
|
6055
|
+
try {
|
|
6056
|
+
const TargetClass = relMeta.target?.();
|
|
6057
|
+
const targetMetadata = TargetClass
|
|
6058
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
6059
|
+
: null;
|
|
6060
|
+
const conditions = compileWhereClause(relMeta.where, targetMetadata);
|
|
6061
|
+
if (conditions.length > 0) {
|
|
6062
|
+
const escapedPredicate = escapeSurrealString(relMeta.predicate);
|
|
6063
|
+
relShape.getter = `(->link[WHERE predicate = '${escapedPredicate}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
|
|
6064
|
+
}
|
|
6065
|
+
}
|
|
6066
|
+
catch (e) {
|
|
6067
|
+
// Target metadata may not be available yet
|
|
6068
|
+
}
|
|
6069
|
+
}
|
|
6070
|
+
else if (relMeta.target && relMeta.filter !== false) {
|
|
6071
|
+
try {
|
|
6072
|
+
const TargetClass = relMeta.target();
|
|
6073
|
+
const filter = buildConformanceFilter(relMeta.predicate, TargetClass);
|
|
6074
|
+
if (filter) {
|
|
6075
|
+
relShape.getter = filter.getter;
|
|
6076
|
+
relShape.conformanceConditions = filter.conformanceConditions;
|
|
6077
|
+
}
|
|
6078
|
+
}
|
|
6079
|
+
catch (e) {
|
|
6080
|
+
// Target class may not be available yet — getter will be
|
|
6081
|
+
// absent and runtime will fall back to unfiltered get_links
|
|
6082
|
+
}
|
|
6083
|
+
}
|
|
6084
|
+
// === sh:class — target shape reference ===
|
|
6085
|
+
// Always set when a target model is declared, regardless of filter.
|
|
6086
|
+
// This enables typed construction on the Rust/MCP side.
|
|
6087
|
+
if (relMeta.target) {
|
|
6088
|
+
try {
|
|
6089
|
+
const TargetClass = relMeta.target();
|
|
6090
|
+
const targetSHACL = TargetClass.generateSHACL?.();
|
|
6091
|
+
if (targetSHACL?.shape?.nodeShapeUri) {
|
|
6092
|
+
relShape.class = targetSHACL.shape.nodeShapeUri;
|
|
6093
|
+
}
|
|
6094
|
+
}
|
|
6095
|
+
catch (e) {
|
|
6096
|
+
// Target class may not be available yet
|
|
6097
|
+
}
|
|
6098
|
+
}
|
|
5769
6099
|
shape.addProperty(relShape);
|
|
5770
6100
|
}
|
|
5771
6101
|
// Always set constructor and destructor actions on the shape, even
|
|
@@ -5926,10 +6256,36 @@ function ReadOnly(opts) {
|
|
|
5926
6256
|
*/
|
|
5927
6257
|
function resolveRelationArgs(first, second) {
|
|
5928
6258
|
const opts = typeof first === 'function'
|
|
5929
|
-
? { ...second, target: first }
|
|
6259
|
+
? { ...(second || {}), target: first }
|
|
5930
6260
|
: first;
|
|
6261
|
+
// getter is mutually exclusive with through, target, and where
|
|
6262
|
+
if (opts.getter) {
|
|
6263
|
+
if (opts.through) {
|
|
6264
|
+
throw new Error('Relation decorator: `getter` and `through` are mutually exclusive. ' +
|
|
6265
|
+
'Use `getter` alone for custom read-only relations, or `through` ' +
|
|
6266
|
+
'(with optional `target`) for standard link-based relations.');
|
|
6267
|
+
}
|
|
6268
|
+
if (opts.target) {
|
|
6269
|
+
throw new Error('Relation decorator: `getter` and `target` are mutually exclusive. ' +
|
|
6270
|
+
'`target` auto-generates a conformance getter from the model shape; ' +
|
|
6271
|
+
'providing both is contradictory.');
|
|
6272
|
+
}
|
|
6273
|
+
if (opts.where) {
|
|
6274
|
+
throw new Error('Relation decorator: `where` and `getter` are mutually exclusive. ' +
|
|
6275
|
+
'Use `where` for DSL-based filtering, or `getter` for raw SurrealQL.');
|
|
6276
|
+
}
|
|
6277
|
+
return opts;
|
|
6278
|
+
}
|
|
6279
|
+
// Default predicate when not provided
|
|
5931
6280
|
if (!opts.through) {
|
|
5932
|
-
|
|
6281
|
+
opts.through = 'ad4m://has_child';
|
|
6282
|
+
}
|
|
6283
|
+
// where validation
|
|
6284
|
+
if (opts.where) {
|
|
6285
|
+
if (opts.filter === false) {
|
|
6286
|
+
throw new Error('Relation decorator: `where` and `filter: false` are contradictory. ' +
|
|
6287
|
+
'`where` adds filtering constraints; `filter: false` disables filtering.');
|
|
6288
|
+
}
|
|
5933
6289
|
}
|
|
5934
6290
|
return opts;
|
|
5935
6291
|
}
|
|
@@ -5947,18 +6303,23 @@ function HasMany(first, second) {
|
|
|
5947
6303
|
kind: 'hasMany',
|
|
5948
6304
|
local: opts.local,
|
|
5949
6305
|
...(opts.getter && { getter: opts.getter }),
|
|
6306
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6307
|
+
...(opts.where && { where: opts.where }),
|
|
5950
6308
|
};
|
|
5951
|
-
// Add prototype methods for add/remove/set
|
|
5952
6309
|
const relKey = key;
|
|
5953
|
-
|
|
5954
|
-
|
|
5955
|
-
|
|
5956
|
-
|
|
5957
|
-
|
|
5958
|
-
|
|
5959
|
-
|
|
5960
|
-
|
|
5961
|
-
|
|
6310
|
+
// Only add mutation methods when a predicate is available
|
|
6311
|
+
// (getter-only relations are read-only)
|
|
6312
|
+
if (opts.through) {
|
|
6313
|
+
target[`add${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6314
|
+
return this.addRelationValue(relKey, arg, batchId);
|
|
6315
|
+
};
|
|
6316
|
+
target[`remove${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6317
|
+
return this.removeRelationValue(relKey, arg, batchId);
|
|
6318
|
+
};
|
|
6319
|
+
target[`set${capitalize$1(relKey)}`] = async function (arg, batchId) {
|
|
6320
|
+
return this.setRelationValues(relKey, arg, batchId);
|
|
6321
|
+
};
|
|
6322
|
+
}
|
|
5962
6323
|
Object.defineProperty(target, relKey, { configurable: true, writable: true });
|
|
5963
6324
|
};
|
|
5964
6325
|
}
|
|
@@ -5975,24 +6336,31 @@ function HasOne(first, second) {
|
|
|
5975
6336
|
kind: 'hasOne',
|
|
5976
6337
|
maxCount: 1,
|
|
5977
6338
|
local: opts.local,
|
|
6339
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6340
|
+
...(opts.where && { where: opts.where }),
|
|
5978
6341
|
};
|
|
5979
|
-
// Register as a writable property
|
|
5980
|
-
applyPropertyMetadata({
|
|
5981
|
-
through: opts.through,
|
|
5982
|
-
readOnly: false,
|
|
5983
|
-
local: opts.local,
|
|
5984
|
-
})(target, key);
|
|
5985
|
-
// Add prototype methods for add/remove/set (mirroring @HasMany)
|
|
5986
6342
|
const relKey = key;
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
|
|
5991
|
-
|
|
5992
|
-
|
|
5993
|
-
|
|
5994
|
-
|
|
5995
|
-
|
|
6343
|
+
if (opts.through) {
|
|
6344
|
+
// Register as a writable property
|
|
6345
|
+
applyPropertyMetadata({
|
|
6346
|
+
through: opts.through,
|
|
6347
|
+
readOnly: false,
|
|
6348
|
+
local: opts.local,
|
|
6349
|
+
})(target, key);
|
|
6350
|
+
// Add prototype methods for add/remove/set (mirroring @HasMany)
|
|
6351
|
+
target[`add${capitalize$1(relKey)}`] = async function (arg) {
|
|
6352
|
+
return this.addRelationValue(relKey, arg);
|
|
6353
|
+
};
|
|
6354
|
+
target[`remove${capitalize$1(relKey)}`] = async function (arg) {
|
|
6355
|
+
return this.removeRelationValue(relKey, arg);
|
|
6356
|
+
};
|
|
6357
|
+
target[`set${capitalize$1(relKey)}`] = async function (arg) {
|
|
6358
|
+
return this.setRelationValues(relKey, arg);
|
|
6359
|
+
};
|
|
6360
|
+
}
|
|
6361
|
+
else {
|
|
6362
|
+
Object.defineProperty(target, relKey, { configurable: true, writable: true });
|
|
6363
|
+
}
|
|
5996
6364
|
};
|
|
5997
6365
|
}
|
|
5998
6366
|
function BelongsToOne(first, second) {
|
|
@@ -6008,13 +6376,20 @@ function BelongsToOne(first, second) {
|
|
|
6008
6376
|
kind: 'belongsToOne',
|
|
6009
6377
|
maxCount: 1,
|
|
6010
6378
|
local: opts.local,
|
|
6379
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6380
|
+
...(opts.where && { where: opts.where }),
|
|
6011
6381
|
};
|
|
6012
|
-
|
|
6013
|
-
|
|
6014
|
-
|
|
6015
|
-
|
|
6016
|
-
|
|
6017
|
-
|
|
6382
|
+
if (opts.through) {
|
|
6383
|
+
// Read-only property (the owning side manages the link)
|
|
6384
|
+
applyPropertyMetadata({
|
|
6385
|
+
through: opts.through,
|
|
6386
|
+
readOnly: true,
|
|
6387
|
+
local: opts.local,
|
|
6388
|
+
})(target, key);
|
|
6389
|
+
}
|
|
6390
|
+
else {
|
|
6391
|
+
Object.defineProperty(target, key, { configurable: true, writable: true });
|
|
6392
|
+
}
|
|
6018
6393
|
};
|
|
6019
6394
|
}
|
|
6020
6395
|
function BelongsToMany(first, second) {
|
|
@@ -6030,6 +6405,8 @@ function BelongsToMany(first, second) {
|
|
|
6030
6405
|
kind: 'belongsToMany',
|
|
6031
6406
|
local: opts.local,
|
|
6032
6407
|
...(opts.getter && { getter: opts.getter }),
|
|
6408
|
+
...(opts.filter !== undefined && { filter: opts.filter }),
|
|
6409
|
+
...(opts.where && { where: opts.where }),
|
|
6033
6410
|
};
|
|
6034
6411
|
// @BelongsToMany is the inverse/read-only side — do NOT generate add*/remove*/set*
|
|
6035
6412
|
// prototype methods. Mutation must go through the owning side's @HasMany decorator.
|
|
@@ -6038,58 +6415,6 @@ function BelongsToMany(first, second) {
|
|
|
6038
6415
|
};
|
|
6039
6416
|
}
|
|
6040
6417
|
|
|
6041
|
-
function formatList(list) {
|
|
6042
|
-
if (!list?.length) {
|
|
6043
|
-
return "";
|
|
6044
|
-
}
|
|
6045
|
-
if (list.length === 1) {
|
|
6046
|
-
return list.toString();
|
|
6047
|
-
}
|
|
6048
|
-
if (list.length === 2) {
|
|
6049
|
-
return list.join(' and ');
|
|
6050
|
-
}
|
|
6051
|
-
return list.slice(0, -1).join(', ') + ', and ' + list.slice(-1);
|
|
6052
|
-
}
|
|
6053
|
-
function capSentence(cap) {
|
|
6054
|
-
const can = cap.can.includes("*") ? ["READ", "WRITE", "UPDATE"] : cap.can;
|
|
6055
|
-
const domain = cap.with.domain === "*" ? "" : cap.with.domain;
|
|
6056
|
-
const pointers = cap.with.pointers.includes("*")
|
|
6057
|
-
? ["all AD4M data"]
|
|
6058
|
-
: cap.with.pointers;
|
|
6059
|
-
return `${formatList(can)} your ${domain} actions, with access to ${formatList(pointers)}`;
|
|
6060
|
-
}
|
|
6061
|
-
/**
|
|
6062
|
-
* Escapes a string value for safe use in SurrealQL queries.
|
|
6063
|
-
*
|
|
6064
|
-
* @description
|
|
6065
|
-
* Prevents SQL injection by properly escaping special characters in string values
|
|
6066
|
-
* that will be interpolated into SurrealQL queries. This handles the most common
|
|
6067
|
-
* special characters that could break SQL queries or enable injection attacks.
|
|
6068
|
-
*
|
|
6069
|
-
* Single quotes, backslashes, and other special characters are escaped using
|
|
6070
|
-
* backslash notation, which is the standard escaping mechanism for SurrealQL.
|
|
6071
|
-
*
|
|
6072
|
-
* @param value - The string value to escape
|
|
6073
|
-
* @returns The escaped string safe for SurrealQL interpolation (without surrounding quotes)
|
|
6074
|
-
*
|
|
6075
|
-
* @example
|
|
6076
|
-
* ```typescript
|
|
6077
|
-
* const userInput = "user's input with 'quotes'";
|
|
6078
|
-
* const escaped = escapeSurrealString(userInput);
|
|
6079
|
-
* const query = `SELECT * FROM link WHERE uri = '${escaped}'`;
|
|
6080
|
-
* // Results in: SELECT * FROM link WHERE uri = 'user\'s input with \'quotes\''
|
|
6081
|
-
* ```
|
|
6082
|
-
*/
|
|
6083
|
-
function escapeSurrealString(value) {
|
|
6084
|
-
return value
|
|
6085
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
6086
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
6087
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
6088
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
6089
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
6090
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
6091
|
-
}
|
|
6092
|
-
|
|
6093
6418
|
/**
|
|
6094
6419
|
* SHACL Flow - represents a state machine for AD4M expressions
|
|
6095
6420
|
*
|
|
@@ -20444,6 +20769,9 @@ class Ad4mModel {
|
|
|
20444
20769
|
...(options.local !== undefined && { local: options.local }),
|
|
20445
20770
|
...(options.getter !== undefined && { getter: options.getter }),
|
|
20446
20771
|
direction: (options.kind === 'belongsToMany' || options.kind === 'belongsToOne') ? 'reverse' : 'forward',
|
|
20772
|
+
...(options.target !== undefined && { target: options.target }),
|
|
20773
|
+
...(options.filter !== undefined && { filter: options.filter }),
|
|
20774
|
+
...(options.where !== undefined && { where: options.where }),
|
|
20447
20775
|
};
|
|
20448
20776
|
}
|
|
20449
20777
|
// Fallback: If both structures are empty but a JSON schema is attached, derive from it
|
|
@@ -20707,11 +21035,29 @@ class Ad4mModel {
|
|
|
20707
21035
|
predToProperty.set(propMeta.predicate, [propName, propMeta]);
|
|
20708
21036
|
}
|
|
20709
21037
|
const predToRelation = new Map();
|
|
21038
|
+
// Two-pass approach: first add all non-getter, non-target-filtered relations,
|
|
21039
|
+
// then try to add target+filter relations only if their predicate isn't
|
|
21040
|
+
// already claimed. This prevents predicate collisions (e.g. entries +
|
|
21041
|
+
// messages sharing the same predicate) while still populating unique-
|
|
21042
|
+
// predicate relations normally via link hydration.
|
|
21043
|
+
const deferredTargetRelations = [];
|
|
20710
21044
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
20711
21045
|
if (relMeta.getter)
|
|
21046
|
+
continue; // Handled via explicit custom getter evaluation
|
|
21047
|
+
if (relMeta.target && relMeta.filter !== false) {
|
|
21048
|
+
deferredTargetRelations.push([relName, relMeta]);
|
|
20712
21049
|
continue;
|
|
21050
|
+
}
|
|
20713
21051
|
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
20714
21052
|
}
|
|
21053
|
+
// Second pass: add deferred target+filter relations only if their predicate
|
|
21054
|
+
// is not already claimed by a base relation. When a collision exists, the
|
|
21055
|
+
// conformance getter will handle the filtered view instead.
|
|
21056
|
+
for (const [relName, relMeta] of deferredTargetRelations) {
|
|
21057
|
+
if (!predToRelation.has(relMeta.predicate)) {
|
|
21058
|
+
predToRelation.set(relMeta.predicate, [relName, relMeta]);
|
|
21059
|
+
}
|
|
21060
|
+
}
|
|
20715
21061
|
// Per-property accumulator: track all matching targets so we can pick the last (latest-wins)
|
|
20716
21062
|
const propertyLatest = new Map();
|
|
20717
21063
|
// Per-relation accumulator: ordered targets with metadata for sorting
|
|
@@ -21029,7 +21375,10 @@ class Ad4mModel {
|
|
|
21029
21375
|
}
|
|
21030
21376
|
}
|
|
21031
21377
|
// Evaluate SurrealQL getters
|
|
21032
|
-
|
|
21378
|
+
const getterOpts = opts?.properties || opts?.include
|
|
21379
|
+
? { requestedProperties: opts?.properties, include: opts?.include }
|
|
21380
|
+
: undefined;
|
|
21381
|
+
await ctor.evaluateCustomGettersForInstance(this, this._perspective, metadata, getterOpts);
|
|
21033
21382
|
// Eager-load relations if requested
|
|
21034
21383
|
if (opts?.include) {
|
|
21035
21384
|
await ctor.hydrateRelations([this], this._perspective, opts.include);
|
|
@@ -21066,14 +21415,49 @@ class Ad4mModel {
|
|
|
21066
21415
|
`;
|
|
21067
21416
|
return fullQuery;
|
|
21068
21417
|
}
|
|
21418
|
+
/**
|
|
21419
|
+
* Builds a SurrealQL conformance getter for a relation whose `target` model
|
|
21420
|
+
* is known but no explicit `getter` string was supplied.
|
|
21421
|
+
*
|
|
21422
|
+
* The generated getter traverses outgoing links matching the relation's
|
|
21423
|
+
* predicate and then filters the target nodes to only those that conform to
|
|
21424
|
+
* the target model's shape (required properties / flags).
|
|
21425
|
+
*
|
|
21426
|
+
* Delegates to the shared `buildConformanceFilter()` utility in decorators.ts
|
|
21427
|
+
* so the same logic is used at shape-definition time and at query time.
|
|
21428
|
+
*
|
|
21429
|
+
* @param relationPredicate - The relation's predicate URI (e.g. "flux://entry_type")
|
|
21430
|
+
* @param targetClass - The target model class (result of calling the `target()` thunk)
|
|
21431
|
+
* @returns A SurrealQL expression string, or `undefined` if no conformance
|
|
21432
|
+
* conditions could be derived from the target model.
|
|
21433
|
+
* @private
|
|
21434
|
+
*/
|
|
21435
|
+
static buildConformanceGetter(relationPredicate, targetClass) {
|
|
21436
|
+
const filter = buildConformanceFilter(relationPredicate, targetClass);
|
|
21437
|
+
if (!filter) {
|
|
21438
|
+
const targetName = targetClass?.prototype?.className || targetClass?.name || 'unknown';
|
|
21439
|
+
console.warn(`[Ad4mModel] buildConformanceGetter: no conditions found for target "${targetName}".`);
|
|
21440
|
+
return undefined;
|
|
21441
|
+
}
|
|
21442
|
+
return filter.getter;
|
|
21443
|
+
}
|
|
21069
21444
|
/**
|
|
21070
21445
|
* Evaluates custom SurrealQL getters for properties and relations on a specific instance.
|
|
21446
|
+
*
|
|
21447
|
+
* For relations that declare a `target` but no explicit `getter`, a conformance
|
|
21448
|
+
* getter is auto-generated from the target model's metadata (unless `filter: false`).
|
|
21071
21449
|
* @private
|
|
21072
21450
|
*/
|
|
21073
|
-
static async evaluateCustomGettersForInstance(instance, perspective, metadata) {
|
|
21451
|
+
static async evaluateCustomGettersForInstance(instance, perspective, metadata, options) {
|
|
21074
21452
|
const safeBaseExpression = this.formatSurrealValue(instance.id);
|
|
21453
|
+
// Build projection filter — when requestedProperties is active, only
|
|
21454
|
+
// evaluate getters for fields that are requested (or included).
|
|
21455
|
+
const projectionActive = options?.requestedProperties && options.requestedProperties.length > 0;
|
|
21456
|
+
const projectionSet = projectionActive ? new Set(options.requestedProperties) : null;
|
|
21075
21457
|
// Evaluate property getters
|
|
21076
21458
|
for (const [propName, propMeta] of Object.entries(metadata.properties)) {
|
|
21459
|
+
if (projectionSet && !projectionSet.has(propName))
|
|
21460
|
+
continue;
|
|
21077
21461
|
if (propMeta.getter) {
|
|
21078
21462
|
try {
|
|
21079
21463
|
// Replace 'Base' placeholder with actual base expression
|
|
@@ -21089,14 +21473,56 @@ class Ad4mModel {
|
|
|
21089
21473
|
}
|
|
21090
21474
|
}
|
|
21091
21475
|
}
|
|
21092
|
-
// Evaluate relation getters
|
|
21476
|
+
// Evaluate relation getters (explicit or auto-generated from target)
|
|
21093
21477
|
for (const [relName, relMeta] of Object.entries(metadata.relations)) {
|
|
21094
|
-
|
|
21478
|
+
// Skip relations excluded by property projection (unless in include map)
|
|
21479
|
+
if (projectionSet && !projectionSet.has(relName) && !(options?.include && relName in options.include))
|
|
21480
|
+
continue;
|
|
21481
|
+
const meta = relMeta;
|
|
21482
|
+
// Determine the getter to execute:
|
|
21483
|
+
// 1. Explicit `getter` always wins
|
|
21484
|
+
// 2. `where` clause → compile DSL to SurrealQL getter
|
|
21485
|
+
// 3. If `target` is set and `filter !== false`, auto-generate from target metadata
|
|
21486
|
+
// BUT skip auto-generation for reverse relations (belongsToMany / belongsToOne)
|
|
21487
|
+
// because buildConformanceGetter traverses outgoing links (->link) which is
|
|
21488
|
+
// wrong for reverse relations. Their values are already populated by the
|
|
21489
|
+
// reverse link lookup in instancesFromSurrealResult / getData.
|
|
21490
|
+
let getter = meta.getter;
|
|
21491
|
+
if (!getter && meta.where && meta.direction !== 'reverse') {
|
|
21492
|
+
try {
|
|
21493
|
+
const TargetClass = meta.target?.();
|
|
21494
|
+
const targetMetadata = TargetClass
|
|
21495
|
+
? TargetClass.getModelMetadata?.() ?? null
|
|
21496
|
+
: null;
|
|
21497
|
+
const conditions = compileWhereClause(meta.where, targetMetadata);
|
|
21498
|
+
if (conditions.length > 0) {
|
|
21499
|
+
const escapedPred = escapeSurrealString(meta.predicate);
|
|
21500
|
+
getter = `(->link[WHERE predicate = '${escapedPred}'].out[WHERE ${conditions.join(' AND ')}].uri)`;
|
|
21501
|
+
}
|
|
21502
|
+
}
|
|
21503
|
+
catch (e) {
|
|
21504
|
+
// Target metadata may not be available yet
|
|
21505
|
+
}
|
|
21506
|
+
}
|
|
21507
|
+
if (!getter && meta.target && meta.filter !== false && meta.direction !== 'reverse') {
|
|
21508
|
+
try {
|
|
21509
|
+
const TargetClass = meta.target();
|
|
21510
|
+
getter = this.buildConformanceGetter(meta.predicate, TargetClass);
|
|
21511
|
+
if (!getter) {
|
|
21512
|
+
console.warn(`[Ad4mModel] buildConformanceGetter returned undefined for relation "${relName}" (predicate: "${meta.predicate}")`);
|
|
21513
|
+
}
|
|
21514
|
+
}
|
|
21515
|
+
catch (e) {
|
|
21516
|
+
console.warn(`[Ad4mModel] auto-generation failed for relation "${relName}":`, e);
|
|
21517
|
+
}
|
|
21518
|
+
}
|
|
21519
|
+
if (getter) {
|
|
21095
21520
|
try {
|
|
21096
21521
|
// Replace 'Base' placeholder with actual base expression
|
|
21097
|
-
const query =
|
|
21522
|
+
const query = getter.replace(/Base/g, safeBaseExpression);
|
|
21523
|
+
const fullQuery = `SELECT (${query}) AS value FROM node WHERE uri = ${safeBaseExpression}`;
|
|
21098
21524
|
// Query from node table to have graph traversal context
|
|
21099
|
-
const result = await perspective.querySurrealDB(
|
|
21525
|
+
const result = await perspective.querySurrealDB(fullQuery);
|
|
21100
21526
|
if (result && result.length > 0 && result[0].value !== undefined && result[0].value !== null) {
|
|
21101
21527
|
// Filter out 'None' from relation results
|
|
21102
21528
|
const value = result[0].value;
|
|
@@ -21876,26 +22302,7 @@ FETCH links
|
|
|
21876
22302
|
* @private
|
|
21877
22303
|
*/
|
|
21878
22304
|
static formatSurrealValue(value) {
|
|
21879
|
-
|
|
21880
|
-
// Escape backslashes first, then single quotes and other special characters
|
|
21881
|
-
const escaped = value
|
|
21882
|
-
.replace(/\\/g, '\\\\') // Backslash -> \\
|
|
21883
|
-
.replace(/'/g, "\\'") // Single quote -> \'
|
|
21884
|
-
.replace(/"/g, '\\"') // Double quote -> \"
|
|
21885
|
-
.replace(/\n/g, '\\n') // Newline -> \n
|
|
21886
|
-
.replace(/\r/g, '\\r') // Carriage return -> \r
|
|
21887
|
-
.replace(/\t/g, '\\t'); // Tab -> \t
|
|
21888
|
-
return `'${escaped}'`;
|
|
21889
|
-
}
|
|
21890
|
-
else if (typeof value === 'number' || typeof value === 'boolean') {
|
|
21891
|
-
return String(value);
|
|
21892
|
-
}
|
|
21893
|
-
else if (Array.isArray(value)) {
|
|
21894
|
-
return `[${value.map(v => this.formatSurrealValue(v)).join(', ')}]`;
|
|
21895
|
-
}
|
|
21896
|
-
else {
|
|
21897
|
-
return String(value);
|
|
21898
|
-
}
|
|
22305
|
+
return formatSurrealValue(value);
|
|
21899
22306
|
}
|
|
21900
22307
|
static async instancesFromPrologResult(perspective, query, result) {
|
|
21901
22308
|
if (!result?.[0]?.AllInstances)
|
|
@@ -22023,8 +22430,11 @@ FETCH links
|
|
|
22023
22430
|
}));
|
|
22024
22431
|
}
|
|
22025
22432
|
// Evaluate custom getters for all instances (single pass)
|
|
22433
|
+
const getterOpts = requestedProperties.length > 0 || query.include
|
|
22434
|
+
? { requestedProperties, include: query.include }
|
|
22435
|
+
: undefined;
|
|
22026
22436
|
for (const instance of instances) {
|
|
22027
|
-
await this.evaluateCustomGettersForInstance(instance, perspective, metadata);
|
|
22437
|
+
await this.evaluateCustomGettersForInstance(instance, perspective, metadata, getterOpts);
|
|
22028
22438
|
}
|
|
22029
22439
|
// Filter by where conditions that couldn't be filtered in SQL
|
|
22030
22440
|
// This includes:
|
|
@@ -22528,11 +22938,25 @@ FETCH links
|
|
|
22528
22938
|
// entirely and let innerUpdate write the links directly.
|
|
22529
22939
|
const metadata = this.constructor.getModelMetadata();
|
|
22530
22940
|
const hasConstructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
|
|
22941
|
+
// Track properties that have resolveLanguage (non-literal) so they can be
|
|
22942
|
+
// set via setProperty after createSubject (which doesn't resolve languages).
|
|
22943
|
+
const deferredResolveLanguageProps = [];
|
|
22531
22944
|
if (hasConstructor) {
|
|
22532
22945
|
// First filter out the properties that are not relations (arrays)
|
|
22533
22946
|
const initialValues = {};
|
|
22534
22947
|
for (const [key, value] of Object.entries(this)) {
|
|
22535
22948
|
if (value !== undefined && value !== null && !(Array.isArray(value) && value.length > 0) && !value?.action) {
|
|
22949
|
+
// Check if this property requires language resolution (e.g. file storage).
|
|
22950
|
+
// If so, resolve the expression *before* passing to createSubject so
|
|
22951
|
+
// the constructor receives a valid URI instead of raw data.
|
|
22952
|
+
const propMeta = metadata.properties[key];
|
|
22953
|
+
if (propMeta?.resolveLanguage && propMeta.resolveLanguage !== 'literal' && typeof value === 'object') {
|
|
22954
|
+
// Defer these properties — they need createExpression which may
|
|
22955
|
+
// fail inside a batch context on some languages. We'll set them
|
|
22956
|
+
// via setProperty after createSubject.
|
|
22957
|
+
deferredResolveLanguageProps.push(key);
|
|
22958
|
+
continue;
|
|
22959
|
+
}
|
|
22536
22960
|
initialValues[key] = value;
|
|
22537
22961
|
}
|
|
22538
22962
|
}
|
|
@@ -22545,6 +22969,15 @@ FETCH links
|
|
|
22545
22969
|
// When createSubject was skipped (no constructor actions), we must enable
|
|
22546
22970
|
// property writing so that scalar values are persisted as links.
|
|
22547
22971
|
await this.innerUpdate(!hasConstructor, batchId);
|
|
22972
|
+
// Now handle any deferred resolveLanguage properties that were excluded
|
|
22973
|
+
// from initialValues. setProperty will call createExpression to upload
|
|
22974
|
+
// the data to the appropriate language and store the resulting URI.
|
|
22975
|
+
for (const key of deferredResolveLanguageProps) {
|
|
22976
|
+
const value = this[key];
|
|
22977
|
+
if (value !== undefined && value !== null) {
|
|
22978
|
+
await this.setProperty(key, value, batchId);
|
|
22979
|
+
}
|
|
22980
|
+
}
|
|
22548
22981
|
// If we got a batchId passed in, we let the caller decide when to commit.
|
|
22549
22982
|
// We can't call getData() since the instance won't exist in the perspective
|
|
22550
22983
|
// until the batch is committed.
|
|
@@ -22597,6 +23030,22 @@ FETCH links
|
|
|
22597
23030
|
// Skip unchanged fields when a snapshot is available
|
|
22598
23031
|
if (dirty && !dirty.has(key))
|
|
22599
23032
|
continue;
|
|
23033
|
+
// Skip read-only computed relations — explicit getters never write links.
|
|
23034
|
+
// For target+filter relations, skip only when another relation on this
|
|
23035
|
+
// model claims the same predicate (i.e., this is a filtered *view* of a
|
|
23036
|
+
// base relation and writing would collide).
|
|
23037
|
+
const relMeta = metadata.relations[key];
|
|
23038
|
+
if (relMeta) {
|
|
23039
|
+
if (relMeta.getter)
|
|
23040
|
+
continue;
|
|
23041
|
+
if (relMeta.target && relMeta.filter !== false) {
|
|
23042
|
+
// Check for predicate collision with a sibling relation
|
|
23043
|
+
const hasCollision = Object.entries(metadata.relations).some(([otherName, otherMeta]) => otherName !== key &&
|
|
23044
|
+
otherMeta.predicate === relMeta.predicate);
|
|
23045
|
+
if (hasCollision)
|
|
23046
|
+
continue;
|
|
23047
|
+
}
|
|
23048
|
+
}
|
|
22600
23049
|
if (value !== undefined && value !== null) {
|
|
22601
23050
|
if (value?.action) {
|
|
22602
23051
|
switch (value.action) {
|
|
@@ -22693,11 +23142,6 @@ FETCH links
|
|
|
22693
23142
|
* ```
|
|
22694
23143
|
*/
|
|
22695
23144
|
async delete(batchId) {
|
|
22696
|
-
// Check if the model has a destructor (required properties, flags, or
|
|
22697
|
-
// properties with initial values). Models whose properties are all
|
|
22698
|
-
// optional, have no @Flag, and have no initial values produce an empty
|
|
22699
|
-
// SHACL destructor, so calling removeSubject would fail. In that case
|
|
22700
|
-
// we skip the destructor and just remove all outgoing links directly.
|
|
22701
23145
|
const metadata = this.constructor.getModelMetadata();
|
|
22702
23146
|
const hasDestructor = Object.values(metadata.properties).some((p) => p.required || p.flag || p.initial !== undefined);
|
|
22703
23147
|
if (hasDestructor) {
|
|
@@ -22705,18 +23149,39 @@ FETCH links
|
|
|
22705
23149
|
await this._perspective.removeSubject(this, this._baseExpression, batchId);
|
|
22706
23150
|
}
|
|
22707
23151
|
else {
|
|
22708
|
-
// No destructor
|
|
23152
|
+
// No destructor (all-optional model).
|
|
23153
|
+
// SAFETY: We must NOT remove all outgoing links because another model
|
|
23154
|
+
// class may be instantiated on the same base expression. Removing
|
|
23155
|
+
// everything would silently destroy that other instance's data — and
|
|
23156
|
+
// if that instance has a destructor, it can no longer be called
|
|
23157
|
+
// cleanly, leaving link debris.
|
|
23158
|
+
//
|
|
23159
|
+
// Instead we only remove outgoing links whose predicate is declared
|
|
23160
|
+
// by THIS model's schema (properties + relations).
|
|
22709
23161
|
try {
|
|
23162
|
+
const knownPredicates = new Set();
|
|
23163
|
+
for (const p of Object.values(metadata.properties)) {
|
|
23164
|
+
if (p.predicate)
|
|
23165
|
+
knownPredicates.add(p.predicate);
|
|
23166
|
+
}
|
|
23167
|
+
for (const r of Object.values(metadata.relations)) {
|
|
23168
|
+
if (r.predicate)
|
|
23169
|
+
knownPredicates.add(r.predicate);
|
|
23170
|
+
}
|
|
22710
23171
|
const outgoingLinks = await this._perspective.get(new exports.LinkQuery({ source: this._baseExpression }));
|
|
22711
|
-
|
|
22712
|
-
|
|
23172
|
+
const ownLinks = outgoingLinks.filter((link) => link.data.predicate && knownPredicates.has(link.data.predicate));
|
|
23173
|
+
if (ownLinks.length > 0) {
|
|
23174
|
+
await this._perspective.removeLinks(ownLinks, batchId);
|
|
22713
23175
|
}
|
|
22714
23176
|
}
|
|
22715
23177
|
catch (e) {
|
|
22716
23178
|
console.warn(`delete(): failed to remove outgoing links for ${this._baseExpression}:`, e);
|
|
22717
23179
|
}
|
|
22718
23180
|
}
|
|
22719
|
-
// Clean up incoming links — remove any links that point **to** this instance
|
|
23181
|
+
// Clean up incoming links — remove any links that point **to** this instance.
|
|
23182
|
+
// Unlike outgoing links (scoped above), incoming links originate from OTHER
|
|
23183
|
+
// nodes. Removing them doesn't damage sibling models on this node; it
|
|
23184
|
+
// prevents dangling references elsewhere (e.g. a parent's has_child link).
|
|
22720
23185
|
try {
|
|
22721
23186
|
const incomingLinks = await this._perspective.get(new exports.LinkQuery({ target: this._baseExpression }));
|
|
22722
23187
|
if (incomingLinks.length > 0) {
|
|
@@ -23942,6 +24407,7 @@ exports.SMART_LITERAL_CONTENT_PREDICATE = SMART_LITERAL_CONTENT_PREDICATE;
|
|
|
23942
24407
|
exports.SmartLiteral = SmartLiteral;
|
|
23943
24408
|
exports.Subject = Subject;
|
|
23944
24409
|
exports.addLink = addLink;
|
|
24410
|
+
exports.buildConformanceFilter = buildConformanceFilter;
|
|
23945
24411
|
exports.capSentence = capSentence;
|
|
23946
24412
|
exports.escapeSurrealString = escapeSurrealString;
|
|
23947
24413
|
exports.exprRef2String = exprRef2String;
|