jsonldjs 0.1.0 → 0.1.2
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/README.md +405 -1
- package/builder-utils.d.ts +57 -0
- package/builder-utils.js +269 -0
- package/builder.d.ts +44 -0
- package/builder.js +119 -0
- package/config.d.ts +143 -0
- package/config.js +344 -0
- package/esm/builder-utils.js +255 -0
- package/esm/builder.js +114 -0
- package/esm/config.js +339 -0
- package/esm/index.js +4 -390
- package/esm/jsonld-utils.js +483 -0
- package/esm/types.js +8 -0
- package/index.d.ts +5 -119
- package/index.js +24 -402
- package/jsonld-utils.d.ts +142 -0
- package/jsonld-utils.js +500 -0
- package/package.json +1 -1
- package/types.d.ts +162 -0
- package/types.js +9 -0
package/jsonld-utils.js
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Custom JSON-LD graph utilities
|
|
4
|
+
*
|
|
5
|
+
* Simple, focused functions for working with JSON-LD graph arrays.
|
|
6
|
+
* No external dependencies, no context expansion - just pure graph traversal.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.matchesSelector = matchesSelector;
|
|
10
|
+
exports.findEntity = findEntity;
|
|
11
|
+
exports.findEntities = findEntities;
|
|
12
|
+
exports.findEntitiesByType = findEntitiesByType;
|
|
13
|
+
exports.extractReferences = extractReferences;
|
|
14
|
+
exports.extractSubgraph = extractSubgraph;
|
|
15
|
+
exports.extractSubgraphs = extractSubgraphs;
|
|
16
|
+
exports.findReferencingEntities = findReferencingEntities;
|
|
17
|
+
exports.extractSubgraphWithDepth = extractSubgraphWithDepth;
|
|
18
|
+
exports.findMissingReferences = findMissingReferences;
|
|
19
|
+
exports.findNestedEntities = findNestedEntities;
|
|
20
|
+
exports.findOrphans = findOrphans;
|
|
21
|
+
exports.inlineReferences = inlineReferences;
|
|
22
|
+
exports.filterEntityProperties = filterEntityProperties;
|
|
23
|
+
exports.filterGraphProperties = filterGraphProperties;
|
|
24
|
+
/**
|
|
25
|
+
* Check if an entity matches a property filter selector
|
|
26
|
+
*/
|
|
27
|
+
function matchesSelector(entity, selector) {
|
|
28
|
+
// Global selector - matches everything
|
|
29
|
+
if (selector === '*')
|
|
30
|
+
return true;
|
|
31
|
+
// Empty object selector - matches everything
|
|
32
|
+
if (typeof selector === 'object' && Object.keys(selector).length === 0)
|
|
33
|
+
return true;
|
|
34
|
+
// Property-based matching
|
|
35
|
+
return Object.entries(selector).every(([property, expectedValue]) => {
|
|
36
|
+
const entityValue = entity[property];
|
|
37
|
+
// Handle array values - check if expectedValue is in the array
|
|
38
|
+
if (Array.isArray(entityValue)) {
|
|
39
|
+
return entityValue.includes(expectedValue);
|
|
40
|
+
}
|
|
41
|
+
// Handle object references - compare @id if expectedValue is an object with @id
|
|
42
|
+
if (typeof expectedValue === 'object' &&
|
|
43
|
+
expectedValue['@id'] &&
|
|
44
|
+
typeof entityValue === 'object' &&
|
|
45
|
+
entityValue['@id']) {
|
|
46
|
+
return entityValue['@id'] === expectedValue['@id'];
|
|
47
|
+
}
|
|
48
|
+
// Direct value comparison
|
|
49
|
+
return entityValue === expectedValue;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Find a single entity in the graph by @id
|
|
54
|
+
*
|
|
55
|
+
* @param graph - Array of JSON-LD entities
|
|
56
|
+
* @param id - The @id to search for
|
|
57
|
+
* @returns The entity if found, undefined otherwise
|
|
58
|
+
*/
|
|
59
|
+
function findEntity(graph, id) {
|
|
60
|
+
return graph.find((entity) => entity['@id'] === id);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Find multiple entities in the graph by @id
|
|
64
|
+
*
|
|
65
|
+
* @param graph - Array of JSON-LD entities
|
|
66
|
+
* @param ids - Array of @ids to search for
|
|
67
|
+
* @returns Array of found entities (may be fewer than requested if some not found)
|
|
68
|
+
*/
|
|
69
|
+
function findEntities(graph, ids) {
|
|
70
|
+
const idSet = new Set(ids);
|
|
71
|
+
return graph.filter((entity) => idSet.has(entity['@id']));
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Find entities by @type
|
|
75
|
+
*
|
|
76
|
+
* @param graph - Array of JSON-LD entities
|
|
77
|
+
* @param type - The @type to search for
|
|
78
|
+
* @returns Array of entities matching the type
|
|
79
|
+
*/
|
|
80
|
+
function findEntitiesByType(graph, type) {
|
|
81
|
+
return graph.filter((entity) => {
|
|
82
|
+
const entityType = entity['@type'];
|
|
83
|
+
if (Array.isArray(entityType)) {
|
|
84
|
+
return entityType.includes(type);
|
|
85
|
+
}
|
|
86
|
+
return entityType === type;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Extract all @id references from an entity's properties
|
|
91
|
+
*
|
|
92
|
+
* @param entity - JSON-LD entity to scan
|
|
93
|
+
* @returns Set of @id strings found in the entity
|
|
94
|
+
*/
|
|
95
|
+
function extractReferences(entity) {
|
|
96
|
+
const references = new Set();
|
|
97
|
+
function scanValue(value) {
|
|
98
|
+
if (value === null || value === undefined) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (typeof value === 'string') {
|
|
102
|
+
// Check if it looks like an @id reference using regex pattern
|
|
103
|
+
// Pattern: ^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?[^\s]+$
|
|
104
|
+
// This matches:
|
|
105
|
+
// - URIs with scheme: scheme:path (e.g., mailto:user@example.com)
|
|
106
|
+
// - Compact URIs: prefix:suffix (e.g., person:danlynch, org:hyperweb)
|
|
107
|
+
// - Must not contain spaces (filters out titles/descriptions with colons)
|
|
108
|
+
const idPattern = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)[^\s]+$/;
|
|
109
|
+
// Additional checks:
|
|
110
|
+
// - Must match the pattern
|
|
111
|
+
// - Must contain a colon (to be a reference)
|
|
112
|
+
// - Exclude http/https URLs (handled separately)
|
|
113
|
+
if (idPattern.test(value) && value.includes(':') && !value.startsWith('http')) {
|
|
114
|
+
references.add(value);
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (Array.isArray(value)) {
|
|
119
|
+
value.forEach(scanValue);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (typeof value === 'object') {
|
|
123
|
+
// If it has an @id, add it
|
|
124
|
+
if (value['@id']) {
|
|
125
|
+
references.add(value['@id']);
|
|
126
|
+
}
|
|
127
|
+
// Recursively scan all properties
|
|
128
|
+
Object.values(value).forEach(scanValue);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// Scan all properties except @id and @type
|
|
133
|
+
Object.entries(entity).forEach(([key, value]) => {
|
|
134
|
+
if (key !== '@id' && key !== '@type') {
|
|
135
|
+
scanValue(value);
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
return references;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Extract a subgraph containing an entity and all its referenced entities
|
|
142
|
+
*
|
|
143
|
+
* Recursively finds all @id references within the entity and includes
|
|
144
|
+
* those entities in the result. Returns a filtered array of the original
|
|
145
|
+
* graph elements - does not modify the entities themselves.
|
|
146
|
+
*
|
|
147
|
+
* @param graph - Array of JSON-LD entities
|
|
148
|
+
* @param id - The root @id to start from
|
|
149
|
+
* @param propertyFilters - Optional property filtering configuration to apply before reference traversal
|
|
150
|
+
* @returns Array containing the root entity and all recursively referenced entities
|
|
151
|
+
*/
|
|
152
|
+
function extractSubgraph(graph, id, propertyFilters) {
|
|
153
|
+
const result = new Map();
|
|
154
|
+
const visited = new Set();
|
|
155
|
+
const toProcess = new Set([id]);
|
|
156
|
+
while (toProcess.size > 0) {
|
|
157
|
+
const currentId = toProcess.values().next().value;
|
|
158
|
+
toProcess.delete(currentId);
|
|
159
|
+
if (visited.has(currentId)) {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
visited.add(currentId);
|
|
163
|
+
const entity = findEntity(graph, currentId);
|
|
164
|
+
if (!entity) {
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
// Apply property filtering to this specific entity as we encounter it
|
|
168
|
+
const filteredEntity = propertyFilters ? filterEntityProperties(entity, propertyFilters) : entity;
|
|
169
|
+
result.set(currentId, filteredEntity);
|
|
170
|
+
// Find all references in the filtered entity (only surviving properties)
|
|
171
|
+
const references = extractReferences(filteredEntity);
|
|
172
|
+
// Add unvisited references to process queue
|
|
173
|
+
references.forEach((refId) => {
|
|
174
|
+
if (!visited.has(refId)) {
|
|
175
|
+
toProcess.add(refId);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return Array.from(result.values());
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Extract subgraphs for multiple root entities
|
|
183
|
+
*
|
|
184
|
+
* @param graph - Array of JSON-LD entities
|
|
185
|
+
* @param ids - Array of root @ids to start from
|
|
186
|
+
* @param propertyFilters - Optional property filtering configuration to apply before reference traversal
|
|
187
|
+
* @returns Array containing all entities and their recursively referenced entities
|
|
188
|
+
*/
|
|
189
|
+
function extractSubgraphs(graph, ids, propertyFilters) {
|
|
190
|
+
const allEntities = new Map();
|
|
191
|
+
ids.forEach((id) => {
|
|
192
|
+
const subgraph = extractSubgraph(graph, id, propertyFilters);
|
|
193
|
+
subgraph.forEach((entity) => {
|
|
194
|
+
allEntities.set(entity['@id'], entity);
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
return Array.from(allEntities.values());
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Find entities that reference a specific @id
|
|
201
|
+
*
|
|
202
|
+
* @param graph - Array of JSON-LD entities
|
|
203
|
+
* @param targetId - The @id to find references to
|
|
204
|
+
* @param propertyFilters - Optional property filtering to apply before checking references
|
|
205
|
+
* @returns Array of entities that reference the target @id
|
|
206
|
+
*/
|
|
207
|
+
function findReferencingEntities(graph, targetId, propertyFilters) {
|
|
208
|
+
return graph
|
|
209
|
+
.filter((entity) => {
|
|
210
|
+
// Apply property filtering to this specific entity
|
|
211
|
+
const filteredEntity = propertyFilters ? filterEntityProperties(entity, propertyFilters) : entity;
|
|
212
|
+
// Check if the filtered entity references the target ID
|
|
213
|
+
const references = extractReferences(filteredEntity);
|
|
214
|
+
return references.has(targetId);
|
|
215
|
+
})
|
|
216
|
+
.map((entity) => {
|
|
217
|
+
// Return the filtered version of entities that match
|
|
218
|
+
return propertyFilters ? filterEntityProperties(entity, propertyFilters) : entity;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Extract a subgraph with limited depth traversal
|
|
223
|
+
*
|
|
224
|
+
* Unlike extractSubgraph which recursively follows all references,
|
|
225
|
+
* this function only traverses to a specified depth from the root entity.
|
|
226
|
+
*
|
|
227
|
+
* @param graph - Array of JSON-LD entities
|
|
228
|
+
* @param id - The root @id to start from
|
|
229
|
+
* @param maxDepth - Maximum depth to traverse (1 = direct references only)
|
|
230
|
+
* @param propertyFilters - Optional property filtering configuration to apply before reference traversal
|
|
231
|
+
* @returns Array containing entities up to the specified depth
|
|
232
|
+
*/
|
|
233
|
+
function extractSubgraphWithDepth(graph, id, maxDepth, propertyFilters) {
|
|
234
|
+
if (maxDepth < 1) {
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
const result = new Map();
|
|
238
|
+
const visited = new Set();
|
|
239
|
+
const toProcess = [{ id, depth: 0 }];
|
|
240
|
+
while (toProcess.length > 0) {
|
|
241
|
+
const current = toProcess.shift();
|
|
242
|
+
if (visited.has(current.id) || current.depth > maxDepth) {
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
visited.add(current.id);
|
|
246
|
+
const entity = findEntity(graph, current.id);
|
|
247
|
+
if (!entity) {
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
// Apply property filtering to this specific entity as we encounter it
|
|
251
|
+
const filteredEntity = propertyFilters ? filterEntityProperties(entity, propertyFilters) : entity;
|
|
252
|
+
result.set(current.id, filteredEntity);
|
|
253
|
+
// Only process references if we haven't reached max depth
|
|
254
|
+
if (current.depth < maxDepth) {
|
|
255
|
+
// Find all references in the filtered entity (only surviving properties)
|
|
256
|
+
const references = extractReferences(filteredEntity);
|
|
257
|
+
references.forEach((refId) => {
|
|
258
|
+
if (!visited.has(refId)) {
|
|
259
|
+
toProcess.push({ id: refId, depth: current.depth + 1 });
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
return Array.from(result.values());
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Find all @id references that don't have corresponding entities in the graph
|
|
268
|
+
* @param graph - The JSON-LD graph to analyze
|
|
269
|
+
* @returns Array of missing @id references
|
|
270
|
+
*/
|
|
271
|
+
function findMissingReferences(graph) {
|
|
272
|
+
// First, collect all entity @ids that exist in the graph
|
|
273
|
+
const existingIds = new Set();
|
|
274
|
+
for (const entity of graph) {
|
|
275
|
+
if (entity['@id']) {
|
|
276
|
+
existingIds.add(entity['@id']);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// Then, collect all referenced @ids
|
|
280
|
+
const allReferences = new Set();
|
|
281
|
+
for (const entity of graph) {
|
|
282
|
+
const references = extractReferences(entity);
|
|
283
|
+
for (const ref of references) {
|
|
284
|
+
allReferences.add(ref);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// Find references that don't exist
|
|
288
|
+
const missing = [];
|
|
289
|
+
for (const ref of allReferences) {
|
|
290
|
+
if (!existingIds.has(ref)) {
|
|
291
|
+
missing.push(ref);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return missing.sort(); // Sort for consistent output
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Find entities that contain nested objects (potential normalization candidates)
|
|
298
|
+
* @param graph - The JSON-LD graph to analyze
|
|
299
|
+
* @returns Array of objects with parent @id and details about nested entities
|
|
300
|
+
*/
|
|
301
|
+
function findNestedEntities(graph) {
|
|
302
|
+
const results = [];
|
|
303
|
+
function isNestedEntity(value) {
|
|
304
|
+
// Check if it's an object (not null, not array)
|
|
305
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
// Skip if it's just an @id reference (only has @id property)
|
|
309
|
+
if (Object.keys(value).length === 1 && value['@id']) {
|
|
310
|
+
return false;
|
|
311
|
+
}
|
|
312
|
+
// It's a nested entity if it has properties beyond just @id
|
|
313
|
+
return true;
|
|
314
|
+
}
|
|
315
|
+
function scanEntity(entity, parentId, basePath = '') {
|
|
316
|
+
for (const [key, value] of Object.entries(entity)) {
|
|
317
|
+
// Skip special JSON-LD properties
|
|
318
|
+
if (key.startsWith('@'))
|
|
319
|
+
continue;
|
|
320
|
+
const propertyPath = basePath ? `${basePath}.${key}` : key;
|
|
321
|
+
if (isNestedEntity(value)) {
|
|
322
|
+
results.push({
|
|
323
|
+
parentId: parentId,
|
|
324
|
+
property: propertyPath,
|
|
325
|
+
nestedEntity: value,
|
|
326
|
+
hasId: !!value['@id'],
|
|
327
|
+
});
|
|
328
|
+
// Recursively scan the nested entity
|
|
329
|
+
scanEntity(value, parentId, propertyPath);
|
|
330
|
+
}
|
|
331
|
+
else if (Array.isArray(value)) {
|
|
332
|
+
// Check arrays for nested entities
|
|
333
|
+
value.forEach((item, index) => {
|
|
334
|
+
if (isNestedEntity(item)) {
|
|
335
|
+
const arrayPath = `${propertyPath}[${index}]`;
|
|
336
|
+
results.push({
|
|
337
|
+
parentId: parentId,
|
|
338
|
+
property: arrayPath,
|
|
339
|
+
nestedEntity: item,
|
|
340
|
+
hasId: !!item['@id'],
|
|
341
|
+
});
|
|
342
|
+
// Recursively scan the nested entity in array
|
|
343
|
+
scanEntity(item, parentId, arrayPath);
|
|
344
|
+
}
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
for (const entity of graph) {
|
|
350
|
+
if (!entity['@id'])
|
|
351
|
+
continue;
|
|
352
|
+
scanEntity(entity, entity['@id']);
|
|
353
|
+
}
|
|
354
|
+
return results;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Find all entities that exist in the graph but are never referenced by other entities
|
|
358
|
+
* @param graph - The JSON-LD graph to analyze
|
|
359
|
+
* @returns Array of orphaned @id values
|
|
360
|
+
*/
|
|
361
|
+
function findOrphans(graph) {
|
|
362
|
+
// First, collect all entity @ids that exist in the graph
|
|
363
|
+
const allIds = new Set();
|
|
364
|
+
for (const entity of graph) {
|
|
365
|
+
if (entity['@id']) {
|
|
366
|
+
allIds.add(entity['@id']);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
// Then, collect all referenced @ids
|
|
370
|
+
const referencedIds = new Set();
|
|
371
|
+
for (const entity of graph) {
|
|
372
|
+
const references = extractReferences(entity);
|
|
373
|
+
for (const ref of references) {
|
|
374
|
+
referencedIds.add(ref);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
// Find entities that exist but are never referenced
|
|
378
|
+
const orphans = [];
|
|
379
|
+
for (const id of allIds) {
|
|
380
|
+
if (!referencedIds.has(id)) {
|
|
381
|
+
orphans.push(id);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
return orphans.sort(); // Sort for consistent output
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Inline all @id references within entities, replacing them with their full entity data
|
|
388
|
+
*
|
|
389
|
+
* This function takes an array of entities and recursively replaces all @id references
|
|
390
|
+
* with the actual entity data. If a specific root ID is provided, it returns only
|
|
391
|
+
* that entity with all its references inlined. Otherwise, it returns all entities
|
|
392
|
+
* with references inlined.
|
|
393
|
+
*
|
|
394
|
+
* @param entities - Array of JSON-LD entities
|
|
395
|
+
* @param rootId - Optional root entity @id to return (if not provided, returns all entities)
|
|
396
|
+
* @returns Either a single entity with inlined references or array of all entities with inlined references
|
|
397
|
+
*/
|
|
398
|
+
function inlineReferences(entities, rootId) {
|
|
399
|
+
// Create a lookup map for all entities
|
|
400
|
+
const entityMap = new Map();
|
|
401
|
+
entities.forEach((entity) => {
|
|
402
|
+
if (entity['@id']) {
|
|
403
|
+
entityMap.set(entity['@id'], entity);
|
|
404
|
+
}
|
|
405
|
+
});
|
|
406
|
+
// Function to recursively inline references with circular reference protection
|
|
407
|
+
function inlineValue(value, visited = new Set()) {
|
|
408
|
+
if (value === null || value === undefined) {
|
|
409
|
+
return value;
|
|
410
|
+
}
|
|
411
|
+
if (Array.isArray(value)) {
|
|
412
|
+
return value.map((v) => inlineValue(v, visited));
|
|
413
|
+
}
|
|
414
|
+
if (typeof value === 'object') {
|
|
415
|
+
// If it's an @id reference (object with only @id property), replace with the full entity
|
|
416
|
+
if (value['@id'] && Object.keys(value).length === 1) {
|
|
417
|
+
const id = value['@id'];
|
|
418
|
+
// Check for circular reference
|
|
419
|
+
if (visited.has(id)) {
|
|
420
|
+
// Return just the @id reference to break the cycle
|
|
421
|
+
return { '@id': id };
|
|
422
|
+
}
|
|
423
|
+
const referencedEntity = entityMap.get(id);
|
|
424
|
+
if (referencedEntity) {
|
|
425
|
+
// Add to visited set before processing
|
|
426
|
+
const newVisited = new Set(visited);
|
|
427
|
+
newVisited.add(id);
|
|
428
|
+
// Create a copy and inline its references
|
|
429
|
+
const copy = { ...referencedEntity };
|
|
430
|
+
return inlineValue(copy, newVisited);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
// Otherwise, recursively process all properties
|
|
434
|
+
const result = {};
|
|
435
|
+
for (const [key, val] of Object.entries(value)) {
|
|
436
|
+
result[key] = inlineValue(val, visited);
|
|
437
|
+
}
|
|
438
|
+
return result;
|
|
439
|
+
}
|
|
440
|
+
return value;
|
|
441
|
+
}
|
|
442
|
+
// If a root ID is specified, return only that entity with inlined references
|
|
443
|
+
if (rootId) {
|
|
444
|
+
const mainEntity = entities.find((e) => e['@id'] === rootId);
|
|
445
|
+
if (!mainEntity) {
|
|
446
|
+
throw new Error(`Entity with @id "${rootId}" not found`);
|
|
447
|
+
}
|
|
448
|
+
return inlineValue(mainEntity);
|
|
449
|
+
}
|
|
450
|
+
// Otherwise, inline references in all entities
|
|
451
|
+
return entities.map((entity) => inlineValue(entity));
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Apply property filtering to a single entity based on matching rules
|
|
455
|
+
*/
|
|
456
|
+
function filterEntityProperties(entity, config) {
|
|
457
|
+
// Collect all exclusions and inclusions from matching rules
|
|
458
|
+
let allExclusions = new Set();
|
|
459
|
+
let lastInclude;
|
|
460
|
+
// Apply rules in order - later rules override earlier ones
|
|
461
|
+
for (const rule of config) {
|
|
462
|
+
if (matchesSelector(entity, rule.selector)) {
|
|
463
|
+
// If this rule has include, it overrides previous includes
|
|
464
|
+
if (rule.include) {
|
|
465
|
+
lastInclude = rule.include;
|
|
466
|
+
}
|
|
467
|
+
// Accumulate exclusions
|
|
468
|
+
if (rule.exclude) {
|
|
469
|
+
rule.exclude.forEach((prop) => allExclusions.add(prop));
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
// Determine which properties to include
|
|
474
|
+
let propertiesToInclude;
|
|
475
|
+
if (lastInclude) {
|
|
476
|
+
// Start with explicitly included properties from the last matching include rule
|
|
477
|
+
propertiesToInclude = lastInclude.filter((prop) => prop in entity);
|
|
478
|
+
}
|
|
479
|
+
else {
|
|
480
|
+
// Include all existing properties
|
|
481
|
+
propertiesToInclude = Object.keys(entity);
|
|
482
|
+
}
|
|
483
|
+
// Remove all accumulated excluded properties (exclude takes precedence)
|
|
484
|
+
propertiesToInclude = propertiesToInclude.filter((prop) => !allExclusions.has(prop));
|
|
485
|
+
// Build filtered entity - always include @id
|
|
486
|
+
const filteredEntity = { '@id': entity['@id'] };
|
|
487
|
+
for (const prop of propertiesToInclude) {
|
|
488
|
+
if (prop !== '@id') {
|
|
489
|
+
// Don't overwrite @id
|
|
490
|
+
filteredEntity[prop] = entity[prop];
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return filteredEntity;
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Apply property filtering to all entities in a graph
|
|
497
|
+
*/
|
|
498
|
+
function filterGraphProperties(graph, config) {
|
|
499
|
+
return graph.map((entity) => filterEntityProperties(entity, config));
|
|
500
|
+
}
|
package/package.json
CHANGED
package/types.d.ts
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for the JSON-LD Builder API
|
|
3
|
+
*
|
|
4
|
+
* Provides comprehensive type definitions for the fluent builder interface
|
|
5
|
+
* that maintains compatibility with existing filtering logic while adding
|
|
6
|
+
* new configuration-first approach.
|
|
7
|
+
*/
|
|
8
|
+
import type { JsonLdEntity, JsonLdGraph, PropertyFilterConfig, PropertyFilterRule } from './jsonld-utils';
|
|
9
|
+
export type { JsonLdEntity, JsonLdGraph, PropertyFilterConfig, PropertyFilterRule };
|
|
10
|
+
/**
|
|
11
|
+
* Filter function type for JSON-LD entities
|
|
12
|
+
*/
|
|
13
|
+
export type JsonLdFilter = (entity: JsonLdEntity) => boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Updated filter options with renamed properties for clarity
|
|
16
|
+
*/
|
|
17
|
+
export interface JsonLdFilterOptions {
|
|
18
|
+
/** Include only these entity types */
|
|
19
|
+
includeTypes?: string[];
|
|
20
|
+
/** Exclude these entity types */
|
|
21
|
+
excludeTypes?: string[];
|
|
22
|
+
/** Include only entities with these IDs */
|
|
23
|
+
includeIds?: string[];
|
|
24
|
+
/** Exclude entities with these IDs */
|
|
25
|
+
excludeIds?: string[];
|
|
26
|
+
/** Custom filter function */
|
|
27
|
+
customFilter?: JsonLdFilter;
|
|
28
|
+
/** Maximum number of entities to include */
|
|
29
|
+
maxEntities?: number;
|
|
30
|
+
/** Include only entities with specific properties */
|
|
31
|
+
requiredProperties?: string[];
|
|
32
|
+
/** Exclude entities with specific properties (renamed from excludeProperties) */
|
|
33
|
+
excludeEntitiesWithProperties?: string[];
|
|
34
|
+
/** Root IDs for subgraph extraction */
|
|
35
|
+
subgraphRoots?: string[];
|
|
36
|
+
/** Property-level filtering configuration */
|
|
37
|
+
propertyFilters?: PropertyFilterConfig;
|
|
38
|
+
/** Property filtering rules by entity IDs */
|
|
39
|
+
propertyFiltersByIds?: PropertyFilterByIdRule[];
|
|
40
|
+
/** Property filtering rules by entity types */
|
|
41
|
+
propertyFiltersByTypes?: PropertyFilterByTypeRule[];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Configuration for property filtering by entity IDs
|
|
45
|
+
*/
|
|
46
|
+
export interface PropertyFilterByIdRule {
|
|
47
|
+
/** Entity IDs to apply this rule to */
|
|
48
|
+
entityIds: string[];
|
|
49
|
+
/** Properties to include (if specified, only these are included) */
|
|
50
|
+
include?: string[];
|
|
51
|
+
/** Properties to exclude */
|
|
52
|
+
exclude?: string[];
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Configuration for property filtering by entity types
|
|
56
|
+
*/
|
|
57
|
+
export interface PropertyFilterByTypeRule {
|
|
58
|
+
/** Entity types to apply this rule to */
|
|
59
|
+
entityTypes: string[];
|
|
60
|
+
/** Properties to include (if specified, only these are included) */
|
|
61
|
+
include?: string[];
|
|
62
|
+
/** Properties to exclude */
|
|
63
|
+
exclude?: string[];
|
|
64
|
+
}
|
|
65
|
+
export interface PopulateProperty {
|
|
66
|
+
property: string;
|
|
67
|
+
entities: JsonLdEntity[];
|
|
68
|
+
}
|
|
69
|
+
export interface PopulateConfig {
|
|
70
|
+
[entityId: string]: PopulateProperty[];
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Immutable configuration state for JSON-LD processing
|
|
74
|
+
*/
|
|
75
|
+
export interface JsonLdConfig {
|
|
76
|
+
/** Base graph to process */
|
|
77
|
+
baseGraph?: JsonLdGraph;
|
|
78
|
+
/** Entity filtering options */
|
|
79
|
+
filters?: JsonLdFilterOptions;
|
|
80
|
+
/** Additional entities to include */
|
|
81
|
+
additionalEntities?: JsonLdEntity[];
|
|
82
|
+
/** Custom transformation functions */
|
|
83
|
+
pipes?: PipeFunction[];
|
|
84
|
+
/** Populate configuration (contains data to populate) */
|
|
85
|
+
populateConfig?: PopulateConfig;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Options for the build() method
|
|
89
|
+
*/
|
|
90
|
+
export interface BuildOptions {
|
|
91
|
+
/** Whether to pretty-print the JSON output */
|
|
92
|
+
prettyPrint?: boolean;
|
|
93
|
+
/** Custom context URL (defaults to 'https://schema.org') */
|
|
94
|
+
contextUrl?: string;
|
|
95
|
+
/** Whether to wrap output in a script tag */
|
|
96
|
+
withScriptTag?: boolean;
|
|
97
|
+
/** ID for the script tag (only used if withScriptTag is true) */
|
|
98
|
+
scriptId?: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Custom transformation function type
|
|
102
|
+
*/
|
|
103
|
+
export type PipeFunction = (graph: JsonLdGraph) => JsonLdGraph;
|
|
104
|
+
/**
|
|
105
|
+
* Configuration builder interface (immutable operations)
|
|
106
|
+
*/
|
|
107
|
+
export interface IJsonLdConfigBuilder {
|
|
108
|
+
/** Set the base graph to process */
|
|
109
|
+
baseGraph(graph: JsonLdGraph): this;
|
|
110
|
+
/** Include only entities with these IDs */
|
|
111
|
+
includeIds(ids: string[]): this;
|
|
112
|
+
/** Exclude entities with these IDs */
|
|
113
|
+
excludeIds(ids: string[]): this;
|
|
114
|
+
/** Include only these entity types */
|
|
115
|
+
includeTypes(types: string[]): this;
|
|
116
|
+
/** Exclude these entity types */
|
|
117
|
+
excludeTypes(types: string[]): this;
|
|
118
|
+
/** Apply custom filter function */
|
|
119
|
+
customFilter(fn: JsonLdFilter): this;
|
|
120
|
+
/** Limit maximum number of entities */
|
|
121
|
+
maxEntities(max: number): this;
|
|
122
|
+
/** Include only entities with these properties */
|
|
123
|
+
requiredProperties(props: string[]): this;
|
|
124
|
+
/** Exclude entities with these properties */
|
|
125
|
+
excludeEntitiesWithProperties(props: string[]): this;
|
|
126
|
+
/** Extract subgraph starting from these root IDs */
|
|
127
|
+
subgraph(rootIds: string[]): this;
|
|
128
|
+
/** Filter properties for specific entity IDs */
|
|
129
|
+
filterPropertiesByIds(entityIds: string[], rule: {
|
|
130
|
+
include?: string[];
|
|
131
|
+
exclude?: string[];
|
|
132
|
+
}): this;
|
|
133
|
+
/** Filter properties for specific entity types */
|
|
134
|
+
filterPropertiesByTypes(entityTypes: string[], rule: {
|
|
135
|
+
include?: string[];
|
|
136
|
+
exclude?: string[];
|
|
137
|
+
}): this;
|
|
138
|
+
/** Add additional entities */
|
|
139
|
+
addEntities(entities: JsonLdEntity[]): this;
|
|
140
|
+
/** Add custom transformation pipe */
|
|
141
|
+
pipe(fn: PipeFunction): this;
|
|
142
|
+
/** Configure entity population */
|
|
143
|
+
populateEntities(entityIds: string[], populateConfig: PopulateConfig): this;
|
|
144
|
+
/** Clear both includeIds and excludeIds */
|
|
145
|
+
clearIds(): this;
|
|
146
|
+
/** Clear both includeTypes and excludeTypes */
|
|
147
|
+
clearTypes(): this;
|
|
148
|
+
/** Clear both requiredProperties and excludeEntitiesWithProperties */
|
|
149
|
+
clearPropertyRequirements(): this;
|
|
150
|
+
/** Clear both propertyFiltersByIds and propertyFiltersByTypes */
|
|
151
|
+
clearPropertyFilters(): this;
|
|
152
|
+
/** Clear subgraphRoots */
|
|
153
|
+
clearSubgraph(): this;
|
|
154
|
+
/** Clear entire configuration except baseGraph */
|
|
155
|
+
clearAll(): this;
|
|
156
|
+
/** Merge with another configuration */
|
|
157
|
+
mergeConfig(config: JsonLdConfig): this;
|
|
158
|
+
/** Merge only the filters part of another configuration */
|
|
159
|
+
mergeFilters(filters: JsonLdFilterOptions): this;
|
|
160
|
+
/** Get the current configuration */
|
|
161
|
+
getConfig(): JsonLdConfig;
|
|
162
|
+
}
|
package/types.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Types for the JSON-LD Builder API
|
|
4
|
+
*
|
|
5
|
+
* Provides comprehensive type definitions for the fluent builder interface
|
|
6
|
+
* that maintains compatibility with existing filtering logic while adding
|
|
7
|
+
* new configuration-first approach.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|