@power-plant/core 0.0.25 → 0.0.28

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.
@@ -0,0 +1,461 @@
1
+ import { callAsyncExecutionContext, callAsyncSessionContext } from "./context.mjs";
2
+ import { isGeneratorConfigObject, isInputConfigObject, isOutputConfigObject, isSchemaConfigObject } from "./helpers/type-checks.mjs";
3
+ import { resolveMeta, resolveMetaDescription, resolveMetaExample } from "./helpers/meta.mjs";
4
+ import { uuid } from "@stryke/unique-id/uuid";
5
+ import { getEnvPaths } from "@stryke/env/get-env-paths";
6
+ import { readFileIfExisting } from "@stryke/fs/read-file";
7
+ import { writeFile } from "@stryke/fs/write-file";
8
+ import { joinPaths } from "@stryke/path/join-paths";
9
+ import { isSetString } from "@stryke/type-checks/is-set-string";
10
+ import defu from "defu";
11
+ import os from "node:os";
12
+ import { createStorage } from "unstorage";
13
+ import fsLite from "unstorage/drivers/fs-lite";
14
+ import { mapStorageToFileSystem } from "@power-plant/schema/storage";
15
+ import { load } from "@stryke/resolve/load";
16
+ import { isFunction } from "@stryke/type-checks/is-function";
17
+ import { assertSchemasDoNotContradict, extractSchemaWithSource, mergeMetadata } from "@power-plant/schema";
18
+ import { isLoadReference } from "@stryke/resolve/type-checks";
19
+
20
+ //#region src/lib/context.ts
21
+ const logger = {
22
+ debug: console.debug,
23
+ info: console.info,
24
+ warn: console.warn,
25
+ error: console.error
26
+ };
27
+ const paths = getEnvPaths({
28
+ appId: "power-plant",
29
+ orgId: "storm-software"
30
+ });
31
+ /**
32
+ * Create a session context for the engine.
33
+ *
34
+ * @param session - The session for the context.
35
+ * @param userConfig - The user configuration.
36
+ * @returns A session context.
37
+ */
38
+ async function createSessionContext(userConfig = {}) {
39
+ const cwd = userConfig.cwd || process.cwd();
40
+ const now = /* @__PURE__ */ new Date();
41
+ const storage = createStorage({ driver: fsLite({ base: cwd }) });
42
+ const store = JSON.parse(await readFileIfExisting(joinPaths(paths.data, ".local-store.json")) || "{}");
43
+ const device = store.device || os.hostname() || uuid();
44
+ const user = store.user || os.userInfo().username || uuid();
45
+ if (!isSetString(store.device) || !isSetString(store.user)) await writeFile(joinPaths(paths.data, ".local-store.json"), JSON.stringify({
46
+ device,
47
+ user
48
+ }, null, 2));
49
+ return defu({
50
+ cwd,
51
+ session: {
52
+ id: uuid(),
53
+ createdAt: now,
54
+ updatedAt: now,
55
+ device,
56
+ user,
57
+ executions: []
58
+ }
59
+ }, userConfig, {
60
+ storage,
61
+ settings: {},
62
+ logger
63
+ });
64
+ }
65
+ /**
66
+ * Create an execution context for the engine.
67
+ *
68
+ * @param executionId - The ID of the execution.
69
+ * @param sessionContext - The session context.
70
+ * @param options - The options.
71
+ * @param schema - The schema.
72
+ * @param input - The input.
73
+ * @param output - The output.
74
+ * @returns A promise that resolves to an execution context.
75
+ */
76
+ async function createExecutionContext(executionId, sessionContext, options, schema, input, output) {
77
+ const documents = {};
78
+ const addDocument = (pathOrDocument, document) => {
79
+ if (isSetString(pathOrDocument)) documents[pathOrDocument] = defu({ path: pathOrDocument }, document, {
80
+ chunks: [],
81
+ meta: {}
82
+ });
83
+ else documents[pathOrDocument.path] = defu(pathOrDocument, document);
84
+ };
85
+ let specValue;
86
+ const context = {
87
+ ...sessionContext,
88
+ id: executionId,
89
+ createdAt: /* @__PURE__ */ new Date(),
90
+ updatedAt: /* @__PURE__ */ new Date(),
91
+ options,
92
+ schema,
93
+ input,
94
+ output,
95
+ documents,
96
+ spec() {
97
+ if (!specValue) throw new Error("The specification was accessed prior to the input processing.");
98
+ return specValue;
99
+ },
100
+ addDocument,
101
+ meta: {
102
+ id: executionId,
103
+ executedAt: /* @__PURE__ */ new Date(),
104
+ executedBy: ""
105
+ }
106
+ };
107
+ Object.defineProperty(context, "~spec", {
108
+ get() {
109
+ return specValue;
110
+ },
111
+ set(value) {
112
+ specValue = value;
113
+ },
114
+ enumerable: false
115
+ });
116
+ return context;
117
+ }
118
+
119
+ //#endregion
120
+ //#region src/lib/extract.ts
121
+ async function extractExecution(execution, _spec, _options) {
122
+ return execution;
123
+ }
124
+
125
+ //#endregion
126
+ //#region src/lib/schema.ts
127
+ /**
128
+ * Extracts and normalizes {@link SchemaMetaConfig | schema metadata} from a given {@link SchemaMetaConfig}. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
129
+ *
130
+ * @param schema - The schema from which to extract metadata.
131
+ * @param input - The schema metadata input to extract and normalize.
132
+ * @returns The normalized schema metadata.
133
+ */
134
+ function extractSchemaMeta(schema, input) {
135
+ const jsonSchema = schema?.schema ?? {};
136
+ const meta = resolveMeta(schema, input);
137
+ meta.description = resolveMetaDescription(`Accepts a ${meta.title ?? ""} specification and processes it with a {title} sink.`, jsonSchema, meta, input?.description);
138
+ meta.examples = resolveMetaExample(jsonSchema, meta, input?.examples);
139
+ return meta;
140
+ }
141
+ /**
142
+ * Normalizes any accepted schema input into a concrete schema descriptor.
143
+ *
144
+ * @param input - The schema input to normalize.
145
+ * @param options - Optional options for resolving the schema input.
146
+ * @returns A promise that resolves to a normalized schema descriptor.
147
+ */
148
+ async function createSchema(input, options = {}) {
149
+ const { meta, schema } = isSchemaConfigObject(input) ? input : {
150
+ schema: input,
151
+ meta: {}
152
+ };
153
+ const resolvedSchema = await extractSchemaWithSource(schema, options);
154
+ return {
155
+ ...resolvedSchema,
156
+ meta: extractSchemaMeta(resolvedSchema, meta)
157
+ };
158
+ }
159
+ /**
160
+ * Ensures resolved input/output schema overrides do not contradict the generator schema.
161
+ *
162
+ * @param baseSchema - The resolved generator schema.
163
+ * @param input - The resolved generator input descriptor.
164
+ * @param output - The resolved generator output descriptor.
165
+ */
166
+ function assertGeneratorConfigSchemasDoNotContradict(baseSchema, input, output) {
167
+ if (input && input.schema !== baseSchema) assertSchemasDoNotContradict(baseSchema.schema, input.schema.schema, "input");
168
+ if (output && output.schema !== baseSchema) assertSchemasDoNotContradict(baseSchema.schema, output.schema.schema, "output");
169
+ }
170
+
171
+ //#endregion
172
+ //#region src/lib/input.ts
173
+ /**
174
+ * Extracts and normalizes input metadata from a given configuration. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
175
+ *
176
+ * @param schema - The schema that the input input is expected to conform to.
177
+ * @param input - The input metadata input to extract and normalize.
178
+ * @returns The normalized input metadata.
179
+ */
180
+ function extractInputMeta(schema, input) {
181
+ const jsonSchema = schema?.schema ?? {};
182
+ const meta = resolveMeta(schema, input);
183
+ meta.description = resolveMetaDescription(`Determines the ${meta.title ?? ""} specification from a {title} input.`, jsonSchema, meta, input?.description);
184
+ return meta;
185
+ }
186
+ /**
187
+ * Normalizes any accepted input configuration into a concrete input descriptor.
188
+ *
189
+ * @param schema - The schema that the specification is expected to conform to.
190
+ * @param config - The input configuration to normalize.
191
+ * @param options - Optional options for resolving the input configuration.
192
+ * @returns A promise that resolves to a normalized input descriptor.
193
+ */
194
+ async function createInput(schema, config, options = {}) {
195
+ const { input, meta, schema: inputSchema } = isInputConfigObject(config) ? config : {
196
+ input: config,
197
+ meta: {}
198
+ };
199
+ let resolvedSchema = schema;
200
+ if (inputSchema) {
201
+ let resolvedInputSchema;
202
+ if (isLoadReference(inputSchema)) try {
203
+ resolvedInputSchema = await load(inputSchema, options);
204
+ } catch {}
205
+ else resolvedInputSchema = inputSchema;
206
+ if (resolvedInputSchema) {
207
+ resolvedSchema = await createSchema(resolvedInputSchema, options);
208
+ resolvedSchema.schema = mergeMetadata(resolvedSchema.schema, schema.schema);
209
+ }
210
+ }
211
+ let resolvedInput;
212
+ if (isLoadReference(input)) try {
213
+ const loaded = await load(input, options);
214
+ if (isInputConfigObject(loaded)) resolvedInput = await createInput(resolvedSchema, loaded.input, options).then((s) => s.input);
215
+ else resolvedInput = loaded;
216
+ } catch {}
217
+ if (!resolvedInput) resolvedInput = input;
218
+ return {
219
+ schema: resolvedSchema,
220
+ input: resolvedInput,
221
+ meta: extractInputMeta(resolvedSchema, meta)
222
+ };
223
+ }
224
+
225
+ //#endregion
226
+ //#region src/lib/output.ts
227
+ /**
228
+ * Extracts and normalizes output metadata from a given configuration. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
229
+ *
230
+ * @param schema - The schema that the specification is expected to conform to.
231
+ * @param config - The output metadata config to extract and normalize.
232
+ * @returns The normalized output metadata.
233
+ */
234
+ function extractOutputMeta(schema, config) {
235
+ const jsonSchema = schema?.schema ?? {};
236
+ const meta = resolveMeta(schema, config);
237
+ meta.description = resolveMetaDescription(`Accepts a ${meta.title ?? ""} specification and processes it with a {title} output.`, jsonSchema, meta, config?.description);
238
+ return meta;
239
+ }
240
+ /**
241
+ * Normalizes any accepted output config into a concrete output descriptor.
242
+ *
243
+ * @param schema - The schema that the output config is expected to conform to.
244
+ * @param config - The output config to normalize.
245
+ * @param options - Optional options for resolving the output config.
246
+ * @returns A promise that resolves to a normalized output descriptor.
247
+ */
248
+ async function createOutput(schema, config, options = {}) {
249
+ const { output, meta, schema: configSchema } = isOutputConfigObject(config) ? config : {
250
+ output: config,
251
+ meta: {}
252
+ };
253
+ let resolvedSchema = schema;
254
+ if (configSchema) {
255
+ let resolvedConfigSchema;
256
+ if (isLoadReference(configSchema)) try {
257
+ resolvedConfigSchema = await load(configSchema, options);
258
+ } catch {}
259
+ else resolvedConfigSchema = configSchema;
260
+ if (resolvedConfigSchema) {
261
+ resolvedSchema = await createSchema(resolvedConfigSchema, options);
262
+ resolvedSchema.schema = mergeMetadata(resolvedSchema.schema, schema.schema);
263
+ }
264
+ }
265
+ let resolvedOutput;
266
+ if (isLoadReference(output)) try {
267
+ const loaded = await load(output, options);
268
+ if (isOutputConfigObject(loaded)) resolvedOutput = await createOutput(resolvedSchema, loaded.output, options).then((s) => s.output);
269
+ else resolvedOutput = loaded;
270
+ } catch {}
271
+ if (!resolvedOutput) resolvedOutput = output;
272
+ return {
273
+ schema: resolvedSchema,
274
+ output: resolvedOutput,
275
+ meta: extractOutputMeta(resolvedSchema, meta)
276
+ };
277
+ }
278
+
279
+ //#endregion
280
+ //#region src/lib/generator.ts
281
+ /**
282
+ * Creates a generator from raw schema/input/output configurations and resolves all descriptors.
283
+ *
284
+ * @remarks
285
+ * This function is used to create a generator from raw schema, input, and output configurations. It resolves all descriptors and returns a fully constructed generator that can be used to generate output based on the provided schema and options.
286
+ *
287
+ * @template TSpec - The type of the specification that the generator will produce.
288
+ * @template TOptions - The type of the options that will be passed to the generator during generation.
289
+ * @param config - The generator configuration containing schema, input, output, and optional meta information.
290
+ * @param options - Optional extraction options for schema, input, and output.
291
+ * @returns A promise that resolves to a fully constructed generator.
292
+ */
293
+ async function createGenerator(executionId, sessionContext, config, options = {}) {
294
+ let configObject;
295
+ if (isGeneratorConfigObject(config)) configObject = config;
296
+ else configObject = await load(config, {
297
+ fs: mapStorageToFileSystem(sessionContext.storage),
298
+ ...options
299
+ });
300
+ if (!configObject.schema) configObject.schema = { type: "any" };
301
+ const schema = await createSchema(configObject.schema, {
302
+ storage: sessionContext.storage,
303
+ tsconfig: options.tsconfig,
304
+ ...options
305
+ });
306
+ let inputConfig = configObject.input;
307
+ if (!inputConfig) if (options.inputPath) inputConfig = "@power-plant/unstorage-input";
308
+ else throw new Error("No input configuration provided. Please provide an input configuration, a valid specification, or a `inputPath` option that points to a valid input file.");
309
+ let outputConfig = configObject.output;
310
+ if (!outputConfig) outputConfig = "@power-plant/unstorage-output";
311
+ const [input, output] = await Promise.all([createInput(schema, inputConfig, {
312
+ storage: sessionContext.storage,
313
+ ...options
314
+ }), createOutput(schema, outputConfig, {
315
+ storage: sessionContext.storage,
316
+ ...options
317
+ })]);
318
+ assertGeneratorConfigSchemasDoNotContradict(schema, input, output);
319
+ const generator = async (options) => {
320
+ const context = await createExecutionContext(executionId, sessionContext, options, schema, input, output);
321
+ return callAsyncExecutionContext(context, async () => {
322
+ const spec = isFunction(input.input) ? await input.input({
323
+ storage: context.storage,
324
+ ...options
325
+ }) : input.input;
326
+ context["~spec"] = spec;
327
+ let generatorFn;
328
+ if (isFunction(configObject.generator)) generatorFn = configObject.generator;
329
+ else generatorFn = await load(configObject.generator, {
330
+ storage: context.storage,
331
+ ...options
332
+ });
333
+ const documents = await generatorFn(spec, options);
334
+ return {
335
+ spec,
336
+ options,
337
+ documents,
338
+ returns: await output.output(spec, options, documents)
339
+ };
340
+ });
341
+ };
342
+ return {
343
+ meta: configObject.meta,
344
+ schema,
345
+ input,
346
+ output,
347
+ generator
348
+ };
349
+ }
350
+
351
+ //#endregion
352
+ //#region src/execute.ts
353
+ /**
354
+ * Creates an execution function that can be used to execute a generator.
355
+ *
356
+ * @remarks
357
+ * This function is used to create an execution function that can be used to execute a generator. It creates a new execution context and returns an execution function that can be used to execute the generator with the given configuration and options.
358
+ *
359
+ *
360
+ * @example
361
+ * ```ts
362
+ * import { createExecute } from "@power-plant/core";
363
+ *
364
+ * // First, create an execution function with a custom configuration
365
+ * const execute = await createExecute({
366
+ * ...
367
+ * });
368
+ *
369
+ * // Then, execute the generator
370
+ * const result = await execute("my-generator", {
371
+ * ...
372
+ * });
373
+ * ```
374
+ *
375
+ * @example
376
+ * ```ts
377
+ * import { createExecute } from "@power-plant/core";
378
+ *
379
+ * // First, create an execution function with a custom configuration
380
+ * const execute = await createExecute({
381
+ * ...
382
+ * });
383
+ *
384
+ * // Then, execute the generator
385
+ * const result = await execute({
386
+ * generator: (spec, options) => { ... },
387
+ * ...
388
+ * });
389
+ * ```
390
+ *
391
+ * @template TSpec - The type of the specification that the generator will produce.
392
+ * @template TOptions - The type of the options that will be passed to the generator during generation.
393
+ * @template TReturns - The type of the returns that the generator will produce.
394
+ * @param userConfig - The user configuration for the engine.
395
+ * @returns A promise that resolves to an execution function.
396
+ */
397
+ async function createExecute(userConfig = {}) {
398
+ const context = await createSessionContext(userConfig);
399
+ const execute = async (config, options = {}) => callAsyncSessionContext(context, async () => {
400
+ const executionId = uuid();
401
+ const { generator } = await createGenerator(executionId, context, config, options);
402
+ const { documents, returns, spec, options: returnedOptions } = await generator(options);
403
+ const execution = await extractExecution({
404
+ documents: Object.fromEntries(Object.entries(documents).map(([path, document]) => [path, {
405
+ ...document,
406
+ path,
407
+ meta: { executionId }
408
+ }])),
409
+ meta: {
410
+ executionId,
411
+ executedAt: /* @__PURE__ */ new Date(),
412
+ executedBy: context.session.user
413
+ }
414
+ }, spec, returnedOptions);
415
+ context.session.executions.push(execution);
416
+ return returns;
417
+ });
418
+ return execute;
419
+ }
420
+ /**
421
+ * Executes a generator with a given configuration and options.
422
+ *
423
+ * @remarks
424
+ * This function is used to execute a generator with a given configuration and options. It creates a new execution context and returns an execution function that can be used to execute the generator with the given configuration and options.
425
+ *
426
+ * @example
427
+ * ```ts
428
+ * import { execute } from "@power-plant/core";
429
+ *
430
+ * // Create and execute the generator
431
+ * const result = await execute("my-generator", {
432
+ * ...
433
+ * });
434
+ * ```
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * import { execute } from "@power-plant/core";
439
+ *
440
+ * // Create and execute the generator
441
+ * const result = await execute({
442
+ * generator: (spec, options) => { ... },
443
+ * }, {
444
+ * ...
445
+ * });
446
+ * ```
447
+ *
448
+ * @template TSpec - The type of the specification that the generator will produce.
449
+ * @template TOptions - The type of the options that will be passed to the generator during generation.
450
+ * @template TReturns - The type of the returns that the generator will produce.
451
+ * @param config - The configuration for the generator.
452
+ * @param options - The options for the generator.
453
+ * @returns A promise that resolves to the returns of the generator.
454
+ */
455
+ async function execute(config, options = {}) {
456
+ return (await createExecute(options))(config, options);
457
+ }
458
+
459
+ //#endregion
460
+ export { execute as n, createExecute as t };
461
+ //# sourceMappingURL=execute-C6kyFG8N.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execute-C6kyFG8N.mjs","names":[],"sources":[],"mappings":""}
package/dist/execute.cjs CHANGED
@@ -1 +1,6 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./execute-4whFNgY3.cjs");require("./context.cjs"),exports.createExecute=e.t,exports.execute=e.n;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_execute = require('./execute-3oK9lgh3.cjs');
3
+ require('./context.cjs');
4
+
5
+ exports.createExecute = require_execute.createExecute;
6
+ exports.execute = require_execute.execute;
package/dist/execute.mjs CHANGED
@@ -1 +1,4 @@
1
- import"./context.mjs";import{n as e,t}from"./execute-ByonuMsd.mjs";export{t as createExecute,e as execute};
1
+ import "./context.mjs";
2
+ import { n as execute, t as createExecute } from "./execute-C6kyFG8N.mjs";
3
+
4
+ export { createExecute, execute };
@@ -1 +1,17 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./type-checks.cjs"),t=require("./meta.cjs");exports.formatMetaVersion=t.formatMetaVersion,exports.isGeneratorConfigObject=e.isGeneratorConfigObject,exports.isInputConfigObject=e.isInputConfigObject,exports.isOutputConfigObject=e.isOutputConfigObject,exports.isSchemaConfigObject=e.isSchemaConfigObject,exports.resolveMeta=t.resolveMeta,exports.resolveMetaDescription=t.resolveMetaDescription,exports.resolveMetaExample=t.resolveMetaExample,exports.resolveMetaId=t.resolveMetaId,exports.resolveMetaLinks=t.resolveMetaLinks,exports.resolveMetaName=t.resolveMetaName,exports.resolveMetaTitle=t.resolveMetaTitle,exports.resolveMetaVersion=t.resolveMetaVersion;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_helpers_type_checks = require('./type-checks.cjs');
3
+ const require_helpers_meta = require('./meta.cjs');
4
+
5
+ exports.formatMetaVersion = require_helpers_meta.formatMetaVersion;
6
+ exports.isGeneratorConfigObject = require_helpers_type_checks.isGeneratorConfigObject;
7
+ exports.isInputConfigObject = require_helpers_type_checks.isInputConfigObject;
8
+ exports.isOutputConfigObject = require_helpers_type_checks.isOutputConfigObject;
9
+ exports.isSchemaConfigObject = require_helpers_type_checks.isSchemaConfigObject;
10
+ exports.resolveMeta = require_helpers_meta.resolveMeta;
11
+ exports.resolveMetaDescription = require_helpers_meta.resolveMetaDescription;
12
+ exports.resolveMetaExample = require_helpers_meta.resolveMetaExample;
13
+ exports.resolveMetaId = require_helpers_meta.resolveMetaId;
14
+ exports.resolveMetaLinks = require_helpers_meta.resolveMetaLinks;
15
+ exports.resolveMetaName = require_helpers_meta.resolveMetaName;
16
+ exports.resolveMetaTitle = require_helpers_meta.resolveMetaTitle;
17
+ exports.resolveMetaVersion = require_helpers_meta.resolveMetaVersion;
@@ -1 +1,4 @@
1
- import{isGeneratorConfigObject as e,isInputConfigObject as t,isOutputConfigObject as n,isSchemaConfigObject as r}from"./type-checks.mjs";import{formatMetaVersion as i,resolveMeta as a,resolveMetaDescription as o,resolveMetaExample as s,resolveMetaId as c,resolveMetaLinks as l,resolveMetaName as u,resolveMetaTitle as d,resolveMetaVersion as f}from"./meta.mjs";export{i as formatMetaVersion,e as isGeneratorConfigObject,t as isInputConfigObject,n as isOutputConfigObject,r as isSchemaConfigObject,a as resolveMeta,o as resolveMetaDescription,s as resolveMetaExample,c as resolveMetaId,l as resolveMetaLinks,u as resolveMetaName,d as resolveMetaTitle,f as resolveMetaVersion};
1
+ import { isGeneratorConfigObject, isInputConfigObject, isOutputConfigObject, isSchemaConfigObject } from "./type-checks.mjs";
2
+ import { formatMetaVersion, resolveMeta, resolveMetaDescription, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaTitle, resolveMetaVersion } from "./meta.mjs";
3
+
4
+ export { formatMetaVersion, isGeneratorConfigObject, isInputConfigObject, isOutputConfigObject, isSchemaConfigObject, resolveMeta, resolveMetaDescription, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaTitle, resolveMetaVersion };
@@ -1 +1,142 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@stryke/string-format/title-case"),t=require("@stryke/type-checks/is-set-object"),n=require("@stryke/unique-id/uuid"),r=require("@stryke/type-checks/is-set-string"),i=require("@power-plant/schema"),a=require("@power-plant/schema/codegen"),o=require("@stryke/convert/to-array"),s=require("@stryke/date/format"),c=require("@stryke/date/validate"),l=require("@stryke/helpers/get-unique"),u=require("@stryke/string-format/kebab-case"),d=require("@stryke/type-checks/is-date"),f=require("@stryke/type-checks/is-number");function p(e){return(0,d.isDate)(e)?(0,s.formatYYYYMMDD)(e):(0,f.isNumber)(e)?(0,c.isValidTimestamp)(e)&&e>1e9?(0,s.formatYYYYMMDD)(new Date(e)):e.toString():(0,r.isSetString)(e)?e:`1.0`}function m(e,t,n){return p(n??t?.version??e?.version)}function h(e,t,n){return n??t.name??((0,r.isSetString)(e?.name)?e.name:(0,r.isSetString)(e?.title)?e.title:e.$id?(0,u.kebabCase)(e.$id):(0,a.stringifyType)(e))}function g(e,t){let r=h(e,t),i=m(e,t);return r?`${(0,u.kebabCase)(r)}@${i}`:(0,n.uuid)()}function _(t,n,r){let i=r??n.title??t?.title;return i===void 0?(0,e.titleCase)(n.name??(0,a.stringifyType)(t)):i}function v(e,t,n,i){n.title??=_(t,n);let a=n.title??``,o=e.replaceAll(/\{\s*title\s*\}/g,a),s=i??n.description??t?.description;return(0,r.isSetString)(s)?s:o}function y(e,n,i){return(e=>e.map((e,n)=>(0,r.isSetString)(e)?{name:`example-${n+1}`,description:`Example Specification #${n+1}`,value:e}:(0,t.isSetObject)(e)&&`value`in e&&(0,r.isSetString)(e.value)?{name:`example-${n+1}`,description:e.description||`Example Specification #${n+1}`,value:e.value}:void 0).filter(Boolean))((0,o.toArray)(i??n.examples??e?.examples??[]))}function b(e,t,n){return(0,l.getUnique)((0,o.toArray)(n).concat(t.links??[]).concat(e?.docs??[]))}function x(e,t){let n=(0,i.isSchemaOf)(e)?e:e??{schema:{}},r={};return r.name=h(n.schema,r,t?.name),r.version=m(n?.schema,r,t?.version),r.title=_(n?.schema,r,t?.title),r.links=b(n?.schema,r,t?.links),t?.deprecated&&(r.deprecated=t?.deprecated),t?.usage&&(r.usage=t?.usage),t?.tags&&(r.tags=t?.tags),r}exports.formatMetaVersion=p,exports.resolveMeta=x,exports.resolveMetaDescription=v,exports.resolveMetaExample=y,exports.resolveMetaId=g,exports.resolveMetaLinks=b,exports.resolveMetaName=h,exports.resolveMetaTitle=_,exports.resolveMetaVersion=m;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _stryke_string_format_title_case = require("@stryke/string-format/title-case");
3
+ let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
4
+ let _stryke_unique_id_uuid = require("@stryke/unique-id/uuid");
5
+ let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
6
+ let _power_plant_schema = require("@power-plant/schema");
7
+ let _power_plant_schema_codegen = require("@power-plant/schema/codegen");
8
+ let _stryke_convert_to_array = require("@stryke/convert/to-array");
9
+ let _stryke_date_format = require("@stryke/date/format");
10
+ let _stryke_date_validate = require("@stryke/date/validate");
11
+ let _stryke_helpers_get_unique = require("@stryke/helpers/get-unique");
12
+ let _stryke_string_format_kebab_case = require("@stryke/string-format/kebab-case");
13
+ let _stryke_type_checks_is_date = require("@stryke/type-checks/is-date");
14
+ let _stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
15
+
16
+ //#region src/helpers/meta.ts
17
+ function formatMetaVersion(value) {
18
+ return (0, _stryke_type_checks_is_date.isDate)(value) ? (0, _stryke_date_format.formatYYYYMMDD)(value) : (0, _stryke_type_checks_is_number.isNumber)(value) ? (0, _stryke_date_validate.isValidTimestamp)(value) && value > 1e9 ? (0, _stryke_date_format.formatYYYYMMDD)(new Date(value)) : value.toString() : (0, _stryke_type_checks_is_set_string.isSetString)(value) ? value : "1.0";
19
+ }
20
+ /**
21
+ * Extracts the version information from a given input, which can be a string, number, or Date object. The function returns a string representation of the version in the format "YYYYMMDD" for Date inputs, or as a string for valid timestamp numbers. If the input is a string, it is returned as-is. If the input is invalid or not provided, a default version of "1.0" is returned.
22
+ *
23
+ * @param input - The input from which to extract the version. It can be a string, number, undefined, or Date object.
24
+ * @returns A string representing the extracted version information.
25
+ */
26
+ function resolveMetaVersion(schema, meta, input) {
27
+ return formatMetaVersion(input ?? meta?.version ?? schema?.version);
28
+ }
29
+ /**
30
+ * Resolves a metadata name using explicit input, metadata, or schema fallbacks.
31
+ *
32
+ * @param schema - The JSON Schema fragment to read fallback values from.
33
+ * @param meta - Metadata values that may already include a name.
34
+ * @param input - An explicit name value to prioritize when provided.
35
+ * @returns The resolved metadata name.
36
+ */
37
+ function resolveMetaName(schema, meta, input) {
38
+ return input ?? meta.name ?? ((0, _stryke_type_checks_is_set_string.isSetString)(schema?.name) ? schema.name : (0, _stryke_type_checks_is_set_string.isSetString)(schema?.title) ? schema.title : schema.$id ? (0, _stryke_string_format_kebab_case.kebabCase)(schema.$id) : (0, _power_plant_schema_codegen.stringifyType)(schema));
39
+ }
40
+ /**
41
+ * Resolves a stable metadata identifier in the format `<name>@<version>`.
42
+ *
43
+ * @param schema - The JSON Schema fragment used to infer fallback values.
44
+ * @param meta - Metadata values used to resolve name and version.
45
+ * @returns The resolved metadata identifier, or a generated id when no name is available.
46
+ */
47
+ function resolveMetaId(schema, meta) {
48
+ const name = resolveMetaName(schema, meta);
49
+ const version = resolveMetaVersion(schema, meta);
50
+ return name ? `${(0, _stryke_string_format_kebab_case.kebabCase)(name)}@${version}` : (0, _stryke_unique_id_uuid.uuid)();
51
+ }
52
+ /**
53
+ * Resolves a human-readable display name for metadata.
54
+ *
55
+ * @param schema - The JSON Schema fragment to read fallback display values from.
56
+ * @param meta - Metadata values that may already include a display name.
57
+ * @param input - An explicit display name value to prioritize when provided.
58
+ * @returns The resolved metadata display name.
59
+ */
60
+ function resolveMetaTitle(schema, meta, input) {
61
+ const value = input ?? meta.title ?? schema?.title;
62
+ if (value !== void 0) return value;
63
+ return (0, _stryke_string_format_title_case.titleCase)(meta.name ?? (0, _power_plant_schema_codegen.stringifyType)(schema));
64
+ }
65
+ /**
66
+ * Resolves a metadata description from explicit input, metadata, or schema values.
67
+ *
68
+ * @param template - A template string used to generate a default description when no explicit description is provided.
69
+ * @param schema - The JSON Schema fragment to read fallback description values from.
70
+ * @param meta - Metadata values that may already include a description.
71
+ * @param input - An explicit description value to prioritize when provided.
72
+ * @returns The resolved description, if available.
73
+ */
74
+ function resolveMetaDescription(template, schema, meta, input) {
75
+ meta.title ??= resolveMetaTitle(schema, meta);
76
+ const title = meta.title ?? "";
77
+ const defaultDescription = template.replaceAll(/\{\s*title\s*\}/g, title);
78
+ const resolved = input ?? meta.description ?? schema?.description;
79
+ return (0, _stryke_type_checks_is_set_string.isSetString)(resolved) ? resolved : defaultDescription;
80
+ }
81
+ /**
82
+ * Resolves and normalizes metadata examples into a consistent object format.
83
+ *
84
+ * @typeParam TSpec - The schema specification type associated with example values.
85
+ * @param schema - The JSON Schema fragment to read fallback examples from.
86
+ * @param meta - Metadata values that may already include examples.
87
+ * @param input - Explicit examples to prioritize when provided.
88
+ * @returns A normalized list of examples with generated descriptions when needed.
89
+ */
90
+ function resolveMetaExample(schema, meta, input) {
91
+ const normalizeExamples = (examples) => examples.map((example, i) => (0, _stryke_type_checks_is_set_string.isSetString)(example) ? {
92
+ name: `example-${i + 1}`,
93
+ description: `Example Specification #${i + 1}`,
94
+ value: example
95
+ } : (0, _stryke_type_checks_is_set_object.isSetObject)(example) && "value" in example && (0, _stryke_type_checks_is_set_string.isSetString)(example.value) ? {
96
+ name: `example-${i + 1}`,
97
+ description: example.description || `Example Specification #${i + 1}`,
98
+ value: example.value
99
+ } : void 0).filter(Boolean);
100
+ return normalizeExamples((0, _stryke_convert_to_array.toArray)(input ?? meta.examples ?? schema?.examples ?? []));
101
+ }
102
+ /**
103
+ * Resolves and de-duplicates metadata links from input, metadata, and schema docs.
104
+ *
105
+ * @param schema - The JSON Schema fragment to read fallback documentation links from.
106
+ * @param meta - Metadata values that may already include links.
107
+ * @param input - Explicit links to prioritize when provided.
108
+ * @returns A unique list of metadata links.
109
+ */
110
+ function resolveMetaLinks(schema, meta, input) {
111
+ return (0, _stryke_helpers_get_unique.getUnique)((0, _stryke_convert_to_array.toArray)(input).concat(meta.links ?? []).concat(schema?.docs ?? []));
112
+ }
113
+ /**
114
+ * Extracts and normalizes metadata for a specification based on the provided schema and optional configuration.
115
+ *
116
+ * @param schema - The schema that the specification is expected to conform to.
117
+ * @param config - Optional metadata configuration to extract and normalize.
118
+ * @returns The normalized specification metadata.
119
+ */
120
+ function resolveMeta(schema, config) {
121
+ const extractedSchema = (0, _power_plant_schema.isSchemaOf)(schema) ? schema : schema ?? { schema: {} };
122
+ const meta = {};
123
+ meta.name = resolveMetaName(extractedSchema.schema, meta, config?.name);
124
+ meta.version = resolveMetaVersion(extractedSchema?.schema, meta, config?.version);
125
+ meta.title = resolveMetaTitle(extractedSchema?.schema, meta, config?.title);
126
+ meta.links = resolveMetaLinks(extractedSchema?.schema, meta, config?.links);
127
+ if (config?.deprecated) meta.deprecated = config?.deprecated;
128
+ if (config?.usage) meta.usage = config?.usage;
129
+ if (config?.tags) meta.tags = config?.tags;
130
+ return meta;
131
+ }
132
+
133
+ //#endregion
134
+ exports.formatMetaVersion = formatMetaVersion;
135
+ exports.resolveMeta = resolveMeta;
136
+ exports.resolveMetaDescription = resolveMetaDescription;
137
+ exports.resolveMetaExample = resolveMetaExample;
138
+ exports.resolveMetaId = resolveMetaId;
139
+ exports.resolveMetaLinks = resolveMetaLinks;
140
+ exports.resolveMetaName = resolveMetaName;
141
+ exports.resolveMetaTitle = resolveMetaTitle;
142
+ exports.resolveMetaVersion = resolveMetaVersion;