jsonldjs 0.1.0 → 0.1.1

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/builder.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * JSON-LD Builder with fluent interface
3
+ *
4
+ * Provides a mutable builder that applies configurations and processes graphs.
5
+ * Supports runtime overrides and maintains the complex filtering logic from
6
+ * the current head-manager system.
7
+ */
8
+ import { JsonLdConfigBuilder } from './config';
9
+ import { type JsonLdGraph } from './jsonld-utils';
10
+ import type { BuildOptions, JsonLdConfig } from './types';
11
+ /**
12
+ * Mutable builder class that extends config builder with automatic method delegation
13
+ */
14
+ export declare class JsonLdBuilder extends JsonLdConfigBuilder {
15
+ private currentGraph?;
16
+ constructor(initialConfig?: JsonLdConfig);
17
+ /**
18
+ * Override the config builder's method creation to return JsonLdBuilder instances
19
+ */
20
+ protected createInstance(config: JsonLdConfig): JsonLdBuilder;
21
+ /**
22
+ * Apply a pre-built configuration (builder-specific method)
23
+ */
24
+ applyConfig(config: JsonLdConfig): JsonLdBuilder;
25
+ /**
26
+ * Get the current graph state (processes the graph if not already done)
27
+ */
28
+ getCurrentGraph(): JsonLdGraph;
29
+ /**
30
+ * Build the final JSON-LD output
31
+ * @param options - Build configuration options
32
+ * @param options.prettyPrint - Whether to format JSON with indentation (default: true)
33
+ * @param options.contextUrl - The JSON-LD context URL (default: 'https://schema.org')
34
+ * @param options.withScriptTag - Whether to wrap output in a script tag (default: false)
35
+ * @param options.scriptId - Optional ID attribute for the script tag
36
+ * @returns The JSON-LD string, optionally wrapped in a script tag
37
+ */
38
+ build(options?: BuildOptions): string;
39
+ /**
40
+ * Process the graph according to the current configuration
41
+ * This implements the critical filtering logic from the current manager
42
+ */
43
+ private processGraph;
44
+ }
45
+ /**
46
+ * Factory function to create a new builder
47
+ */
48
+ export declare function createJsonLdBuilder(): JsonLdBuilder;
package/builder.js ADDED
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ /**
3
+ * JSON-LD Builder with fluent interface
4
+ *
5
+ * Provides a mutable builder that applies configurations and processes graphs.
6
+ * Supports runtime overrides and maintains the complex filtering logic from
7
+ * the current head-manager system.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JsonLdBuilder = void 0;
11
+ exports.createJsonLdBuilder = createJsonLdBuilder;
12
+ const config_1 = require("./config");
13
+ const jsonld_utils_1 = require("./jsonld-utils");
14
+ const builder_utils_1 = require("./builder-utils");
15
+ /**
16
+ * Mutable builder class that extends config builder with automatic method delegation
17
+ */
18
+ class JsonLdBuilder extends config_1.JsonLdConfigBuilder {
19
+ constructor(initialConfig = {}) {
20
+ super(initialConfig);
21
+ }
22
+ /**
23
+ * Override the config builder's method creation to return JsonLdBuilder instances
24
+ */
25
+ createInstance(config) {
26
+ return new JsonLdBuilder(config);
27
+ }
28
+ /**
29
+ * Apply a pre-built configuration (builder-specific method)
30
+ */
31
+ applyConfig(config) {
32
+ const currentConfig = this.getConfig();
33
+ const mergedConfig = (0, builder_utils_1.mergeConfigs)(currentConfig, config);
34
+ return new JsonLdBuilder(mergedConfig);
35
+ }
36
+ /**
37
+ * Get the current graph state (processes the graph if not already done)
38
+ */
39
+ getCurrentGraph() {
40
+ if (!this.currentGraph) {
41
+ this.currentGraph = this.processGraph();
42
+ }
43
+ return this.currentGraph;
44
+ }
45
+ /**
46
+ * Build the final JSON-LD output
47
+ * @param options - Build configuration options
48
+ * @param options.prettyPrint - Whether to format JSON with indentation (default: true)
49
+ * @param options.contextUrl - The JSON-LD context URL (default: 'https://schema.org')
50
+ * @param options.withScriptTag - Whether to wrap output in a script tag (default: false)
51
+ * @param options.scriptId - Optional ID attribute for the script tag
52
+ * @returns The JSON-LD string, optionally wrapped in a script tag
53
+ */
54
+ build(options = {}) {
55
+ const { prettyPrint = true, contextUrl = 'https://schema.org', withScriptTag = false, scriptId, } = options;
56
+ const graph = this.getCurrentGraph();
57
+ // Create the JSON-LD object
58
+ const jsonLd = {
59
+ '@context': contextUrl,
60
+ '@graph': graph,
61
+ };
62
+ // Stringify with optional pretty printing
63
+ const jsonString = JSON.stringify(jsonLd, null, prettyPrint ? 2 : undefined);
64
+ // Wrap in script tag if requested
65
+ if (withScriptTag) {
66
+ const idAttribute = scriptId ? ` id="${scriptId}"` : '';
67
+ return `<script${idAttribute} type="application/ld+json">${jsonString}</script>`;
68
+ }
69
+ return jsonString;
70
+ }
71
+ /**
72
+ * Process the graph according to the current configuration
73
+ * This implements the critical filtering logic from the current manager
74
+ */
75
+ processGraph() {
76
+ const config = this.getConfig();
77
+ if (!config.baseGraph) {
78
+ throw new Error('No base graph provided. Use baseGraph() or applyConfig() with a baseGraph.');
79
+ }
80
+ // Validate configuration - only check for critical errors that would break processing
81
+ const errors = (0, builder_utils_1.validateRuntimeConfig)(config);
82
+ if (errors.length > 0) {
83
+ throw new Error(`Configuration validation failed: ${errors.join(', ')}`);
84
+ }
85
+ let graph = [...config.baseGraph];
86
+ const propertyFilters = (0, builder_utils_1.buildPropertyFilterConfig)(config);
87
+ let propertyFiltersApplied = false;
88
+ // Layer 1: Subgraph extraction with property filtering if subgraphRoots are set
89
+ if (config.subgraphRoots && config.subgraphRoots.length > 0) {
90
+ // Extract subgraph with property filtering during traversal
91
+ graph = (0, jsonld_utils_1.extractSubgraphs)(graph, config.subgraphRoots, propertyFilters);
92
+ propertyFiltersApplied = true; // Property filters were applied during subgraph extraction
93
+ }
94
+ // Layer 2: Regular entity filtering with property filtering if not already applied
95
+ if (config.filters) {
96
+ // Apply property filters first if they haven't been applied yet
97
+ if (!propertyFiltersApplied && propertyFilters) {
98
+ graph = (0, jsonld_utils_1.filterGraphProperties)(graph, propertyFilters);
99
+ propertyFiltersApplied = true;
100
+ }
101
+ // Apply entity-level filters
102
+ graph = (0, builder_utils_1.filterJsonLdGraph)(graph, config.filters);
103
+ }
104
+ // Apply entity population if configured
105
+ if (config.populateConfig) {
106
+ graph = (0, builder_utils_1.applyPopulateConfig)(graph, config.populateConfig);
107
+ }
108
+ // Add additional entities if specified
109
+ if (config.additionalEntities && config.additionalEntities.length > 0) {
110
+ graph = [...graph, ...config.additionalEntities];
111
+ }
112
+ // Apply custom transformation pipes
113
+ if (config.pipes && config.pipes.length > 0) {
114
+ for (const pipe of config.pipes) {
115
+ graph = pipe(graph);
116
+ }
117
+ }
118
+ return graph;
119
+ }
120
+ }
121
+ exports.JsonLdBuilder = JsonLdBuilder;
122
+ /**
123
+ * Factory function to create a new builder
124
+ */
125
+ function createJsonLdBuilder() {
126
+ return new JsonLdBuilder();
127
+ }
package/config.d.ts ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Immutable configuration builder for JSON-LD processing
3
+ *
4
+ * Provides a fluent interface for building configurations without
5
+ * performing any graph processing. Each method returns a new
6
+ * configuration object for safe reuse and extension.
7
+ */
8
+ import type { IJsonLdConfigBuilder, JsonLdConfig, JsonLdEntity, JsonLdFilter, JsonLdGraph, PipeFunction, PopulateConfig } from './types';
9
+ /**
10
+ * Immutable configuration builder class
11
+ */
12
+ export declare class JsonLdConfigBuilder implements IJsonLdConfigBuilder {
13
+ private config;
14
+ constructor(initialConfig?: JsonLdConfig);
15
+ /**
16
+ * Create a new instance of this class (can be overridden by subclasses)
17
+ */
18
+ protected createInstance(config: JsonLdConfig): JsonLdConfigBuilder;
19
+ /**
20
+ * Set the base graph to process
21
+ */
22
+ baseGraph(graph: JsonLdGraph): this;
23
+ /**
24
+ * Include only entities with these IDs (merges with existing IDs)
25
+ */
26
+ includeIds(ids: string[]): this;
27
+ /**
28
+ * Exclude entities with these IDs (merges with existing IDs)
29
+ */
30
+ excludeIds(ids: string[]): this;
31
+ /**
32
+ * Include only these entity types (merges with existing types)
33
+ */
34
+ includeTypes(types: string[]): this;
35
+ /**
36
+ * Exclude these entity types (merges with existing types)
37
+ */
38
+ excludeTypes(types: string[]): this;
39
+ /**
40
+ * Apply custom filter function
41
+ */
42
+ customFilter(fn: JsonLdFilter): this;
43
+ /**
44
+ * Limit maximum number of entities
45
+ */
46
+ maxEntities(max: number): this;
47
+ /**
48
+ * Include only entities with these properties (merges with existing properties)
49
+ * @param props - Array of property names that entities must have
50
+ * @example
51
+ * ```typescript
52
+ * config.requiredProperties(['name']).requiredProperties(['url'])
53
+ * // Result: entities must have both 'name' and 'url' properties
54
+ * ```
55
+ */
56
+ requiredProperties(props: string[]): this;
57
+ /**
58
+ * Exclude entities with these properties (merges with existing properties)
59
+ */
60
+ excludeEntitiesWithProperties(props: string[]): this;
61
+ /**
62
+ * Extract subgraph starting from these root IDs
63
+ */
64
+ subgraph(rootIds: string[]): this;
65
+ /**
66
+ * Filter properties for specific entity IDs
67
+ */
68
+ filterPropertiesByIds(entityIds: string[], rule: {
69
+ include?: string[];
70
+ exclude?: string[];
71
+ }): this;
72
+ /**
73
+ * Filter properties for specific entity types
74
+ */
75
+ filterPropertiesByTypes(entityTypes: string[], rule: {
76
+ include?: string[];
77
+ exclude?: string[];
78
+ }): this;
79
+ /**
80
+ * Add additional entities
81
+ */
82
+ addEntities(entities: JsonLdEntity[]): this;
83
+ /**
84
+ * Add custom transformation pipe
85
+ */
86
+ pipe(fn: PipeFunction): this;
87
+ /**
88
+ * Configure entity population
89
+ */
90
+ populateEntities(entityIds: string[], populateConfig: PopulateConfig): this;
91
+ /**
92
+ * Clear both includeIds and excludeIds
93
+ * @example
94
+ * ```typescript
95
+ * config.includeIds(['a']).excludeIds(['b']).clearIds().includeIds(['c'])
96
+ * // Result: only includes 'c', previous IDs are cleared
97
+ * ```
98
+ */
99
+ clearIds(): this;
100
+ /**
101
+ * Clear both includeTypes and excludeTypes
102
+ */
103
+ clearTypes(): this;
104
+ /**
105
+ * Clear both requiredProperties and excludeEntitiesWithProperties
106
+ */
107
+ clearPropertyRequirements(): this;
108
+ /**
109
+ * Clear both propertyFiltersByIds and propertyFiltersByTypes
110
+ */
111
+ clearPropertyFilters(): this;
112
+ /**
113
+ * Clear subgraphRoots
114
+ */
115
+ clearSubgraph(): this;
116
+ /**
117
+ * Clear entire configuration except baseGraph
118
+ * @example
119
+ * ```typescript
120
+ * config.baseGraph(graph).includeIds(['a']).clearAll().includeTypes(['Person'])
121
+ * // Result: only baseGraph and includeTypes remain
122
+ * ```
123
+ */
124
+ clearAll(): this;
125
+ /**
126
+ * Get the current configuration
127
+ */
128
+ getConfig(): JsonLdConfig;
129
+ }
130
+ /**
131
+ * Factory function to create a new configuration builder
132
+ */
133
+ export declare function createJsonLdConfig(): JsonLdConfigBuilder;
package/config.js ADDED
@@ -0,0 +1,306 @@
1
+ "use strict";
2
+ /**
3
+ * Immutable configuration builder for JSON-LD processing
4
+ *
5
+ * Provides a fluent interface for building configurations without
6
+ * performing any graph processing. Each method returns a new
7
+ * configuration object for safe reuse and extension.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.JsonLdConfigBuilder = void 0;
11
+ exports.createJsonLdConfig = createJsonLdConfig;
12
+ /**
13
+ * Immutable configuration builder class
14
+ */
15
+ class JsonLdConfigBuilder {
16
+ constructor(initialConfig = {}) {
17
+ this.config = { ...initialConfig };
18
+ }
19
+ /**
20
+ * Create a new instance of this class (can be overridden by subclasses)
21
+ */
22
+ createInstance(config) {
23
+ return new JsonLdConfigBuilder(config);
24
+ }
25
+ /**
26
+ * Set the base graph to process
27
+ */
28
+ baseGraph(graph) {
29
+ return this.createInstance({
30
+ ...this.config,
31
+ baseGraph: graph,
32
+ });
33
+ }
34
+ /**
35
+ * Include only entities with these IDs (merges with existing IDs)
36
+ */
37
+ includeIds(ids) {
38
+ const existingIds = this.config.filters?.includeIds || [];
39
+ return this.createInstance({
40
+ ...this.config,
41
+ filters: {
42
+ ...this.config.filters,
43
+ includeIds: [...existingIds, ...ids],
44
+ },
45
+ });
46
+ }
47
+ /**
48
+ * Exclude entities with these IDs (merges with existing IDs)
49
+ */
50
+ excludeIds(ids) {
51
+ const existingIds = this.config.filters?.excludeIds || [];
52
+ return this.createInstance({
53
+ ...this.config,
54
+ filters: {
55
+ ...this.config.filters,
56
+ excludeIds: [...existingIds, ...ids],
57
+ },
58
+ });
59
+ }
60
+ /**
61
+ * Include only these entity types (merges with existing types)
62
+ */
63
+ includeTypes(types) {
64
+ const existingTypes = this.config.filters?.includeTypes || [];
65
+ return this.createInstance({
66
+ ...this.config,
67
+ filters: {
68
+ ...this.config.filters,
69
+ includeTypes: [...existingTypes, ...types],
70
+ },
71
+ });
72
+ }
73
+ /**
74
+ * Exclude these entity types (merges with existing types)
75
+ */
76
+ excludeTypes(types) {
77
+ const existingTypes = this.config.filters?.excludeTypes || [];
78
+ return this.createInstance({
79
+ ...this.config,
80
+ filters: {
81
+ ...this.config.filters,
82
+ excludeTypes: [...existingTypes, ...types],
83
+ },
84
+ });
85
+ }
86
+ /**
87
+ * Apply custom filter function
88
+ */
89
+ customFilter(fn) {
90
+ return this.createInstance({
91
+ ...this.config,
92
+ filters: {
93
+ ...this.config.filters,
94
+ customFilter: fn,
95
+ },
96
+ });
97
+ }
98
+ /**
99
+ * Limit maximum number of entities
100
+ */
101
+ maxEntities(max) {
102
+ return this.createInstance({
103
+ ...this.config,
104
+ filters: {
105
+ ...this.config.filters,
106
+ maxEntities: max,
107
+ },
108
+ });
109
+ }
110
+ /**
111
+ * Include only entities with these properties (merges with existing properties)
112
+ * @param props - Array of property names that entities must have
113
+ * @example
114
+ * ```typescript
115
+ * config.requiredProperties(['name']).requiredProperties(['url'])
116
+ * // Result: entities must have both 'name' and 'url' properties
117
+ * ```
118
+ */
119
+ requiredProperties(props) {
120
+ const existingProps = this.config.filters?.requiredProperties || [];
121
+ return this.createInstance({
122
+ ...this.config,
123
+ filters: {
124
+ ...this.config.filters,
125
+ requiredProperties: [...existingProps, ...props],
126
+ },
127
+ });
128
+ }
129
+ /**
130
+ * Exclude entities with these properties (merges with existing properties)
131
+ */
132
+ excludeEntitiesWithProperties(props) {
133
+ const existingProps = this.config.filters?.excludeEntitiesWithProperties || [];
134
+ return this.createInstance({
135
+ ...this.config,
136
+ filters: {
137
+ ...this.config.filters,
138
+ excludeEntitiesWithProperties: [...existingProps, ...props],
139
+ },
140
+ });
141
+ }
142
+ /**
143
+ * Extract subgraph starting from these root IDs
144
+ */
145
+ subgraph(rootIds) {
146
+ return this.createInstance({
147
+ ...this.config,
148
+ subgraphRoots: [...(this.config?.subgraphRoots || []), ...rootIds],
149
+ });
150
+ }
151
+ /**
152
+ * Filter properties for specific entity IDs
153
+ */
154
+ filterPropertiesByIds(entityIds, rule) {
155
+ const existingRules = this.config.propertyFiltersByIds || [];
156
+ const newRule = {
157
+ entityIds,
158
+ ...rule,
159
+ };
160
+ return this.createInstance({
161
+ ...this.config,
162
+ propertyFiltersByIds: [...existingRules, newRule],
163
+ });
164
+ }
165
+ /**
166
+ * Filter properties for specific entity types
167
+ */
168
+ filterPropertiesByTypes(entityTypes, rule) {
169
+ const existingRules = this.config.propertyFiltersByTypes || [];
170
+ const newRule = {
171
+ entityTypes,
172
+ ...rule,
173
+ };
174
+ return this.createInstance({
175
+ ...this.config,
176
+ propertyFiltersByTypes: [...existingRules, newRule],
177
+ });
178
+ }
179
+ /**
180
+ * Add additional entities
181
+ */
182
+ addEntities(entities) {
183
+ const existingEntities = this.config.additionalEntities || [];
184
+ return this.createInstance({
185
+ ...this.config,
186
+ additionalEntities: [...existingEntities, ...entities],
187
+ });
188
+ }
189
+ /**
190
+ * Add custom transformation pipe
191
+ */
192
+ pipe(fn) {
193
+ const existingPipes = this.config.pipes || [];
194
+ return this.createInstance({
195
+ ...this.config,
196
+ pipes: [...existingPipes, fn],
197
+ });
198
+ }
199
+ /**
200
+ * Configure entity population
201
+ */
202
+ populateEntities(entityIds, populateConfig) {
203
+ // Merge with existing populate config
204
+ const existingPopulateConfig = this.config.populateConfig || {};
205
+ const mergedPopulateConfig = { ...existingPopulateConfig };
206
+ // Add the new populate config for the specified entity IDs
207
+ for (const entityId of entityIds) {
208
+ if (populateConfig[entityId]) {
209
+ mergedPopulateConfig[entityId] = populateConfig[entityId];
210
+ }
211
+ }
212
+ return this.createInstance({
213
+ ...this.config,
214
+ populateConfig: mergedPopulateConfig,
215
+ });
216
+ }
217
+ /**
218
+ * Clear both includeIds and excludeIds
219
+ * @example
220
+ * ```typescript
221
+ * config.includeIds(['a']).excludeIds(['b']).clearIds().includeIds(['c'])
222
+ * // Result: only includes 'c', previous IDs are cleared
223
+ * ```
224
+ */
225
+ clearIds() {
226
+ return this.createInstance({
227
+ ...this.config,
228
+ filters: {
229
+ ...this.config.filters,
230
+ includeIds: undefined,
231
+ excludeIds: undefined,
232
+ },
233
+ });
234
+ }
235
+ /**
236
+ * Clear both includeTypes and excludeTypes
237
+ */
238
+ clearTypes() {
239
+ return this.createInstance({
240
+ ...this.config,
241
+ filters: {
242
+ ...this.config.filters,
243
+ includeTypes: undefined,
244
+ excludeTypes: undefined,
245
+ },
246
+ });
247
+ }
248
+ /**
249
+ * Clear both requiredProperties and excludeEntitiesWithProperties
250
+ */
251
+ clearPropertyRequirements() {
252
+ return this.createInstance({
253
+ ...this.config,
254
+ filters: {
255
+ ...this.config.filters,
256
+ requiredProperties: undefined,
257
+ excludeEntitiesWithProperties: undefined,
258
+ },
259
+ });
260
+ }
261
+ /**
262
+ * Clear both propertyFiltersByIds and propertyFiltersByTypes
263
+ */
264
+ clearPropertyFilters() {
265
+ return this.createInstance({
266
+ ...this.config,
267
+ propertyFiltersByIds: undefined,
268
+ propertyFiltersByTypes: undefined,
269
+ });
270
+ }
271
+ /**
272
+ * Clear subgraphRoots
273
+ */
274
+ clearSubgraph() {
275
+ return this.createInstance({
276
+ ...this.config,
277
+ subgraphRoots: undefined,
278
+ });
279
+ }
280
+ /**
281
+ * Clear entire configuration except baseGraph
282
+ * @example
283
+ * ```typescript
284
+ * config.baseGraph(graph).includeIds(['a']).clearAll().includeTypes(['Person'])
285
+ * // Result: only baseGraph and includeTypes remain
286
+ * ```
287
+ */
288
+ clearAll() {
289
+ return this.createInstance({
290
+ baseGraph: this.config.baseGraph,
291
+ });
292
+ }
293
+ /**
294
+ * Get the current configuration
295
+ */
296
+ getConfig() {
297
+ return { ...this.config };
298
+ }
299
+ }
300
+ exports.JsonLdConfigBuilder = JsonLdConfigBuilder;
301
+ /**
302
+ * Factory function to create a new configuration builder
303
+ */
304
+ function createJsonLdConfig() {
305
+ return new JsonLdConfigBuilder();
306
+ }