@lorion-org/descriptor-discovery 1.0.0-beta.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the 'Software'), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @lorion-org/descriptor-discovery
2
+
3
+ Disk-based discovery and normalization helpers for descriptor files.
4
+
5
+ This package is the Node-side companion to `@lorion-org/composition-graph`.
6
+ It is responsible for reading descriptor documents from disk and flattening
7
+ optional nested descriptor authoring into the flat `Descriptor[]` shape that
8
+ the graph core expects.
9
+
10
+ ## Install
11
+
12
+ ```shell
13
+ pnpm add @lorion-org/descriptor-discovery @lorion-org/composition-graph
14
+ ```
15
+
16
+ ## What it is
17
+
18
+ - a Node-side descriptor file discovery helper
19
+ - a normalization layer for descriptor ids and versions
20
+ - a small flattening helper for one level of nested descriptor authoring
21
+ - a bridge from files on disk to `@lorion-org/composition-graph`
22
+
23
+ ## What it is not
24
+
25
+ - not a graph builder
26
+ - not a package manager
27
+ - not a framework adapter
28
+ - not a recursive schema language
29
+ - not a watcher or live reload system
30
+
31
+ ## Directory shape
32
+
33
+ ```text
34
+ descriptors/
35
+ billing/
36
+ descriptor.json
37
+ dashboard/
38
+ descriptor.json
39
+ ```
40
+
41
+ ## Basic example
42
+
43
+ ```ts
44
+ import { discoverDescriptors } from '@lorion-org/descriptor-discovery';
45
+
46
+ const discovered = discoverDescriptors({
47
+ roots: ['./descriptors'],
48
+ });
49
+
50
+ const descriptors = discovered.map((entry) => entry.descriptor);
51
+ ```
52
+
53
+ `discoverDescriptors()` scans each direct child directory below every root and
54
+ loads a descriptor file when it exists. The directory name is used as a fallback
55
+ id when the descriptor does not define one.
56
+
57
+ ## Example: custom descriptor fields
58
+
59
+ ```ts
60
+ import { discoverDescriptors } from '@lorion-org/descriptor-discovery';
61
+
62
+ const discovered = discoverDescriptors({
63
+ roots: ['./modules'],
64
+ descriptorFileName: 'module.json',
65
+ idField: 'name',
66
+ nestedField: 'bundles',
67
+ });
68
+
69
+ discovered.map((entry) => entry.id);
70
+ ```
71
+
72
+ Nested descriptors are flattened into the same output list as their parent.
73
+ Only one nesting level is supported so the resulting graph input stays explicit.
74
+
75
+ ## Example: use with composition graph
76
+
77
+ ```ts
78
+ import { createDescriptorCatalog } from '@lorion-org/composition-graph';
79
+ import { discoverDescriptors } from '@lorion-org/descriptor-discovery';
80
+
81
+ const discovered = discoverDescriptors({
82
+ roots: ['./descriptors'],
83
+ });
84
+
85
+ const catalog = createDescriptorCatalog({
86
+ descriptors: discovered.map((entry) => entry.descriptor),
87
+ });
88
+
89
+ catalog.resolveSelection({
90
+ selected: ['billing'],
91
+ });
92
+ ```
93
+
94
+ ## Local commands
95
+
96
+ ```shell
97
+ cd packages/descriptor-discovery
98
+ pnpm build
99
+ pnpm test
100
+ pnpm typecheck
101
+ pnpm package:check
102
+ ```
@@ -0,0 +1,49 @@
1
+ // src/descriptor.schema.json
2
+ var descriptor_schema_default = {
3
+ $schema: "http://json-schema.org/draft-07/schema#",
4
+ $id: "https://lorion.dev/schemas/descriptor.schema.json",
5
+ $ref: "#/$defs/descriptor",
6
+ $defs: {
7
+ semver: {
8
+ type: "string",
9
+ pattern: "^(\\^|~)?\\d+\\.\\d+\\.\\d+$"
10
+ },
11
+ dependencyMap: {
12
+ type: "object",
13
+ additionalProperties: { $ref: "#/$defs/semver" }
14
+ },
15
+ descriptor: {
16
+ type: "object",
17
+ properties: {
18
+ id: {
19
+ type: "string",
20
+ minLength: 1
21
+ },
22
+ version: { $ref: "#/$defs/semver" },
23
+ providesFor: {
24
+ type: "string",
25
+ minLength: 1
26
+ },
27
+ capabilities: {
28
+ type: "array",
29
+ items: {
30
+ type: "string",
31
+ minLength: 1
32
+ }
33
+ },
34
+ dependencies: { $ref: "#/$defs/dependencyMap" },
35
+ disabled: { type: "boolean" },
36
+ location: { type: "string" }
37
+ },
38
+ required: ["id", "version"],
39
+ additionalProperties: true
40
+ }
41
+ }
42
+ };
43
+
44
+ // src/schema.ts
45
+ var descriptorSchema = descriptor_schema_default;
46
+
47
+ export {
48
+ descriptorSchema
49
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,298 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ descriptorSchema: () => descriptorSchema,
34
+ discoverDescriptors: () => discoverDescriptors,
35
+ expandNestedDescriptors: () => expandNestedDescriptors
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+ var import_node_fs = require("fs");
39
+ var import_node_path = require("path");
40
+ var import_ajv = __toESM(require("ajv"), 1);
41
+
42
+ // src/descriptor.schema.json
43
+ var descriptor_schema_default = {
44
+ $schema: "http://json-schema.org/draft-07/schema#",
45
+ $id: "https://lorion.dev/schemas/descriptor.schema.json",
46
+ $ref: "#/$defs/descriptor",
47
+ $defs: {
48
+ semver: {
49
+ type: "string",
50
+ pattern: "^(\\^|~)?\\d+\\.\\d+\\.\\d+$"
51
+ },
52
+ dependencyMap: {
53
+ type: "object",
54
+ additionalProperties: { $ref: "#/$defs/semver" }
55
+ },
56
+ descriptor: {
57
+ type: "object",
58
+ properties: {
59
+ id: {
60
+ type: "string",
61
+ minLength: 1
62
+ },
63
+ version: { $ref: "#/$defs/semver" },
64
+ providesFor: {
65
+ type: "string",
66
+ minLength: 1
67
+ },
68
+ capabilities: {
69
+ type: "array",
70
+ items: {
71
+ type: "string",
72
+ minLength: 1
73
+ }
74
+ },
75
+ dependencies: { $ref: "#/$defs/dependencyMap" },
76
+ disabled: { type: "boolean" },
77
+ location: { type: "string" }
78
+ },
79
+ required: ["id", "version"],
80
+ additionalProperties: true
81
+ }
82
+ }
83
+ };
84
+
85
+ // src/schema.ts
86
+ var descriptorSchema = descriptor_schema_default;
87
+
88
+ // src/index.ts
89
+ function formatDescriptorSchemaValidationError(target, validationError) {
90
+ const jsonPath = validationError.instancePath || "/";
91
+ const ajvError = `${validationError.keyword}${validationError.message ? `: ${validationError.message}` : ""}`;
92
+ return new Error(
93
+ [
94
+ "Descriptor schema validation failed.",
95
+ `File: ${target.descriptorPath}`,
96
+ `JSON path: ${jsonPath}`,
97
+ `Schema error: ${ajvError}`
98
+ ].join("\n")
99
+ );
100
+ }
101
+ function createDescriptorValidator(options) {
102
+ if (!options) return void 0;
103
+ const ajv = new import_ajv.default({
104
+ strict: false,
105
+ allErrors: false,
106
+ ...options.ajvOptions
107
+ });
108
+ const validate = ajv.compile(options.schema);
109
+ const formatError = options.formatError ?? formatDescriptorSchemaValidationError;
110
+ return (target, descriptor) => {
111
+ if (validate(descriptor)) return;
112
+ const validationError = validate.errors?.[0];
113
+ if (validationError) throw formatError(target, validationError);
114
+ throw new Error(`Descriptor schema validation failed: "${target.descriptorPath}"`);
115
+ };
116
+ }
117
+ function resolveDescriptorId(input) {
118
+ const configuredId = input.rawDescriptor[input.idField];
119
+ if (typeof configuredId === "string" && configuredId.trim()) {
120
+ return configuredId.trim();
121
+ }
122
+ if (typeof input.fallbackId === "string" && input.fallbackId.trim()) {
123
+ return input.fallbackId.trim();
124
+ }
125
+ throw new Error(`${input.label} is missing a non-empty "${input.idField}" field`);
126
+ }
127
+ function getNestedDescriptors(input) {
128
+ if (!input.nestedField) return [];
129
+ const nestedValue = input.rawDescriptor[input.nestedField];
130
+ if (nestedValue === void 0) return [];
131
+ if (!Array.isArray(nestedValue))
132
+ throw new Error(`Descriptor "${input.parentId}" field "${input.nestedField}" must be an array`);
133
+ return nestedValue.map((entry, index) => {
134
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
135
+ throw new Error(
136
+ `Descriptor "${input.parentId}" field "${input.nestedField}" contains an invalid entry at index ${index}`
137
+ );
138
+ }
139
+ return entry;
140
+ });
141
+ }
142
+ function normalizeDescriptor(input) {
143
+ const version = typeof input.rawDescriptor.version === "string" && input.rawDescriptor.version.trim() ? input.rawDescriptor.version : "0.0.0";
144
+ if (input.nestedField) {
145
+ const descriptor = { ...input.rawDescriptor };
146
+ delete descriptor[input.nestedField];
147
+ return {
148
+ ...descriptor,
149
+ id: input.id,
150
+ version
151
+ };
152
+ }
153
+ return {
154
+ ...input.rawDescriptor,
155
+ id: input.id,
156
+ version
157
+ };
158
+ }
159
+ function expandNestedDescriptors(input) {
160
+ const idField = input.idField ?? "id";
161
+ const rootId = resolveDescriptorId({
162
+ rawDescriptor: input.rawDescriptor,
163
+ idField,
164
+ fallbackId: input.fallbackId,
165
+ label: "Descriptor"
166
+ });
167
+ const nestedDescriptors = getNestedDescriptors({
168
+ rawDescriptor: input.rawDescriptor,
169
+ parentId: rootId,
170
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
171
+ });
172
+ const descriptors = [
173
+ normalizeDescriptor({
174
+ rawDescriptor: input.rawDescriptor,
175
+ id: rootId,
176
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
177
+ })
178
+ ];
179
+ for (const nestedDescriptor of nestedDescriptors) {
180
+ const nestedId = resolveDescriptorId({
181
+ rawDescriptor: nestedDescriptor,
182
+ idField,
183
+ label: `Nested descriptor in "${rootId}"`
184
+ });
185
+ const nestedChildren = getNestedDescriptors({
186
+ rawDescriptor: nestedDescriptor,
187
+ parentId: nestedId,
188
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
189
+ });
190
+ if (nestedChildren.length) {
191
+ throw new Error(`Nested descriptors are not supported inside descriptor "${nestedId}"`);
192
+ }
193
+ descriptors.push(
194
+ normalizeDescriptor({
195
+ rawDescriptor: nestedDescriptor,
196
+ id: nestedId,
197
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
198
+ })
199
+ );
200
+ }
201
+ return descriptors;
202
+ }
203
+ function escapeRegex(value) {
204
+ return value.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
205
+ }
206
+ function createGlobSegmentRegex(segment) {
207
+ return new RegExp(`^${segment.split("*").map(escapeRegex).join("[^/\\\\]*")}$`);
208
+ }
209
+ function splitPattern(pattern) {
210
+ return pattern.split(/[\\/]+/).filter(Boolean);
211
+ }
212
+ function expandDescriptorPathPattern(input) {
213
+ const segments = splitPattern(input.pattern);
214
+ const visit = (currentDir, index) => {
215
+ const segment = segments[index];
216
+ if (!segment) return [];
217
+ const isLast = index === segments.length - 1;
218
+ if (!segment.includes("*")) {
219
+ const nextPath = (0, import_node_path.join)(currentDir, segment);
220
+ if (isLast) return (0, import_node_fs.existsSync)(nextPath) ? [nextPath] : [];
221
+ if (!(0, import_node_fs.existsSync)(nextPath)) return [];
222
+ return visit(nextPath, index + 1);
223
+ }
224
+ if (!(0, import_node_fs.existsSync)(currentDir)) return [];
225
+ const matcher = createGlobSegmentRegex(segment);
226
+ return (0, import_node_fs.readdirSync)(currentDir, { withFileTypes: true }).filter((entry) => entry.name !== "node_modules" && matcher.test(entry.name)).flatMap((entry) => {
227
+ const nextPath = (0, import_node_path.join)(currentDir, entry.name);
228
+ if (isLast) return entry.isFile() ? [nextPath] : [];
229
+ return entry.isDirectory() ? visit(nextPath, index + 1) : [];
230
+ });
231
+ };
232
+ return visit((0, import_node_path.resolve)(input.cwd), 0);
233
+ }
234
+ function discoverDescriptorFiles(input) {
235
+ return [
236
+ ...new Set(
237
+ input.descriptorPaths.flatMap(
238
+ (pattern) => expandDescriptorPathPattern({
239
+ cwd: input.cwd,
240
+ pattern
241
+ })
242
+ )
243
+ )
244
+ ].sort();
245
+ }
246
+ function discoverDescriptorFilesFromRoots(input) {
247
+ const discovered = [];
248
+ const visit = (root, depth) => {
249
+ if (depth > input.maxDepth || !(0, import_node_fs.existsSync)(root)) return;
250
+ for (const entry of (0, import_node_fs.readdirSync)(root, { withFileTypes: true })) {
251
+ if (!entry.isDirectory() || entry.name === "node_modules") continue;
252
+ const cwd = (0, import_node_path.join)(root, entry.name);
253
+ const descriptorPath = (0, import_node_path.join)(cwd, input.descriptorFileName);
254
+ if ((0, import_node_fs.existsSync)(descriptorPath)) discovered.push(descriptorPath);
255
+ visit(cwd, depth + 1);
256
+ }
257
+ };
258
+ for (const root of input.roots) {
259
+ visit((0, import_node_path.resolve)(root), 1);
260
+ }
261
+ return [...new Set(discovered)].sort();
262
+ }
263
+ function discoverDescriptors(input) {
264
+ const descriptorFileName = input.descriptorFileName ?? "descriptor.json";
265
+ const idField = input.idField ?? "id";
266
+ const maxDepth = input.maxDepth ?? 1;
267
+ const validateDescriptor = createDescriptorValidator(input.validation);
268
+ const descriptorPaths = input.descriptorPaths?.length ? discoverDescriptorFiles({
269
+ cwd: input.cwd ?? "",
270
+ descriptorPaths: input.descriptorPaths
271
+ }) : discoverDescriptorFilesFromRoots({
272
+ descriptorFileName,
273
+ maxDepth,
274
+ roots: input.roots ?? []
275
+ });
276
+ return descriptorPaths.flatMap((descriptorPath) => {
277
+ const cwd = (0, import_node_path.dirname)(descriptorPath);
278
+ const rawDescriptor = JSON.parse((0, import_node_fs.readFileSync)(descriptorPath, "utf8"));
279
+ validateDescriptor?.({ descriptorPath }, rawDescriptor);
280
+ return expandNestedDescriptors({
281
+ rawDescriptor,
282
+ fallbackId: (0, import_node_path.basename)(cwd),
283
+ idField,
284
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
285
+ }).map((descriptor) => ({
286
+ id: descriptor.id,
287
+ cwd,
288
+ descriptorPath,
289
+ descriptor
290
+ }));
291
+ });
292
+ }
293
+ // Annotate the CommonJS export names for ESM import in node:
294
+ 0 && (module.exports = {
295
+ descriptorSchema,
296
+ discoverDescriptors,
297
+ expandNestedDescriptors
298
+ });
@@ -0,0 +1,42 @@
1
+ import { ErrorObject, Options } from 'ajv';
2
+ import { Descriptor } from '@lorion-org/composition-graph';
3
+ export { JsonSchemaObject, descriptorSchema } from './schema.cjs';
4
+
5
+ type RawDescriptor = Omit<Descriptor, 'id'> & {
6
+ id?: string;
7
+ };
8
+ type DiscoveredDescriptor = {
9
+ id: string;
10
+ cwd: string;
11
+ descriptorPath: string;
12
+ descriptor: Descriptor;
13
+ };
14
+ type DescriptorSchemaValidationTarget = {
15
+ descriptorPath: string;
16
+ };
17
+ type DescriptorSchemaValidationErrorFormatter = (target: DescriptorSchemaValidationTarget, validationError: ErrorObject) => Error;
18
+ type DescriptorValidationOptions = {
19
+ ajvOptions?: Options;
20
+ formatError?: DescriptorSchemaValidationErrorFormatter;
21
+ schema: object;
22
+ };
23
+ type ExpandNestedDescriptorsInput = {
24
+ rawDescriptor: RawDescriptor & Record<string, unknown>;
25
+ fallbackId: string;
26
+ idField?: string;
27
+ nestedField?: string;
28
+ };
29
+ type DiscoverDescriptorsInput = {
30
+ cwd?: string;
31
+ descriptorPaths?: string[];
32
+ roots?: string[];
33
+ descriptorFileName?: string;
34
+ idField?: string;
35
+ maxDepth?: number;
36
+ nestedField?: string;
37
+ validation?: false | DescriptorValidationOptions;
38
+ };
39
+ declare function expandNestedDescriptors(input: ExpandNestedDescriptorsInput): Descriptor[];
40
+ declare function discoverDescriptors(input: DiscoverDescriptorsInput): DiscoveredDescriptor[];
41
+
42
+ export { type DescriptorSchemaValidationErrorFormatter, type DescriptorSchemaValidationTarget, type DescriptorValidationOptions, type DiscoverDescriptorsInput, type DiscoveredDescriptor, type ExpandNestedDescriptorsInput, type RawDescriptor, discoverDescriptors, expandNestedDescriptors };
@@ -0,0 +1,42 @@
1
+ import { ErrorObject, Options } from 'ajv';
2
+ import { Descriptor } from '@lorion-org/composition-graph';
3
+ export { JsonSchemaObject, descriptorSchema } from './schema.js';
4
+
5
+ type RawDescriptor = Omit<Descriptor, 'id'> & {
6
+ id?: string;
7
+ };
8
+ type DiscoveredDescriptor = {
9
+ id: string;
10
+ cwd: string;
11
+ descriptorPath: string;
12
+ descriptor: Descriptor;
13
+ };
14
+ type DescriptorSchemaValidationTarget = {
15
+ descriptorPath: string;
16
+ };
17
+ type DescriptorSchemaValidationErrorFormatter = (target: DescriptorSchemaValidationTarget, validationError: ErrorObject) => Error;
18
+ type DescriptorValidationOptions = {
19
+ ajvOptions?: Options;
20
+ formatError?: DescriptorSchemaValidationErrorFormatter;
21
+ schema: object;
22
+ };
23
+ type ExpandNestedDescriptorsInput = {
24
+ rawDescriptor: RawDescriptor & Record<string, unknown>;
25
+ fallbackId: string;
26
+ idField?: string;
27
+ nestedField?: string;
28
+ };
29
+ type DiscoverDescriptorsInput = {
30
+ cwd?: string;
31
+ descriptorPaths?: string[];
32
+ roots?: string[];
33
+ descriptorFileName?: string;
34
+ idField?: string;
35
+ maxDepth?: number;
36
+ nestedField?: string;
37
+ validation?: false | DescriptorValidationOptions;
38
+ };
39
+ declare function expandNestedDescriptors(input: ExpandNestedDescriptorsInput): Descriptor[];
40
+ declare function discoverDescriptors(input: DiscoverDescriptorsInput): DiscoveredDescriptor[];
41
+
42
+ export { type DescriptorSchemaValidationErrorFormatter, type DescriptorSchemaValidationTarget, type DescriptorValidationOptions, type DiscoverDescriptorsInput, type DiscoveredDescriptor, type ExpandNestedDescriptorsInput, type RawDescriptor, discoverDescriptors, expandNestedDescriptors };
package/dist/index.js ADDED
@@ -0,0 +1,217 @@
1
+ import {
2
+ descriptorSchema
3
+ } from "./chunk-PIMQRGRQ.js";
4
+
5
+ // src/index.ts
6
+ import { existsSync, readFileSync, readdirSync } from "fs";
7
+ import { basename, dirname, join, resolve as resolvePath } from "path";
8
+ import Ajv from "ajv";
9
+ function formatDescriptorSchemaValidationError(target, validationError) {
10
+ const jsonPath = validationError.instancePath || "/";
11
+ const ajvError = `${validationError.keyword}${validationError.message ? `: ${validationError.message}` : ""}`;
12
+ return new Error(
13
+ [
14
+ "Descriptor schema validation failed.",
15
+ `File: ${target.descriptorPath}`,
16
+ `JSON path: ${jsonPath}`,
17
+ `Schema error: ${ajvError}`
18
+ ].join("\n")
19
+ );
20
+ }
21
+ function createDescriptorValidator(options) {
22
+ if (!options) return void 0;
23
+ const ajv = new Ajv({
24
+ strict: false,
25
+ allErrors: false,
26
+ ...options.ajvOptions
27
+ });
28
+ const validate = ajv.compile(options.schema);
29
+ const formatError = options.formatError ?? formatDescriptorSchemaValidationError;
30
+ return (target, descriptor) => {
31
+ if (validate(descriptor)) return;
32
+ const validationError = validate.errors?.[0];
33
+ if (validationError) throw formatError(target, validationError);
34
+ throw new Error(`Descriptor schema validation failed: "${target.descriptorPath}"`);
35
+ };
36
+ }
37
+ function resolveDescriptorId(input) {
38
+ const configuredId = input.rawDescriptor[input.idField];
39
+ if (typeof configuredId === "string" && configuredId.trim()) {
40
+ return configuredId.trim();
41
+ }
42
+ if (typeof input.fallbackId === "string" && input.fallbackId.trim()) {
43
+ return input.fallbackId.trim();
44
+ }
45
+ throw new Error(`${input.label} is missing a non-empty "${input.idField}" field`);
46
+ }
47
+ function getNestedDescriptors(input) {
48
+ if (!input.nestedField) return [];
49
+ const nestedValue = input.rawDescriptor[input.nestedField];
50
+ if (nestedValue === void 0) return [];
51
+ if (!Array.isArray(nestedValue))
52
+ throw new Error(`Descriptor "${input.parentId}" field "${input.nestedField}" must be an array`);
53
+ return nestedValue.map((entry, index) => {
54
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
55
+ throw new Error(
56
+ `Descriptor "${input.parentId}" field "${input.nestedField}" contains an invalid entry at index ${index}`
57
+ );
58
+ }
59
+ return entry;
60
+ });
61
+ }
62
+ function normalizeDescriptor(input) {
63
+ const version = typeof input.rawDescriptor.version === "string" && input.rawDescriptor.version.trim() ? input.rawDescriptor.version : "0.0.0";
64
+ if (input.nestedField) {
65
+ const descriptor = { ...input.rawDescriptor };
66
+ delete descriptor[input.nestedField];
67
+ return {
68
+ ...descriptor,
69
+ id: input.id,
70
+ version
71
+ };
72
+ }
73
+ return {
74
+ ...input.rawDescriptor,
75
+ id: input.id,
76
+ version
77
+ };
78
+ }
79
+ function expandNestedDescriptors(input) {
80
+ const idField = input.idField ?? "id";
81
+ const rootId = resolveDescriptorId({
82
+ rawDescriptor: input.rawDescriptor,
83
+ idField,
84
+ fallbackId: input.fallbackId,
85
+ label: "Descriptor"
86
+ });
87
+ const nestedDescriptors = getNestedDescriptors({
88
+ rawDescriptor: input.rawDescriptor,
89
+ parentId: rootId,
90
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
91
+ });
92
+ const descriptors = [
93
+ normalizeDescriptor({
94
+ rawDescriptor: input.rawDescriptor,
95
+ id: rootId,
96
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
97
+ })
98
+ ];
99
+ for (const nestedDescriptor of nestedDescriptors) {
100
+ const nestedId = resolveDescriptorId({
101
+ rawDescriptor: nestedDescriptor,
102
+ idField,
103
+ label: `Nested descriptor in "${rootId}"`
104
+ });
105
+ const nestedChildren = getNestedDescriptors({
106
+ rawDescriptor: nestedDescriptor,
107
+ parentId: nestedId,
108
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
109
+ });
110
+ if (nestedChildren.length) {
111
+ throw new Error(`Nested descriptors are not supported inside descriptor "${nestedId}"`);
112
+ }
113
+ descriptors.push(
114
+ normalizeDescriptor({
115
+ rawDescriptor: nestedDescriptor,
116
+ id: nestedId,
117
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
118
+ })
119
+ );
120
+ }
121
+ return descriptors;
122
+ }
123
+ function escapeRegex(value) {
124
+ return value.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
125
+ }
126
+ function createGlobSegmentRegex(segment) {
127
+ return new RegExp(`^${segment.split("*").map(escapeRegex).join("[^/\\\\]*")}$`);
128
+ }
129
+ function splitPattern(pattern) {
130
+ return pattern.split(/[\\/]+/).filter(Boolean);
131
+ }
132
+ function expandDescriptorPathPattern(input) {
133
+ const segments = splitPattern(input.pattern);
134
+ const visit = (currentDir, index) => {
135
+ const segment = segments[index];
136
+ if (!segment) return [];
137
+ const isLast = index === segments.length - 1;
138
+ if (!segment.includes("*")) {
139
+ const nextPath = join(currentDir, segment);
140
+ if (isLast) return existsSync(nextPath) ? [nextPath] : [];
141
+ if (!existsSync(nextPath)) return [];
142
+ return visit(nextPath, index + 1);
143
+ }
144
+ if (!existsSync(currentDir)) return [];
145
+ const matcher = createGlobSegmentRegex(segment);
146
+ return readdirSync(currentDir, { withFileTypes: true }).filter((entry) => entry.name !== "node_modules" && matcher.test(entry.name)).flatMap((entry) => {
147
+ const nextPath = join(currentDir, entry.name);
148
+ if (isLast) return entry.isFile() ? [nextPath] : [];
149
+ return entry.isDirectory() ? visit(nextPath, index + 1) : [];
150
+ });
151
+ };
152
+ return visit(resolvePath(input.cwd), 0);
153
+ }
154
+ function discoverDescriptorFiles(input) {
155
+ return [
156
+ ...new Set(
157
+ input.descriptorPaths.flatMap(
158
+ (pattern) => expandDescriptorPathPattern({
159
+ cwd: input.cwd,
160
+ pattern
161
+ })
162
+ )
163
+ )
164
+ ].sort();
165
+ }
166
+ function discoverDescriptorFilesFromRoots(input) {
167
+ const discovered = [];
168
+ const visit = (root, depth) => {
169
+ if (depth > input.maxDepth || !existsSync(root)) return;
170
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
171
+ if (!entry.isDirectory() || entry.name === "node_modules") continue;
172
+ const cwd = join(root, entry.name);
173
+ const descriptorPath = join(cwd, input.descriptorFileName);
174
+ if (existsSync(descriptorPath)) discovered.push(descriptorPath);
175
+ visit(cwd, depth + 1);
176
+ }
177
+ };
178
+ for (const root of input.roots) {
179
+ visit(resolvePath(root), 1);
180
+ }
181
+ return [...new Set(discovered)].sort();
182
+ }
183
+ function discoverDescriptors(input) {
184
+ const descriptorFileName = input.descriptorFileName ?? "descriptor.json";
185
+ const idField = input.idField ?? "id";
186
+ const maxDepth = input.maxDepth ?? 1;
187
+ const validateDescriptor = createDescriptorValidator(input.validation);
188
+ const descriptorPaths = input.descriptorPaths?.length ? discoverDescriptorFiles({
189
+ cwd: input.cwd ?? "",
190
+ descriptorPaths: input.descriptorPaths
191
+ }) : discoverDescriptorFilesFromRoots({
192
+ descriptorFileName,
193
+ maxDepth,
194
+ roots: input.roots ?? []
195
+ });
196
+ return descriptorPaths.flatMap((descriptorPath) => {
197
+ const cwd = dirname(descriptorPath);
198
+ const rawDescriptor = JSON.parse(readFileSync(descriptorPath, "utf8"));
199
+ validateDescriptor?.({ descriptorPath }, rawDescriptor);
200
+ return expandNestedDescriptors({
201
+ rawDescriptor,
202
+ fallbackId: basename(cwd),
203
+ idField,
204
+ ...input.nestedField ? { nestedField: input.nestedField } : {}
205
+ }).map((descriptor) => ({
206
+ id: descriptor.id,
207
+ cwd,
208
+ descriptorPath,
209
+ descriptor
210
+ }));
211
+ });
212
+ }
213
+ export {
214
+ descriptorSchema,
215
+ discoverDescriptors,
216
+ expandNestedDescriptors
217
+ };
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/schema.ts
21
+ var schema_exports = {};
22
+ __export(schema_exports, {
23
+ descriptorSchema: () => descriptorSchema
24
+ });
25
+ module.exports = __toCommonJS(schema_exports);
26
+
27
+ // src/descriptor.schema.json
28
+ var descriptor_schema_default = {
29
+ $schema: "http://json-schema.org/draft-07/schema#",
30
+ $id: "https://lorion.dev/schemas/descriptor.schema.json",
31
+ $ref: "#/$defs/descriptor",
32
+ $defs: {
33
+ semver: {
34
+ type: "string",
35
+ pattern: "^(\\^|~)?\\d+\\.\\d+\\.\\d+$"
36
+ },
37
+ dependencyMap: {
38
+ type: "object",
39
+ additionalProperties: { $ref: "#/$defs/semver" }
40
+ },
41
+ descriptor: {
42
+ type: "object",
43
+ properties: {
44
+ id: {
45
+ type: "string",
46
+ minLength: 1
47
+ },
48
+ version: { $ref: "#/$defs/semver" },
49
+ providesFor: {
50
+ type: "string",
51
+ minLength: 1
52
+ },
53
+ capabilities: {
54
+ type: "array",
55
+ items: {
56
+ type: "string",
57
+ minLength: 1
58
+ }
59
+ },
60
+ dependencies: { $ref: "#/$defs/dependencyMap" },
61
+ disabled: { type: "boolean" },
62
+ location: { type: "string" }
63
+ },
64
+ required: ["id", "version"],
65
+ additionalProperties: true
66
+ }
67
+ }
68
+ };
69
+
70
+ // src/schema.ts
71
+ var descriptorSchema = descriptor_schema_default;
72
+ // Annotate the CommonJS export names for ESM import in node:
73
+ 0 && (module.exports = {
74
+ descriptorSchema
75
+ });
@@ -0,0 +1,4 @@
1
+ type JsonSchemaObject = Record<string, unknown>;
2
+ declare const descriptorSchema: JsonSchemaObject;
3
+
4
+ export { type JsonSchemaObject, descriptorSchema };
@@ -0,0 +1,4 @@
1
+ type JsonSchemaObject = Record<string, unknown>;
2
+ declare const descriptorSchema: JsonSchemaObject;
3
+
4
+ export { type JsonSchemaObject, descriptorSchema };
package/dist/schema.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ descriptorSchema
3
+ } from "./chunk-PIMQRGRQ.js";
4
+ export {
5
+ descriptorSchema
6
+ };
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@lorion-org/descriptor-discovery",
3
+ "version": "1.0.0-beta.0",
4
+ "description": "Node-based descriptor discovery and normalization helpers.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/lorion-org/lorion.git",
9
+ "directory": "packages/descriptor-discovery"
10
+ },
11
+ "homepage": "https://github.com/lorion-org/lorion/tree/main/packages/descriptor-discovery#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/lorion-org/lorion/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "main": "./dist/index.cjs",
21
+ "module": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "import": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "require": {
30
+ "types": "./dist/index.d.cts",
31
+ "default": "./dist/index.cjs"
32
+ }
33
+ },
34
+ "./schema": {
35
+ "import": {
36
+ "types": "./dist/schema.d.ts",
37
+ "default": "./dist/schema.js"
38
+ },
39
+ "require": {
40
+ "types": "./dist/schema.d.cts",
41
+ "default": "./dist/schema.cjs"
42
+ }
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "LICENSE"
48
+ ],
49
+ "keywords": [
50
+ "descriptor",
51
+ "discovery",
52
+ "filesystem",
53
+ "typescript"
54
+ ],
55
+ "engines": {
56
+ "node": "^20.19.0 || >=22.12.0"
57
+ },
58
+ "peerDependencies": {
59
+ "@lorion-org/composition-graph": "^1.0.0-beta.0"
60
+ },
61
+ "dependencies": {
62
+ "ajv": "^8.17.1"
63
+ },
64
+ "devDependencies": {
65
+ "@lorion-org/composition-graph": "1.0.0-beta.0"
66
+ },
67
+ "scripts": {
68
+ "build": "tsup src/index.ts src/schema.ts --format esm,cjs --dts",
69
+ "clean": "rimraf coverage dist tsconfig.tsbuildinfo",
70
+ "lint": "eslint src --ext .ts",
71
+ "package:check": "pnpm build && pnpm pack --dry-run && publint",
72
+ "test": "vitest run --root ../.. --config vitest.config.mts packages/descriptor-discovery/src/index.spec.ts",
73
+ "typecheck": "tsc -p tsconfig.json --noEmit"
74
+ }
75
+ }