@power-plant/schema 0.0.25 → 0.0.26

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/dist/index.cjs CHANGED
@@ -1,2 +1,788 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./rolldown-runtime-CMqjfN_6.cjs"),t=require("./constants-CjTQhR-l.cjs"),n=require("./helpers-CFED4EbH.cjs"),r=require("./storage-CgfRQlqS.cjs");let i=require("@stryke/type-checks/is-set-object"),a=require("@stryke/type-checks/is-set-string"),o=require("@stryke/type-checks"),s=require("@stryke/convert/extract-file-reference"),c=require("@stryke/fs/resolve"),l=require("@stryke/hash"),u=require("@stryke/helpers/deep-clone"),d=require("@stryke/json"),f=require("@stryke/path/find"),p=require("@stryke/resolve/constants"),m=require("@stryke/resolve/load"),h=require("@stryke/string-format/list"),g=require("@stryke/zod"),_=require("@typescript/vfs"),ee=require("@valibot/to-json-schema"),v=require("node:path"),te=require("ts-json-schema-generator/dist/factory/generator.js"),y=require("typescript");y=e.t(y,1);const ne=new Set([...t.t,`default`,`examples`]);function re(e){return ne.has(e)}function b(e){return!(0,i.isSetObject)(e)||e.type===`any`||Object.keys(e).filter(e=>!re(e)).length===0}function x(e){if(b(e))return`any`;let t=e.type;if((0,a.isSetString)(t))return[t];if(Array.isArray(t))return t.filter(a.isSetString);let r=n.it(e);return r.length>0?r:n.N(e)?[`object`]:n.v(e)?[`array`]:`any`}function S(e){return e.length>0?e:`schema`}function C(e,t){return JSON.stringify(e)===JSON.stringify(t)}function w(e,t,r=``){let i=[];if(b(e)||b(t))return i;let a=x(e),o=x(t);if(a!==`any`&&o!==`any`&&a.filter(e=>o.includes(e)).length===0)return i.push(`${S(r)} has conflicting types: ${a.join(`|`)} vs ${o.join(`|`)}`),i;let s=e.const,c=t.const;s!==void 0&&c!==void 0&&!C(s,c)&&i.push(`${S(r)} has conflicting const values`);let l=e.enum,u=t.enum;if(l?.length&&u?.length&&(u.some(e=>l.some(t=>C(t,e)))||i.push(`${S(r)} has enum values that do not overlap`)),n.N(e)&&n.N(t)){let a=e.properties??{},o=t.properties??{};for(let[e,t]of Object.entries(o)){let o=a[e],s=r?`${r}.${e}`:e;o&&n.m(o)&&n.m(t)&&i.push(...w(o,t,s))}}if(n.v(e)&&n.v(t)){let a=e.items,o=t.items;a&&o&&n.m(a)&&n.m(o)&&i.push(...w(a,o,r?`${r}[]`:`items`));let s=e.prefixItems,c=t.prefixItems;if(Array.isArray(s)&&Array.isArray(c)){let e=Math.min(s.length,c.length);for(let t=0;t<e;t++){let e=s[t],a=c[t];n.m(e)&&n.m(a)&&i.push(...w(e,a,r?`${r}[${t}]`:`[${t}]`))}}}return i}function T(e,t,n=`schema`){let r=w(e,t);if(r.length>0)throw Error(`The ${n} schema contradicts the generator schema:\n${r.map(e=>`- ${e}`).join(`
2
- `)}`)}const E=`https://power-plant.invalid/`,D={noEmit:!0,emitDecoratorMetadata:!0,experimentalDecorators:!0,target:y.default.ScriptTarget.ES2022,module:y.default.ModuleKind.ESNext,strictNullChecks:!1,skipLibCheck:!0,skipDefaultLibCheck:!0,esModuleInterop:!0};function O(e,t){if(e.readFileSync)try{let n=e.readFileSync(t,`utf8`);return typeof n==`string`?n:void 0}catch{return}}function k(e,t){if(e.existsSync)try{return e.existsSync(t)}catch{return!1}if(e.statSync)try{return e.statSync(t),!0}catch{return!1}return O(e,t)!==void 0}function A(e,t){let n=e.fileExists.bind(e),r=e.readFile.bind(e),i=e.directoryExists.bind(e),a=e.realpath?.bind(e);e.fileExists=e=>k(t,e)||n(e),e.readFile=e=>{if(k(t,e)){let n=O(t,e);if(n!==void 0)return n}return r(e)},e.directoryExists=e=>{try{if(t.statSync){if(t.statSync(e)?.isDirectory?.())return!0}else if(t.existsSync?.(e))return!0}catch{}return i(e)},e.realpath&&t.realpathSync&&(e.realpath=e=>{try{return String(t.realpathSync(e))}catch{return a?.(e)??e}})}function j(e,t,n){if(!t)return{...D};let r=(n?O(n,t):void 0)??y.default.sys.readFile(t);if(!r)return{...D};let i=y.default.parseConfigFileTextToJson(t,r);if(!i.config)return{...D};let a={...y.default.parseJsonConfigFileContent(i.config,e,(0,v.dirname)(t),{},t).options,noEmit:!0};return delete a.out,delete a.outDir,delete a.outFile,delete a.declaration,delete a.declarationDir,delete a.declarationMap,a}function M(e,t){let n=t.cwd??(0,v.dirname)(e),r=_.createFSBackedSystem,i=_.createVirtualCompilerHost,a=r(new Map,n,y.default);t.fs&&A(a,t.fs);let o=j(a,t.tsconfig,t.fs),{compilerHost:s}=i(a,o,y.default);return y.default.createProgram({rootNames:[e],options:o,host:s})}function N(e){return!(!(0,i.isSetObject)(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e)}function P(e){return N(e)?e.schema:e}function F(e){return e.endsWith(`#`)?e.slice(0,-1):e}function I(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function ie(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function ae(e){return e.length===0?``:`/${e.map(e=>ie(e)).join(`/`)}`}function L(e,t){try{return F(new URL(e,t).toString())}catch{return F(e)}}function R(e,t,n,r,a){if(!(0,i.isSetObject)(e))return;let s=e,c=ae(t),l=(0,o.isSetString)(s.$id)?L(s.$id,n):n,u=I(l);if(r.set(l,c),r.set(u,c),(0,o.isSetString)(s.$anchor)&&r.set(`${u}#${s.$anchor}`,c),(0,o.isSetString)(s.$dynamicAnchor)){let e=`${u}#${s.$dynamicAnchor}`;r.set(e,c),a.set(e,`#${s.$dynamicAnchor}`)}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,i)=>{R(n,[...t,e,String(i)],l,r,a)});continue}R(n,[...t,e],l,r,a)}}function z(e,t,n,r,a){if(!(0,i.isSetObject)(e))return;let s=e,c=(0,o.isSetString)(s.$id)?L(s.$id,n):n;if((0,o.isSetString)(s.$ref)){let e=L(s.$ref,c),t=r.get(e)??r.get(I(e));t!==void 0&&(s.$ref=t.length>0?`#${t}`:`#`)}if((0,o.isSetString)(s.$dynamicRef)){let e=L(s.$dynamicRef,c),t=a.get(e);if(t)s.$dynamicRef=t;else{let t=r.get(e)??r.get(I(e));t!==void 0&&(s.$dynamicRef=t.length>0?`#${t}`:`#`)}}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,i)=>{z(n,[...t,e,String(i)],c,r,a)});continue}z(n,[...t,e],c,r,a)}}function B(e){if(!(0,i.isSetObject)(e))return e;let t=(0,u.deepClone)(e),n=(0,o.isSetString)(t.$id)?L(t.$id,E):E,r=new Map,a=new Map;return R(t,[],n,r,a),z(t,[],n,r,a),t}function V(e){if(n.$(e))return W(e);if((0,i.isSetObject)(e)){if(n.Z(e))return G(e);let t=e;if(`$schema`in t&&n.$(t.$schema))return W(t.$schema)}return e}function H(e){return Array.isArray(e)?e.map(e=>V(e)):e}function U(e){return(0,ee.toJsonSchema)(e,{target:`draft-2020-12`})}function W(e){let t=e,n={};for(let[e,r]of Object.entries(t))if(e!==`tsType`&&e!==`markdownType`&&e!==`tags`&&e!==`args`&&e!==`resolve`){if(e===`id`&&(0,o.isSetString)(r)){n.$id=r;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!(0,i.isSetObject)(r)){n[e]=r;continue}n[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,V(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){n[e]=V(r);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){n[e]=H(r);continue}n[e]=r}return n}function G(e){let t=e,r=n.$(t.$schema)?W(t.$schema):{},a={};for(let[e,r]of Object.entries(t)){if(e.startsWith(`$`)||!(0,i.isSetObject)(r))continue;if(n.Z(r)){a[e]=G(r);continue}let t=r;if(`$schema`in t&&n.$(t.$schema)){a[e]=W(t.$schema);continue}n.$(r)&&(a[e]=W(r))}if(!n.N(r))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let o={...(0,i.isSetObject)(r.properties)?r.properties:{},...a};return{...r,type:r.type??`object`,...Object.keys(o).length>0?{properties:o}:{}}}function K(e,t){let r=P(t);if(n.Y(r)||n.K(r))return(0,l.murmurhash)({variant:e,input:r.schema});if((0,o.isSetString)(r)||typeof r==`boolean`)return(0,l.murmurhash)({variant:e,input:r});if((0,i.isSetObject)(r)){if((0,g.isZod3Type)(r))return(0,l.murmurhash)({variant:e,input:r._def});if((0,d.isStandardJsonSchema)(r))return(0,l.murmurhash)({variant:e,input:r[`~standard`]});if(n.m(r))return(0,l.murmurhash)({variant:e,input:r});if(n.tt(r))return(0,l.murmurhash)({variant:e,input:U(r)});if(n.Z(r))return(0,l.murmurhash)({variant:e,input:G(r)});if(n.$(r))return(0,l.murmurhash)({variant:e,input:W(r)})}throw Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`)}function q(e){if((0,i.isSetObject)(e)){if((0,g.isZod3Type)(e))return(0,g.extractJsonSchema)(e,{target:`draft-2020-12`});if(n.Q(e))return G(e);if(n.et(e))return W(e);if((0,d.isStandardJsonSchema)(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(n.tt(e))return U(e);if(n.m(e))return e}}function J(e){if((0,i.isSetObject)(e)){if((0,g.isZod3Type)(e))return`zod3`;if(n.Q(e)||n.et(e))return`untyped`;if((0,d.isStandardJsonSchema)(e))return`standard-schema`;if(n.m(e))return`json-schema`;if(n.tt(e))return`valibot`}throw Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`)}function Y(e){let t=P(e);return n.Y(t)||n.K(t)?t.variant:(0,o.isSetString)(t)||n.p(t)?`file-reference`:J(t)}async function X(e,t){if(n.Y(e))return e.schema;let r=t??J(e),i;if((r===`zod3`||r===`json-schema`||r===`standard-schema`||r===`untyped`||r===`valibot`)&&(i=q(e)),i)return B(i);throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`)}function Z(e,t){if(e===`zod3`)return{hash:K(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:K(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:K(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:K(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:K(e,t),variant:`valibot`,schema:t};throw Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`)}async function Q(e,t={}){let n=(0,s.extractFileReference)(e);if(!n)throw Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);let r=n.export??`*`,i=await(0,c.resolveSafe)(n.file,{fs:t.fs}),a=i||n.file;try{return(0,te.createGenerator)({path:a,type:r,expose:`all`,jsDoc:`extended`,markdownDescription:!0,fullDescription:!0,skipTypeCheck:!0,tsProgram:M(a,t),...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}"${i&&i!==n.file?` (resolved: ${i})`:``} using the type "${r}". Error: ${e.message}`)}}async function $(e,t={}){let i=P(e);if(n.Y(i))return i;if(n.K(i))return{...i,source:{hash:K(`json-schema`,i.schema),variant:`json-schema`,schema:i.schema}};let a,o=Y(i),c=K(o,i);if(o===`file-reference`){let e=(0,s.extractFileReference)(i);if(!e)throw Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(i)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);let o=(0,f.findFileExtensionSafe)(e.file);if(o&&!p.VALID_OBJECT_SOURCE_EXTENSIONS.includes(o))throw Error(`The provided schema file input "${e.file}" has an invalid file extension (.${o}). Please ensure that the file has one of the following extensions: ${(0,h.list)(p.VALID_OBJECT_SOURCE_EXTENSIONS,{conjunction:`or`})}.`);let c;t.storage&&(c=r.t(t.storage));let l=await(0,m.loadSafe)(i,{...t,fs:c});l??=await Q(i,{...t,fs:c});let u=P(l);a=n.Y(u)?u.source:n.K(u)?{hash:K(`json-schema`,u.schema),variant:`json-schema`,schema:u.schema}:Z(J(u),u)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(o))a=Z(o,i);else throw Error(`Invalid schema definition input "${o}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);return{variant:o,source:a,schema:await X(a.schema,a.variant),hash:c}}async function oe(e,t={}){let r=P(e);if(n.Y(r)||n.J(r))return r;let i=await $(e,t);if(!i?.schema)throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);return i}exports.JSON_SCHEMA_METADATA_KEYS=t.t,exports.JSON_SCHEMA_PRIMITIVE_TYPES=t.n,exports.JSON_SCHEMA_TYPES=t.r,exports.JsonSchemaTypeNames=t.i,exports.SCHEMA_ARRAY_CONCAT_KEYWORDS=t.a,exports.SCHEMA_RECORD_KEYWORDS=t.o,exports.SCHEMA_SINGLE_KEYWORDS=t.s,exports.addProperty=n.t,exports.applyJsonSchemaMetadata=n.nt,exports.assertSchemasDoNotContradict=T,exports.bundleReferences=B,exports.createStoragePromises=r.n,exports.extract=oe,exports.extractHash=K,exports.extractJsonSchema=q,exports.extractResolvedVariant=J,exports.extractSchema=X,exports.extractSchemaWithSource=$,exports.extractSource=Z,exports.extractTSType=Q,exports.extractVariant=Y,exports.findSchemaContradictions=w,exports.getJsonSchema=n.n,exports.getJsonSchemaObject=n.r,exports.getPrimarySchemaType=n.rt,exports.getProperties=n.i,exports.getPropertiesList=n.a,exports.getProperty=n.o,exports.isFileReference=n.p,exports.isJsonSchema=n.m,exports.isJsonSchemaAllOf=n.h,exports.isJsonSchemaAny=n.g,exports.isJsonSchemaAnyOf=n._,exports.isJsonSchemaArray=n.v,exports.isJsonSchemaBigint=n.y,exports.isJsonSchemaBoolean=n.b,exports.isJsonSchemaDate=n.x,exports.isJsonSchemaDecimal=n.S,exports.isJsonSchemaEnum=n.C,exports.isJsonSchemaInteger=n.w,exports.isJsonSchemaKeywords=n.T,exports.isJsonSchemaLiteral=n.E,exports.isJsonSchemaMap=n.D,exports.isJsonSchemaNativeEnum=n.O,exports.isJsonSchemaNever=n.k,exports.isJsonSchemaNull=n.A,exports.isJsonSchemaNullable=n.j,exports.isJsonSchemaNumber=n.M,exports.isJsonSchemaObject=n.N,exports.isJsonSchemaPrimitiveType=n.P,exports.isJsonSchemaPrimitiveUnion=n.F,exports.isJsonSchemaRecord=n.I,exports.isJsonSchemaRef=n.L,exports.isJsonSchemaSet=n.R,exports.isJsonSchemaString=n.z,exports.isJsonSchemaTuple=n.B,exports.isJsonSchemaType=n.V,exports.isJsonSchemaUndefined=n.H,exports.isJsonSchemaUnion=n.U,exports.isJsonSchemaUnknown=n.W,exports.isNullOnlyJsonSchema=n.G,exports.isPropertyOptional=n.s,exports.isSchema=n.K,exports.isSchemaNullable=n.c,exports.isSchemaObject=n.q,exports.isSchemaOf=n.J,exports.isSchemaWithSource=n.Y,exports.isStandardSchema=n.X,exports.isUntypedConfig=n.Z,exports.isUntypedConfigStrict=n.Q,exports.isUntypedSchema=n.$,exports.isUntypedSchemaStrict=n.et,exports.isValibotSchema=n.tt,exports.isValidSchemaConfigFile=n.l,exports.mapStorageToFileSystem=r.t,exports.merge=n.u,exports.mergeMetadata=n.d,exports.normalizeKey=r.r,exports.readSchemaTypes=n.it,exports.traverseSchema=n.f;
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
3
+ const require_constants = require('./constants-B7xonHLD.cjs');
4
+ const require_helpers = require('./helpers-sXsSapgI.cjs');
5
+ const require_storage = require('./storage-B8aDmNpv.cjs');
6
+ let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
7
+ let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
8
+ let _stryke_type_checks = require("@stryke/type-checks");
9
+ let _stryke_convert_extract_file_reference = require("@stryke/convert/extract-file-reference");
10
+ let _stryke_fs_resolve = require("@stryke/fs/resolve");
11
+ let _stryke_hash = require("@stryke/hash");
12
+ let _stryke_helpers_deep_clone = require("@stryke/helpers/deep-clone");
13
+ let _stryke_json = require("@stryke/json");
14
+ let _stryke_path_find = require("@stryke/path/find");
15
+ let _stryke_resolve_constants = require("@stryke/resolve/constants");
16
+ let _stryke_resolve_load = require("@stryke/resolve/load");
17
+ let _stryke_string_format_list = require("@stryke/string-format/list");
18
+ let _stryke_zod = require("@stryke/zod");
19
+ let _typescript_vfs = require("@typescript/vfs");
20
+ let _valibot_to_json_schema = require("@valibot/to-json-schema");
21
+ let node_path = require("node:path");
22
+ let ts_json_schema_generator_dist_factory_generator_js = require("ts-json-schema-generator/dist/factory/generator.js");
23
+ let typescript = require("typescript");
24
+ typescript = require_rolldown_runtime.__toESM(typescript, 1);
25
+
26
+ //#region src/compatibility.ts
27
+ const METADATA_KEYS = /* @__PURE__ */ new Set([
28
+ ...require_constants.JSON_SCHEMA_METADATA_KEYS,
29
+ "default",
30
+ "examples"
31
+ ]);
32
+ function isMetadataKey(key) {
33
+ return METADATA_KEYS.has(key);
34
+ }
35
+ function isUnconstrainedSchema(schema) {
36
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(schema)) return true;
37
+ if (schema.type === "any") return true;
38
+ return Object.keys(schema).filter((key) => !isMetadataKey(key)).length === 0;
39
+ }
40
+ function resolveSchemaTypes(schema) {
41
+ if (isUnconstrainedSchema(schema)) return "any";
42
+ const schemaType = schema.type;
43
+ if ((0, _stryke_type_checks_is_set_string.isSetString)(schemaType)) return [schemaType];
44
+ if (Array.isArray(schemaType)) return schemaType.filter(_stryke_type_checks_is_set_string.isSetString);
45
+ const primitiveTypes = require_helpers.readSchemaTypes(schema);
46
+ if (primitiveTypes.length > 0) return primitiveTypes;
47
+ if (require_helpers.isJsonSchemaObject(schema)) return ["object"];
48
+ if (require_helpers.isJsonSchemaArray(schema)) return ["array"];
49
+ return "any";
50
+ }
51
+ function formatPath(path) {
52
+ return path.length > 0 ? path : "schema";
53
+ }
54
+ function valuesEqual(left, right) {
55
+ return JSON.stringify(left) === JSON.stringify(right);
56
+ }
57
+ /**
58
+ * Finds structural contradictions between two JSON Schema fragments.
59
+ *
60
+ * @remarks
61
+ * Metadata-only keywords are ignored. Either schema may be unconstrained
62
+ * (`{}`, `{ type: "any" }`, or missing structural keywords) without
63
+ * producing contradictions.
64
+ *
65
+ * @param base - The base JSON Schema fragment.
66
+ * @param override - The JSON Schema fragment to compare against the base.
67
+ * @param path - Optional dot-separated path used in issue messages.
68
+ * @returns A list of human-readable contradiction descriptions.
69
+ */
70
+ function findSchemaContradictions(base, override, path = "") {
71
+ const issues = [];
72
+ if (isUnconstrainedSchema(base) || isUnconstrainedSchema(override)) return issues;
73
+ const baseTypes = resolveSchemaTypes(base);
74
+ const overrideTypes = resolveSchemaTypes(override);
75
+ if (baseTypes !== "any" && overrideTypes !== "any") {
76
+ if (baseTypes.filter((type) => overrideTypes.includes(type)).length === 0) {
77
+ issues.push(`${formatPath(path)} has conflicting types: ${baseTypes.join("|")} vs ${overrideTypes.join("|")}`);
78
+ return issues;
79
+ }
80
+ }
81
+ const baseConst = base.const;
82
+ const overrideConst = override.const;
83
+ if (baseConst !== void 0 && overrideConst !== void 0 && !valuesEqual(baseConst, overrideConst)) issues.push(`${formatPath(path)} has conflicting const values`);
84
+ const baseEnum = base.enum;
85
+ const overrideEnum = override.enum;
86
+ if (baseEnum?.length && overrideEnum?.length) {
87
+ if (!overrideEnum.some((value) => baseEnum.some((baseValue) => valuesEqual(baseValue, value)))) issues.push(`${formatPath(path)} has enum values that do not overlap`);
88
+ }
89
+ if (require_helpers.isJsonSchemaObject(base) && require_helpers.isJsonSchemaObject(override)) {
90
+ const baseProperties = base.properties ?? {};
91
+ const overrideProperties = override.properties ?? {};
92
+ for (const [key, overrideProperty] of Object.entries(overrideProperties)) {
93
+ const baseProperty = baseProperties[key];
94
+ const propertyPath = path ? `${path}.${key}` : key;
95
+ if (baseProperty && require_helpers.isJsonSchema(baseProperty) && require_helpers.isJsonSchema(overrideProperty)) issues.push(...findSchemaContradictions(baseProperty, overrideProperty, propertyPath));
96
+ }
97
+ }
98
+ if (require_helpers.isJsonSchemaArray(base) && require_helpers.isJsonSchemaArray(override)) {
99
+ const baseItems = base.items;
100
+ const overrideItems = override.items;
101
+ if (baseItems && overrideItems && require_helpers.isJsonSchema(baseItems) && require_helpers.isJsonSchema(overrideItems)) issues.push(...findSchemaContradictions(baseItems, overrideItems, path ? `${path}[]` : "items"));
102
+ const basePrefix = base.prefixItems;
103
+ const overridePrefix = override.prefixItems;
104
+ if (Array.isArray(basePrefix) && Array.isArray(overridePrefix)) {
105
+ const length = Math.min(basePrefix.length, overridePrefix.length);
106
+ for (let index = 0; index < length; index++) {
107
+ const baseItem = basePrefix[index];
108
+ const overrideItem = overridePrefix[index];
109
+ if (require_helpers.isJsonSchema(baseItem) && require_helpers.isJsonSchema(overrideItem)) issues.push(...findSchemaContradictions(baseItem, overrideItem, path ? `${path}[${index}]` : `[${index}]`));
110
+ }
111
+ }
112
+ }
113
+ return issues;
114
+ }
115
+ /**
116
+ * Asserts that two JSON Schema fragments do not structurally contradict each other.
117
+ *
118
+ * @param base - The base JSON Schema fragment.
119
+ * @param override - The JSON Schema fragment to compare against the base.
120
+ * @param label - A label used in the thrown error message.
121
+ * @throws {Error} When one or more structural contradictions are found.
122
+ */
123
+ function assertSchemasDoNotContradict(base, override, label = "schema") {
124
+ const issues = findSchemaContradictions(base, override);
125
+ if (issues.length > 0) throw new Error(`The ${label} schema contradicts the generator schema:\n${issues.map((issue) => `- ${issue}`).join("\n")}`);
126
+ }
127
+
128
+ //#endregion
129
+ //#region src/extract.ts
130
+ const SCHEMA_BUNDLE_BASE_URI = "https://power-plant.invalid/";
131
+ const DEFAULT_TS_COMPILER_OPTIONS = {
132
+ noEmit: true,
133
+ emitDecoratorMetadata: true,
134
+ experimentalDecorators: true,
135
+ target: typescript.default.ScriptTarget.ES2022,
136
+ module: typescript.default.ModuleKind.ESNext,
137
+ strictNullChecks: false,
138
+ skipLibCheck: true,
139
+ skipDefaultLibCheck: true,
140
+ esModuleInterop: true
141
+ };
142
+ function readFileAsString(fs, fileName) {
143
+ if (!fs.readFileSync) return;
144
+ try {
145
+ const content = fs.readFileSync(fileName, "utf8");
146
+ return typeof content === "string" ? content : void 0;
147
+ } catch {
148
+ return;
149
+ }
150
+ }
151
+ function fileExistsOnFs(fs, fileName) {
152
+ if (fs.existsSync) try {
153
+ return fs.existsSync(fileName);
154
+ } catch {
155
+ return false;
156
+ }
157
+ if (fs.statSync) try {
158
+ fs.statSync(fileName);
159
+ return true;
160
+ } catch {
161
+ return false;
162
+ }
163
+ return readFileAsString(fs, fileName) !== void 0;
164
+ }
165
+ /**
166
+ * Prefers `options.fs` for System I/O so virtual storage-backed files resolve
167
+ * through createFSBackedSystem instead of only the real disk.
168
+ */
169
+ function bindFileSystemToSystem(system, fs) {
170
+ const baseFileExists = system.fileExists.bind(system);
171
+ const baseReadFile = system.readFile.bind(system);
172
+ const baseDirectoryExists = system.directoryExists.bind(system);
173
+ const baseRealpath = system.realpath?.bind(system);
174
+ system.fileExists = (fileName) => fileExistsOnFs(fs, fileName) || baseFileExists(fileName);
175
+ system.readFile = (fileName) => {
176
+ if (fileExistsOnFs(fs, fileName)) {
177
+ const content = readFileAsString(fs, fileName);
178
+ if (content !== void 0) return content;
179
+ }
180
+ return baseReadFile(fileName);
181
+ };
182
+ system.directoryExists = (directory) => {
183
+ try {
184
+ if (fs.statSync) {
185
+ if (fs.statSync(directory)?.isDirectory?.()) return true;
186
+ } else if (fs.existsSync?.(directory)) return true;
187
+ } catch {}
188
+ return baseDirectoryExists(directory);
189
+ };
190
+ if (system.realpath && fs.realpathSync) system.realpath = (path) => {
191
+ try {
192
+ return String(fs.realpathSync(path));
193
+ } catch {
194
+ return baseRealpath?.(path) ?? path;
195
+ }
196
+ };
197
+ }
198
+ function resolveCompilerOptions(system, tsconfig, fs) {
199
+ if (!tsconfig) return { ...DEFAULT_TS_COMPILER_OPTIONS };
200
+ const raw = (fs ? readFileAsString(fs, tsconfig) : void 0) ?? typescript.default.sys.readFile(tsconfig);
201
+ if (!raw) return { ...DEFAULT_TS_COMPILER_OPTIONS };
202
+ const parsed = typescript.default.parseConfigFileTextToJson(tsconfig, raw);
203
+ if (!parsed.config) return { ...DEFAULT_TS_COMPILER_OPTIONS };
204
+ const options = {
205
+ ...typescript.default.parseJsonConfigFileContent(parsed.config, system, (0, node_path.dirname)(tsconfig), {}, tsconfig).options,
206
+ noEmit: true
207
+ };
208
+ delete options.out;
209
+ delete options.outDir;
210
+ delete options.outFile;
211
+ delete options.declaration;
212
+ delete options.declarationDir;
213
+ delete options.declarationMap;
214
+ return options;
215
+ }
216
+ function createProgramFromFileSystem(rootFile, options) {
217
+ const projectRoot = options.cwd ?? (0, node_path.dirname)(rootFile);
218
+ const createSystem = _typescript_vfs.createFSBackedSystem;
219
+ const createHost = _typescript_vfs.createVirtualCompilerHost;
220
+ const system = createSystem(/* @__PURE__ */ new Map(), projectRoot, typescript.default);
221
+ if (options.fs) bindFileSystemToSystem(system, options.fs);
222
+ const compilerOptions = resolveCompilerOptions(system, options.tsconfig, options.fs);
223
+ const { compilerHost } = createHost(system, compilerOptions, typescript.default);
224
+ return typescript.default.createProgram({
225
+ rootNames: [rootFile],
226
+ options: compilerOptions,
227
+ host: compilerHost
228
+ });
229
+ }
230
+ function isWrappedSchemaConfig(input) {
231
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(input) || !("schema" in input)) return false;
232
+ if ("hash" in input || "variant" in input || "source" in input) return false;
233
+ return true;
234
+ }
235
+ function unwrapSchemaConfig(input) {
236
+ if (isWrappedSchemaConfig(input)) return input.schema;
237
+ return input;
238
+ }
239
+ function normalizeUri(uri) {
240
+ return uri.endsWith("#") ? uri.slice(0, -1) : uri;
241
+ }
242
+ function stripUriFragment(uri) {
243
+ const hashIndex = uri.indexOf("#");
244
+ return hashIndex >= 0 ? uri.slice(0, hashIndex) : uri;
245
+ }
246
+ function escapeJsonPointerToken(token) {
247
+ return token.replaceAll("~", "~0").replaceAll("/", "~1");
248
+ }
249
+ function toJsonPointer(path) {
250
+ if (path.length === 0) return "";
251
+ return `/${path.map((segment) => escapeJsonPointerToken(segment)).join("/")}`;
252
+ }
253
+ function resolveUri(reference, baseUri) {
254
+ try {
255
+ return normalizeUri(new URL(reference, baseUri).toString());
256
+ } catch {
257
+ return normalizeUri(reference);
258
+ }
259
+ }
260
+ function collectReferenceTargets(value, path, baseUri, uriToPointer, dynamicUriToFragment) {
261
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(value)) return;
262
+ const schema = value;
263
+ const pointer = toJsonPointer(path);
264
+ const currentBaseUri = (0, _stryke_type_checks.isSetString)(schema.$id) ? resolveUri(schema.$id, baseUri) : baseUri;
265
+ const currentDocumentUri = stripUriFragment(currentBaseUri);
266
+ uriToPointer.set(currentBaseUri, pointer);
267
+ uriToPointer.set(currentDocumentUri, pointer);
268
+ if ((0, _stryke_type_checks.isSetString)(schema.$anchor)) uriToPointer.set(`${currentDocumentUri}#${schema.$anchor}`, pointer);
269
+ if ((0, _stryke_type_checks.isSetString)(schema.$dynamicAnchor)) {
270
+ const dynamicTarget = `${currentDocumentUri}#${schema.$dynamicAnchor}`;
271
+ uriToPointer.set(dynamicTarget, pointer);
272
+ dynamicUriToFragment.set(dynamicTarget, `#${schema.$dynamicAnchor}`);
273
+ }
274
+ for (const [key, child] of Object.entries(schema)) {
275
+ if (Array.isArray(child)) {
276
+ child.forEach((entry, index) => {
277
+ collectReferenceTargets(entry, [
278
+ ...path,
279
+ key,
280
+ String(index)
281
+ ], currentBaseUri, uriToPointer, dynamicUriToFragment);
282
+ });
283
+ continue;
284
+ }
285
+ collectReferenceTargets(child, [...path, key], currentBaseUri, uriToPointer, dynamicUriToFragment);
286
+ }
287
+ }
288
+ function rewriteReferenceTargets(value, path, baseUri, uriToPointer, dynamicUriToFragment) {
289
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(value)) return;
290
+ const schema = value;
291
+ const currentBaseUri = (0, _stryke_type_checks.isSetString)(schema.$id) ? resolveUri(schema.$id, baseUri) : baseUri;
292
+ if ((0, _stryke_type_checks.isSetString)(schema.$ref)) {
293
+ const resolvedRefUri = resolveUri(schema.$ref, currentBaseUri);
294
+ const pointer = uriToPointer.get(resolvedRefUri) ?? uriToPointer.get(stripUriFragment(resolvedRefUri));
295
+ if (pointer !== void 0) schema.$ref = pointer.length > 0 ? `#${pointer}` : "#";
296
+ }
297
+ if ((0, _stryke_type_checks.isSetString)(schema.$dynamicRef)) {
298
+ const resolvedDynamicRefUri = resolveUri(schema.$dynamicRef, currentBaseUri);
299
+ const dynamicFragment = dynamicUriToFragment.get(resolvedDynamicRefUri);
300
+ if (dynamicFragment) schema.$dynamicRef = dynamicFragment;
301
+ else {
302
+ const pointer = uriToPointer.get(resolvedDynamicRefUri) ?? uriToPointer.get(stripUriFragment(resolvedDynamicRefUri));
303
+ if (pointer !== void 0) schema.$dynamicRef = pointer.length > 0 ? `#${pointer}` : "#";
304
+ }
305
+ }
306
+ for (const [key, child] of Object.entries(schema)) {
307
+ if (Array.isArray(child)) {
308
+ child.forEach((entry, index) => {
309
+ rewriteReferenceTargets(entry, [
310
+ ...path,
311
+ key,
312
+ String(index)
313
+ ], currentBaseUri, uriToPointer, dynamicUriToFragment);
314
+ });
315
+ continue;
316
+ }
317
+ rewriteReferenceTargets(child, [...path, key], currentBaseUri, uriToPointer, dynamicUriToFragment);
318
+ }
319
+ }
320
+ /**
321
+ * Bundles all external references in a JSON Schema into a single schema document by collecting all reference targets and rewriting the references to point to the bundled definitions. This ensures that the resulting schema is self-contained and can be used independently without relying on external documents.
322
+ *
323
+ * @param schema - The JSON Schema to bundle references for.
324
+ * @returns A new JSON Schema with all references bundled and rewritten to point to the bundled definitions.
325
+ */
326
+ function bundleReferences(schema) {
327
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(schema)) return schema;
328
+ const bundledSchema = (0, _stryke_helpers_deep_clone.deepClone)(schema);
329
+ const baseUri = (0, _stryke_type_checks.isSetString)(bundledSchema.$id) ? resolveUri(bundledSchema.$id, SCHEMA_BUNDLE_BASE_URI) : SCHEMA_BUNDLE_BASE_URI;
330
+ const uriToPointer = /* @__PURE__ */ new Map();
331
+ const dynamicUriToFragment = /* @__PURE__ */ new Map();
332
+ collectReferenceTargets(bundledSchema, [], baseUri, uriToPointer, dynamicUriToFragment);
333
+ rewriteReferenceTargets(bundledSchema, [], baseUri, uriToPointer, dynamicUriToFragment);
334
+ return bundledSchema;
335
+ }
336
+ function convertNestedUntypedSchema(value) {
337
+ if (require_helpers.isUntypedSchema(value)) return convertUntypedSchemaToJsonSchema(value);
338
+ if ((0, _stryke_type_checks_is_set_object.isSetObject)(value)) {
339
+ if (require_helpers.isUntypedConfig(value)) return convertUntypedConfigToJsonSchema(value);
340
+ const nested = value;
341
+ if ("$schema" in nested && require_helpers.isUntypedSchema(nested.$schema)) return convertUntypedSchemaToJsonSchema(nested.$schema);
342
+ }
343
+ return value;
344
+ }
345
+ function convertNestedUntypedSchemaArray(value) {
346
+ if (!Array.isArray(value)) return value;
347
+ return value.map((item) => convertNestedUntypedSchema(item));
348
+ }
349
+ function convertValibotSchemaToJsonSchema(schema) {
350
+ return (0, _valibot_to_json_schema.toJsonSchema)(schema, { target: "draft-2020-12" });
351
+ }
352
+ function convertUntypedSchemaToJsonSchema(schema) {
353
+ const source = schema;
354
+ const jsonSchema = {};
355
+ for (const [key, value] of Object.entries(source)) {
356
+ if (key === "tsType" || key === "markdownType" || key === "tags" || key === "args" || key === "resolve") continue;
357
+ if (key === "id" && (0, _stryke_type_checks.isSetString)(value)) {
358
+ jsonSchema.$id = value;
359
+ continue;
360
+ }
361
+ if (key === "properties" || key === "patternProperties" || key === "dependentSchemas" || key === "$defs" || key === "definitions") {
362
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(value)) {
363
+ jsonSchema[key] = value;
364
+ continue;
365
+ }
366
+ jsonSchema[key] = Object.fromEntries(Object.entries(value).map(([propertyKey, propertyValue]) => [propertyKey, convertNestedUntypedSchema(propertyValue)]));
367
+ continue;
368
+ }
369
+ if (key === "items" || key === "contains" || key === "if" || key === "then" || key === "else" || key === "not" || key === "propertyNames" || key === "additionalProperties" || key === "unevaluatedProperties") {
370
+ jsonSchema[key] = convertNestedUntypedSchema(value);
371
+ continue;
372
+ }
373
+ if (key === "oneOf" || key === "anyOf" || key === "allOf") {
374
+ jsonSchema[key] = convertNestedUntypedSchemaArray(value);
375
+ continue;
376
+ }
377
+ jsonSchema[key] = value;
378
+ }
379
+ return jsonSchema;
380
+ }
381
+ function convertUntypedConfigToJsonSchema(input) {
382
+ const inputObject = input;
383
+ const base = require_helpers.isUntypedSchema(inputObject.$schema) ? convertUntypedSchemaToJsonSchema(inputObject.$schema) : {};
384
+ const properties = {};
385
+ for (const [key, value] of Object.entries(inputObject)) {
386
+ if (key.startsWith("$")) continue;
387
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(value)) continue;
388
+ if (require_helpers.isUntypedConfig(value)) {
389
+ properties[key] = convertUntypedConfigToJsonSchema(value);
390
+ continue;
391
+ }
392
+ const nested = value;
393
+ if ("$schema" in nested && require_helpers.isUntypedSchema(nested.$schema)) {
394
+ properties[key] = convertUntypedSchemaToJsonSchema(nested.$schema);
395
+ continue;
396
+ }
397
+ if (require_helpers.isUntypedSchema(value)) properties[key] = convertUntypedSchemaToJsonSchema(value);
398
+ }
399
+ if (!require_helpers.isJsonSchemaObject(base)) throw new Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);
400
+ const mergedProperties = {
401
+ ...(0, _stryke_type_checks_is_set_object.isSetObject)(base.properties) ? base.properties : {},
402
+ ...properties
403
+ };
404
+ return {
405
+ ...base,
406
+ type: base.type ?? "object",
407
+ ...Object.keys(mergedProperties).length > 0 ? { properties: mergedProperties } : {}
408
+ };
409
+ }
410
+ /**
411
+ * Creates a hash string for a given schema definition input.
412
+ */
413
+ function extractHash(variant, input) {
414
+ const unwrappedConfig = unwrapSchemaConfig(input);
415
+ if (require_helpers.isSchemaWithSource(unwrappedConfig) || require_helpers.isSchema(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
416
+ variant,
417
+ input: unwrappedConfig.schema
418
+ });
419
+ if ((0, _stryke_type_checks.isSetString)(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
420
+ variant,
421
+ input: unwrappedConfig
422
+ });
423
+ else if (typeof unwrappedConfig === "boolean") return (0, _stryke_hash.murmurhash)({
424
+ variant,
425
+ input: unwrappedConfig
426
+ });
427
+ else if ((0, _stryke_type_checks_is_set_object.isSetObject)(unwrappedConfig)) {
428
+ if ((0, _stryke_zod.isZod3Type)(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
429
+ variant,
430
+ input: unwrappedConfig._def
431
+ });
432
+ else if ((0, _stryke_json.isStandardJsonSchema)(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
433
+ variant,
434
+ input: unwrappedConfig["~standard"]
435
+ });
436
+ else if (require_helpers.isJsonSchema(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
437
+ variant,
438
+ input: unwrappedConfig
439
+ });
440
+ else if (require_helpers.isValibotSchema(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
441
+ variant,
442
+ input: convertValibotSchemaToJsonSchema(unwrappedConfig)
443
+ });
444
+ else if (require_helpers.isUntypedConfig(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
445
+ variant,
446
+ input: convertUntypedConfigToJsonSchema(unwrappedConfig)
447
+ });
448
+ else if (require_helpers.isUntypedSchema(unwrappedConfig)) return (0, _stryke_hash.murmurhash)({
449
+ variant,
450
+ input: convertUntypedSchemaToJsonSchema(unwrappedConfig)
451
+ });
452
+ }
453
+ throw new Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`);
454
+ }
455
+ /**
456
+ * Extracts a JSON Schema from Zod, Standard Schema, Valibot, untyped, or JSON Schema inputs.
457
+ *
458
+ * @param schema - The schema input to extract a JSON Schema from.
459
+ * @returns The extracted JSON Schema, or `undefined` if the input is not a supported schema type.
460
+ */
461
+ function extractJsonSchema(schema) {
462
+ if ((0, _stryke_type_checks_is_set_object.isSetObject)(schema)) {
463
+ if ((0, _stryke_zod.isZod3Type)(schema)) return (0, _stryke_zod.extractJsonSchema)(schema, { target: "draft-2020-12" });
464
+ if (require_helpers.isUntypedConfigStrict(schema)) return convertUntypedConfigToJsonSchema(schema);
465
+ if (require_helpers.isUntypedSchemaStrict(schema)) return convertUntypedSchemaToJsonSchema(schema);
466
+ if ((0, _stryke_json.isStandardJsonSchema)(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
467
+ if (require_helpers.isValibotSchema(schema)) return convertValibotSchemaToJsonSchema(schema);
468
+ if (require_helpers.isJsonSchema(schema)) return schema;
469
+ }
470
+ }
471
+ /**
472
+ * Resolves the concrete source variant for a schema source input.
473
+ *
474
+ * @param input - The schema source input to inspect.
475
+ * @returns The resolved schema source variant.
476
+ * @throws Will throw an error when the input cannot be mapped to a supported source variant.
477
+ */
478
+ function extractResolvedVariant(input) {
479
+ if ((0, _stryke_type_checks_is_set_object.isSetObject)(input)) {
480
+ if ((0, _stryke_zod.isZod3Type)(input)) return "zod3";
481
+ else if (require_helpers.isUntypedConfigStrict(input) || require_helpers.isUntypedSchemaStrict(input)) return "untyped";
482
+ else if ((0, _stryke_json.isStandardJsonSchema)(input)) return "standard-schema";
483
+ else if (require_helpers.isJsonSchema(input)) return "json-schema";
484
+ else if (require_helpers.isValibotSchema(input)) return "valibot";
485
+ }
486
+ throw new Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`);
487
+ }
488
+ /**
489
+ * Determines the top-level input variant for schema extraction.
490
+ *
491
+ * @param input - The schema input to classify.
492
+ * @returns The resolved schema input variant.
493
+ */
494
+ function extractVariant(input) {
495
+ const unwrappedConfig = unwrapSchemaConfig(input);
496
+ if (require_helpers.isSchemaWithSource(unwrappedConfig) || require_helpers.isSchema(unwrappedConfig)) return unwrappedConfig.variant;
497
+ if ((0, _stryke_type_checks.isSetString)(unwrappedConfig) || require_helpers.isFileReference(unwrappedConfig)) return "file-reference";
498
+ return extractResolvedVariant(unwrappedConfig);
499
+ }
500
+ /**
501
+ * Extracts and normalizes a JSON Schema from a concrete schema source input.
502
+ *
503
+ * @param input - The schema source input to extract from.
504
+ * @param variant - Optional source variant override. When omitted, the variant is inferred from the input.
505
+ * @returns A promise that resolves to a bundled JSON Schema.
506
+ * @throws Will throw an error if no valid JSON Schema can be extracted from the input.
507
+ */
508
+ async function extractSchema(input, variant) {
509
+ if (require_helpers.isSchemaWithSource(input)) return input.schema;
510
+ const resolvedVariant = variant ?? extractResolvedVariant(input);
511
+ let schema;
512
+ if (resolvedVariant === "zod3" || resolvedVariant === "json-schema" || resolvedVariant === "standard-schema" || resolvedVariant === "untyped" || resolvedVariant === "valibot") schema = extractJsonSchema(input);
513
+ if (schema) return bundleReferences(schema);
514
+ throw new Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`);
515
+ }
516
+ /**
517
+ * Builds source metadata for a schema input using a known source variant.
518
+ *
519
+ * @param variant - The schema source variant associated with the input.
520
+ * @param input - The schema source input to wrap.
521
+ * @returns The normalized schema source payload, including the source hash and variant.
522
+ * @throws Will throw an error if the provided variant is unsupported.
523
+ */
524
+ function extractSource(variant, input) {
525
+ if (variant === "zod3") return {
526
+ hash: extractHash(variant, input),
527
+ variant: "zod3",
528
+ schema: input
529
+ };
530
+ else if (variant === "untyped") return {
531
+ hash: extractHash(variant, input),
532
+ variant: "untyped",
533
+ schema: input
534
+ };
535
+ else if (variant === "standard-schema") return {
536
+ hash: extractHash(variant, input),
537
+ variant: "standard-schema",
538
+ schema: input
539
+ };
540
+ else if (variant === "json-schema") return {
541
+ hash: extractHash(variant, input),
542
+ variant: "json-schema",
543
+ schema: input
544
+ };
545
+ else if (variant === "valibot") return {
546
+ hash: extractHash(variant, input),
547
+ variant: "valibot",
548
+ schema: input
549
+ };
550
+ throw new Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);
551
+ }
552
+ /**
553
+ * Resolves a type definition to a JSON Schema. This function passes the provided file reference to ts-json-schema-generator, using the referenced export name as the target type when one is provided.
554
+ *
555
+ * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.
556
+ * @param options - Optional overrides reserved for API compatibility.
557
+ * @returns A promise that resolves to the generated JSON Schema.
558
+ */
559
+ async function extractTSType(input, options = {}) {
560
+ const fileReference = (0, _stryke_convert_extract_file_reference.extractFileReference)(input);
561
+ if (!fileReference) throw new Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);
562
+ const exportName = fileReference.export ?? "*";
563
+ const resolvedPath = await (0, _stryke_fs_resolve.resolveSafe)(fileReference.file, { fs: options.fs });
564
+ const filePath = resolvedPath || fileReference.file;
565
+ try {
566
+ return (0, ts_json_schema_generator_dist_factory_generator_js.createGenerator)({
567
+ path: filePath,
568
+ type: exportName,
569
+ expose: "all",
570
+ jsDoc: "extended",
571
+ markdownDescription: true,
572
+ fullDescription: true,
573
+ skipTypeCheck: true,
574
+ tsProgram: createProgramFromFileSystem(filePath, options),
575
+ ...options
576
+ }).createSchema(exportName);
577
+ } catch (error) {
578
+ throw new Error(`Failed to generate a JSON schema for "${fileReference.file}"${resolvedPath && resolvedPath !== fileReference.file ? ` (resolved: ${resolvedPath})` : ""} using the type "${exportName}". Error: ${error.message}`);
579
+ }
580
+ }
581
+ /**
582
+ * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
583
+ *
584
+ * @example
585
+ * ```ts
586
+ * Resolve a schema definition from a JSON schema file
587
+ * const schema1 = await extract(context, "./schemas/my-json-schema.json");
588
+ * // Resolve a schema definition from a TypeScript module export
589
+ * const schema2 = await extract(context, "./schemas.ts#MySchema");
590
+ * // Resolve a schema definition from a JSON Schema object
591
+ * const schema3 = await extract(context, schemaObject);
592
+ * // Resolve a schema definition from a Zod schema
593
+ * const schema4 = await extract(context, zodSchema);
594
+ * // Resolve a schema definition from a Valibot schema
595
+ * const schema5 = await extract(context, valibotSchema);
596
+ * // Resolve a schema definition from an untyped schema
597
+ * const schema6 = await extract(context, untypedSchema);
598
+ * ```
599
+ *
600
+ * @see https://zod.dev/
601
+ * @see https://valibot.dev/
602
+ * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec
603
+ * @see https://json-schema.org/
604
+ * @see https://ajv.js.org/json-type-definition.html
605
+ * @see https://github.com/vega/ts-json-schema-generator
606
+ * @see https://github.com/unjs/untyped
607
+ * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html
608
+ *
609
+ * @param input - The schema definition input to extract, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options.
610
+ * @param options - Optional overrides for the configuration used during extraction.
611
+ * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
612
+ * @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
613
+ */
614
+ async function extractSchemaWithSource(input, options = {}) {
615
+ const unwrappedConfig = unwrapSchemaConfig(input);
616
+ if (require_helpers.isSchemaWithSource(unwrappedConfig)) return unwrappedConfig;
617
+ if (require_helpers.isSchema(unwrappedConfig)) return {
618
+ ...unwrappedConfig,
619
+ source: {
620
+ hash: extractHash("json-schema", unwrappedConfig.schema),
621
+ variant: "json-schema",
622
+ schema: unwrappedConfig.schema
623
+ }
624
+ };
625
+ let source;
626
+ const variant = extractVariant(unwrappedConfig);
627
+ const hash = extractHash(variant, unwrappedConfig);
628
+ if (variant === "file-reference") {
629
+ const fileReference = (0, _stryke_convert_extract_file_reference.extractFileReference)(unwrappedConfig);
630
+ if (!fileReference) throw new Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(unwrappedConfig)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);
631
+ const extension = (0, _stryke_path_find.findFileExtensionSafe)(fileReference.file);
632
+ if (extension && !_stryke_resolve_constants.VALID_OBJECT_SOURCE_EXTENSIONS.includes(extension)) throw new Error(`The provided schema file input "${fileReference.file}" has an invalid file extension (.${extension}). Please ensure that the file has one of the following extensions: ${(0, _stryke_string_format_list.list)(_stryke_resolve_constants.VALID_OBJECT_SOURCE_EXTENSIONS, { conjunction: "or" })}.`);
633
+ let fs;
634
+ if (options.storage) fs = require_storage.mapStorageToFileSystem(options.storage);
635
+ let resolved = await (0, _stryke_resolve_load.loadSafe)(unwrappedConfig, {
636
+ ...options,
637
+ fs
638
+ });
639
+ resolved ??= await extractTSType(unwrappedConfig, {
640
+ ...options,
641
+ fs
642
+ });
643
+ const resolvedConfig = unwrapSchemaConfig(resolved);
644
+ if (require_helpers.isSchemaWithSource(resolvedConfig)) source = resolvedConfig.source;
645
+ else if (require_helpers.isSchema(resolvedConfig)) source = {
646
+ hash: extractHash("json-schema", resolvedConfig.schema),
647
+ variant: "json-schema",
648
+ schema: resolvedConfig.schema
649
+ };
650
+ else source = extractSource(extractResolvedVariant(resolvedConfig), resolvedConfig);
651
+ } else if ([
652
+ "json-schema",
653
+ "standard-schema",
654
+ "zod3",
655
+ "untyped",
656
+ "valibot",
657
+ "reflection"
658
+ ].includes(variant)) source = extractSource(variant, unwrappedConfig);
659
+ else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);
660
+ return {
661
+ variant,
662
+ source,
663
+ schema: await extractSchema(source.schema, source.variant),
664
+ hash
665
+ };
666
+ }
667
+ /**
668
+ * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
669
+ *
670
+ * @example
671
+ * ```ts
672
+ * Resolve a schema definition from a JSON schema file
673
+ * const schema1 = await extract(context, "./schemas/my-json-schema.json");
674
+ * // Resolve a schema definition from a TypeScript module export
675
+ * const schema2 = await extract(context, "./schemas.ts#MySchema");
676
+ * // Resolve a schema definition from a JSON Schema object
677
+ * const schema3 = await extract(context, schemaObject);
678
+ * // Resolve a schema definition from a Zod schema
679
+ * const schema4 = await extract(context, zodSchema);
680
+ * // Resolve a schema definition from a Valibot schema
681
+ * const schema5 = await extract(context, valibotSchema);
682
+ * // Resolve a schema definition from an untyped schema
683
+ * const schema6 = await extract(context, untypedSchema);
684
+ * ```
685
+ *
686
+ * @see https://zod.dev/
687
+ * @see https://valibot.dev/
688
+ * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec
689
+ * @see https://json-schema.org/
690
+ * @see https://ajv.js.org/json-type-definition.html
691
+ * @see https://github.com/vega/ts-json-schema-generator
692
+ * @see https://github.com/unjs/untyped
693
+ * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html
694
+ *
695
+ * @param input - The schema definition input to extract, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options.
696
+ * @param options - Optional overrides for the configuration used during extraction.
697
+ * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
698
+ * @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
699
+ */
700
+ async function extract(input, options = {}) {
701
+ const unwrappedConfig = unwrapSchemaConfig(input);
702
+ if (require_helpers.isSchemaWithSource(unwrappedConfig) || require_helpers.isSchemaOf(unwrappedConfig)) return unwrappedConfig;
703
+ const result = await extractSchemaWithSource(input, options);
704
+ if (!result?.schema) throw new Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);
705
+ return result;
706
+ }
707
+
708
+ //#endregion
709
+ exports.JSON_SCHEMA_METADATA_KEYS = require_constants.JSON_SCHEMA_METADATA_KEYS;
710
+ exports.JSON_SCHEMA_PRIMITIVE_TYPES = require_constants.JSON_SCHEMA_PRIMITIVE_TYPES;
711
+ exports.JSON_SCHEMA_TYPES = require_constants.JSON_SCHEMA_TYPES;
712
+ exports.JsonSchemaTypeNames = require_constants.JsonSchemaTypeNames;
713
+ exports.SCHEMA_ARRAY_CONCAT_KEYWORDS = require_constants.SCHEMA_ARRAY_CONCAT_KEYWORDS;
714
+ exports.SCHEMA_RECORD_KEYWORDS = require_constants.SCHEMA_RECORD_KEYWORDS;
715
+ exports.SCHEMA_SINGLE_KEYWORDS = require_constants.SCHEMA_SINGLE_KEYWORDS;
716
+ exports.addProperty = require_helpers.addProperty;
717
+ exports.applyJsonSchemaMetadata = require_helpers.applyJsonSchemaMetadata;
718
+ exports.assertSchemasDoNotContradict = assertSchemasDoNotContradict;
719
+ exports.bundleReferences = bundleReferences;
720
+ exports.createStoragePromises = require_storage.createStoragePromises;
721
+ exports.extract = extract;
722
+ exports.extractHash = extractHash;
723
+ exports.extractJsonSchema = extractJsonSchema;
724
+ exports.extractResolvedVariant = extractResolvedVariant;
725
+ exports.extractSchema = extractSchema;
726
+ exports.extractSchemaWithSource = extractSchemaWithSource;
727
+ exports.extractSource = extractSource;
728
+ exports.extractTSType = extractTSType;
729
+ exports.extractVariant = extractVariant;
730
+ exports.findSchemaContradictions = findSchemaContradictions;
731
+ exports.getJsonSchema = require_helpers.getJsonSchema;
732
+ exports.getJsonSchemaObject = require_helpers.getJsonSchemaObject;
733
+ exports.getPrimarySchemaType = require_helpers.getPrimarySchemaType;
734
+ exports.getProperties = require_helpers.getProperties;
735
+ exports.getPropertiesList = require_helpers.getPropertiesList;
736
+ exports.getProperty = require_helpers.getProperty;
737
+ exports.isFileReference = require_helpers.isFileReference;
738
+ exports.isJsonSchema = require_helpers.isJsonSchema;
739
+ exports.isJsonSchemaAllOf = require_helpers.isJsonSchemaAllOf;
740
+ exports.isJsonSchemaAny = require_helpers.isJsonSchemaAny;
741
+ exports.isJsonSchemaAnyOf = require_helpers.isJsonSchemaAnyOf;
742
+ exports.isJsonSchemaArray = require_helpers.isJsonSchemaArray;
743
+ exports.isJsonSchemaBigint = require_helpers.isJsonSchemaBigint;
744
+ exports.isJsonSchemaBoolean = require_helpers.isJsonSchemaBoolean;
745
+ exports.isJsonSchemaDate = require_helpers.isJsonSchemaDate;
746
+ exports.isJsonSchemaDecimal = require_helpers.isJsonSchemaDecimal;
747
+ exports.isJsonSchemaEnum = require_helpers.isJsonSchemaEnum;
748
+ exports.isJsonSchemaInteger = require_helpers.isJsonSchemaInteger;
749
+ exports.isJsonSchemaKeywords = require_helpers.isJsonSchemaKeywords;
750
+ exports.isJsonSchemaLiteral = require_helpers.isJsonSchemaLiteral;
751
+ exports.isJsonSchemaMap = require_helpers.isJsonSchemaMap;
752
+ exports.isJsonSchemaNativeEnum = require_helpers.isJsonSchemaNativeEnum;
753
+ exports.isJsonSchemaNever = require_helpers.isJsonSchemaNever;
754
+ exports.isJsonSchemaNull = require_helpers.isJsonSchemaNull;
755
+ exports.isJsonSchemaNullable = require_helpers.isJsonSchemaNullable;
756
+ exports.isJsonSchemaNumber = require_helpers.isJsonSchemaNumber;
757
+ exports.isJsonSchemaObject = require_helpers.isJsonSchemaObject;
758
+ exports.isJsonSchemaPrimitiveType = require_helpers.isJsonSchemaPrimitiveType;
759
+ exports.isJsonSchemaPrimitiveUnion = require_helpers.isJsonSchemaPrimitiveUnion;
760
+ exports.isJsonSchemaRecord = require_helpers.isJsonSchemaRecord;
761
+ exports.isJsonSchemaRef = require_helpers.isJsonSchemaRef;
762
+ exports.isJsonSchemaSet = require_helpers.isJsonSchemaSet;
763
+ exports.isJsonSchemaString = require_helpers.isJsonSchemaString;
764
+ exports.isJsonSchemaTuple = require_helpers.isJsonSchemaTuple;
765
+ exports.isJsonSchemaType = require_helpers.isJsonSchemaType;
766
+ exports.isJsonSchemaUndefined = require_helpers.isJsonSchemaUndefined;
767
+ exports.isJsonSchemaUnion = require_helpers.isJsonSchemaUnion;
768
+ exports.isJsonSchemaUnknown = require_helpers.isJsonSchemaUnknown;
769
+ exports.isNullOnlyJsonSchema = require_helpers.isNullOnlyJsonSchema;
770
+ exports.isPropertyOptional = require_helpers.isPropertyOptional;
771
+ exports.isSchema = require_helpers.isSchema;
772
+ exports.isSchemaNullable = require_helpers.isSchemaNullable;
773
+ exports.isSchemaObject = require_helpers.isSchemaObject;
774
+ exports.isSchemaOf = require_helpers.isSchemaOf;
775
+ exports.isSchemaWithSource = require_helpers.isSchemaWithSource;
776
+ exports.isStandardSchema = require_helpers.isStandardSchema;
777
+ exports.isUntypedConfig = require_helpers.isUntypedConfig;
778
+ exports.isUntypedConfigStrict = require_helpers.isUntypedConfigStrict;
779
+ exports.isUntypedSchema = require_helpers.isUntypedSchema;
780
+ exports.isUntypedSchemaStrict = require_helpers.isUntypedSchemaStrict;
781
+ exports.isValibotSchema = require_helpers.isValibotSchema;
782
+ exports.isValidSchemaConfigFile = require_helpers.isValidSchemaConfigFile;
783
+ exports.mapStorageToFileSystem = require_storage.mapStorageToFileSystem;
784
+ exports.merge = require_helpers.merge;
785
+ exports.mergeMetadata = require_helpers.mergeMetadata;
786
+ exports.normalizeKey = require_storage.normalizeKey;
787
+ exports.readSchemaTypes = require_helpers.readSchemaTypes;
788
+ exports.traverseSchema = require_helpers.traverseSchema;