@powerlines/schema 0.11.57 → 0.11.59

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.
@@ -1,5 +1,21 @@
1
1
 
2
2
  //#region src/constants.ts
3
+ const VALID_SOURCE_FILE_EXTENSIONS = [
4
+ "ts",
5
+ "cts",
6
+ "mts",
7
+ "tsx",
8
+ "js",
9
+ "cjs",
10
+ "mjs",
11
+ "jsx",
12
+ "json",
13
+ "jsonc",
14
+ "json5",
15
+ "yaml",
16
+ "yml",
17
+ "toml"
18
+ ];
3
19
  const JsonSchemaTypeNames = {
4
20
  STRING: "string",
5
21
  NUMBER: "number",
@@ -41,4 +57,5 @@ const JSON_SCHEMA_METADATA_KEYS = [
41
57
  exports.JSON_SCHEMA_METADATA_KEYS = JSON_SCHEMA_METADATA_KEYS;
42
58
  exports.JSON_SCHEMA_PRIMITIVE_TYPES = JSON_SCHEMA_PRIMITIVE_TYPES;
43
59
  exports.JSON_SCHEMA_TYPES = JSON_SCHEMA_TYPES;
44
- exports.JsonSchemaTypeNames = JsonSchemaTypeNames;
60
+ exports.JsonSchemaTypeNames = JsonSchemaTypeNames;
61
+ exports.VALID_SOURCE_FILE_EXTENSIONS = VALID_SOURCE_FILE_EXTENSIONS;
@@ -1,4 +1,5 @@
1
1
  //#region src/constants.d.ts
2
+ declare const VALID_SOURCE_FILE_EXTENSIONS: string[];
2
3
  declare const JsonSchemaTypeNames: {
3
4
  readonly STRING: "string";
4
5
  readonly NUMBER: "number";
@@ -12,5 +13,5 @@ declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "intege
12
13
  declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
13
14
  declare const JSON_SCHEMA_METADATA_KEYS: ("title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
14
15
  //#endregion
15
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames };
16
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, VALID_SOURCE_FILE_EXTENSIONS };
16
17
  //# sourceMappingURL=constants.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA"}
1
+ {"version":3,"file":"constants.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,4BAAA;AAAA,cAiBA,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA"}
@@ -1,4 +1,5 @@
1
1
  //#region src/constants.d.ts
2
+ declare const VALID_SOURCE_FILE_EXTENSIONS: string[];
2
3
  declare const JsonSchemaTypeNames: {
3
4
  readonly STRING: "string";
4
5
  readonly NUMBER: "number";
@@ -12,5 +13,5 @@ declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "intege
12
13
  declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
13
14
  declare const JSON_SCHEMA_METADATA_KEYS: ("title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
14
15
  //#endregion
15
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames };
16
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, VALID_SOURCE_FILE_EXTENSIONS };
16
17
  //# sourceMappingURL=constants.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA"}
1
+ {"version":3,"file":"constants.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,4BAAA;AAAA,cAiBA,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA"}
@@ -1,4 +1,20 @@
1
1
  //#region src/constants.ts
2
+ const VALID_SOURCE_FILE_EXTENSIONS = [
3
+ "ts",
4
+ "cts",
5
+ "mts",
6
+ "tsx",
7
+ "js",
8
+ "cjs",
9
+ "mjs",
10
+ "jsx",
11
+ "json",
12
+ "jsonc",
13
+ "json5",
14
+ "yaml",
15
+ "yml",
16
+ "toml"
17
+ ];
2
18
  const JsonSchemaTypeNames = {
3
19
  STRING: "string",
4
20
  NUMBER: "number",
@@ -37,5 +53,5 @@ const JSON_SCHEMA_METADATA_KEYS = [
37
53
  ];
38
54
 
39
55
  //#endregion
40
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames };
56
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, VALID_SOURCE_FILE_EXTENSIONS };
41
57
  //# sourceMappingURL=constants.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { JsonSchemaMetadataKeywords } from \"./types\";\n\nexport const JsonSchemaTypeNames = {\n STRING: \"string\",\n NUMBER: \"number\",\n INTEGER: \"integer\",\n BOOLEAN: \"boolean\",\n NULL: \"null\",\n OBJECT: \"object\",\n ARRAY: \"array\"\n} as const;\n\nexport const JSON_SCHEMA_PRIMITIVE_TYPES = [\n JsonSchemaTypeNames.STRING,\n JsonSchemaTypeNames.NUMBER,\n JsonSchemaTypeNames.INTEGER,\n JsonSchemaTypeNames.BOOLEAN,\n JsonSchemaTypeNames.NULL\n] as const;\n\nexport const JSON_SCHEMA_TYPES = [\n ...JSON_SCHEMA_PRIMITIVE_TYPES,\n JsonSchemaTypeNames.ARRAY,\n JsonSchemaTypeNames.OBJECT\n] as const;\n\nexport const JSON_SCHEMA_METADATA_KEYS = [\n \"docs\",\n \"deprecated\",\n \"title\",\n \"description\",\n \"examples\",\n \"hidden\",\n \"ignore\",\n \"internal\",\n \"runtime\",\n \"readOnly\",\n \"writeOnly\",\n \"alias\",\n \"tags\"\n] satisfies ReadonlyArray<keyof JsonSchemaMetadataKeywords>;\n"],"mappings":";AAoBA,MAAa,sBAAsB;CACjC,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,MAAM;CACN,QAAQ;CACR,OAAO;AACT;AAEA,MAAa,8BAA8B;CACzC,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;AACtB;AAEA,MAAa,oBAAoB;CAC/B,GAAG;CACH,oBAAoB;CACpB,oBAAoB;AACtB;AAEA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
1
+ {"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { JsonSchemaMetadataKeywords } from \"./types\";\n\nexport const VALID_SOURCE_FILE_EXTENSIONS = [\n \"ts\",\n \"cts\",\n \"mts\",\n \"tsx\",\n \"js\",\n \"cjs\",\n \"mjs\",\n \"jsx\",\n \"json\",\n \"jsonc\",\n \"json5\",\n \"yaml\",\n \"yml\",\n \"toml\"\n] as const as string[];\n\nexport const JsonSchemaTypeNames = {\n STRING: \"string\",\n NUMBER: \"number\",\n INTEGER: \"integer\",\n BOOLEAN: \"boolean\",\n NULL: \"null\",\n OBJECT: \"object\",\n ARRAY: \"array\"\n} as const;\n\nexport const JSON_SCHEMA_PRIMITIVE_TYPES = [\n JsonSchemaTypeNames.STRING,\n JsonSchemaTypeNames.NUMBER,\n JsonSchemaTypeNames.INTEGER,\n JsonSchemaTypeNames.BOOLEAN,\n JsonSchemaTypeNames.NULL\n] as const;\n\nexport const JSON_SCHEMA_TYPES = [\n ...JSON_SCHEMA_PRIMITIVE_TYPES,\n JsonSchemaTypeNames.ARRAY,\n JsonSchemaTypeNames.OBJECT\n] as const;\n\nexport const JSON_SCHEMA_METADATA_KEYS = [\n \"docs\",\n \"deprecated\",\n \"title\",\n \"description\",\n \"examples\",\n \"hidden\",\n \"ignore\",\n \"internal\",\n \"runtime\",\n \"readOnly\",\n \"writeOnly\",\n \"alias\",\n \"tags\"\n] satisfies ReadonlyArray<keyof JsonSchemaMetadataKeywords>;\n"],"mappings":";AAoBA,MAAa,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,sBAAsB;CACjC,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,SAAS;CACT,MAAM;CACN,QAAQ;CACR,OAAO;AACT;AAEA,MAAa,8BAA8B;CACzC,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;CACpB,oBAAoB;AACtB;AAEA,MAAa,oBAAoB;CAC/B,GAAG;CACH,oBAAoB;CACpB,oBAAoB;AACtB;AAEA,MAAa,4BAA4B;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
package/dist/extract.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
2
+ const require_constants = require('./constants.cjs');
2
3
  const require_type_checks = require('./type-checks.cjs');
3
4
  const require_persistence = require('./persistence.cjs');
4
5
  const require_reflection = require('./reflection.cjs');
@@ -6,14 +7,17 @@ const require_resolve = require('./resolve.cjs');
6
7
  let defu = require("defu");
7
8
  defu = require_runtime.__toESM(defu, 1);
8
9
  let _stryke_type_checks = require("@stryke/type-checks");
10
+ let _stryke_path_find = require("@stryke/path/find");
9
11
  let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
10
12
  let _powerlines_core = require("@powerlines/core");
11
13
  let _powerlines_deepkit_esbuild_plugin = require("@powerlines/deepkit/esbuild-plugin");
12
14
  let _powerlines_deepkit_vendor_type = require("@powerlines/deepkit/vendor/type");
15
+ let _stryke_convert_extract_file_reference = require("@stryke/convert/extract-file-reference");
13
16
  let _stryke_hash = require("@stryke/hash");
14
17
  let _stryke_helpers_deep_clone = require("@stryke/helpers/deep-clone");
15
18
  let _stryke_json = require("@stryke/json");
16
19
  let _stryke_path_join = require("@stryke/path/join");
20
+ let _stryke_string_format_list = require("@stryke/string-format/list");
17
21
  let _stryke_zod = require("@stryke/zod");
18
22
  let _valibot_to_json_schema = require("@valibot/to-json-schema");
19
23
 
@@ -280,7 +284,7 @@ function extractResolvedVariant(input) {
280
284
  * @returns The resolved schema input variant.
281
285
  */
282
286
  function extractVariant(input) {
283
- if ((0, _stryke_type_checks.isSetString)(input) || (0, _powerlines_core.isTypeDefinition)(input)) return "type-definition";
287
+ if ((0, _powerlines_core.isFileReference)(input)) return "file-reference";
284
288
  return extractResolvedVariant(input);
285
289
  }
286
290
  /**
@@ -381,7 +385,10 @@ async function extractSchemaWithSource(context, input, options = {}) {
381
385
  let source;
382
386
  const variant = extractVariant(input);
383
387
  const hash = extractHash(variant, input);
384
- if (variant === "type-definition") {
388
+ if (variant === "file-reference") {
389
+ const fileReference = (0, _stryke_convert_extract_file_reference.extractFileReference)(input);
390
+ if (!fileReference) throw new Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(input)}". 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.`);
391
+ if (!require_constants.VALID_SOURCE_FILE_EXTENSIONS.includes((0, _stryke_path_find.findFileExtensionSafe)(fileReference.file))) throw new Error(`The provided schema file input "${fileReference.file}" has an invalid file extension. Please ensure that the file has one of the following extensions: ${(0, _stryke_string_format_list.list)(require_constants.VALID_SOURCE_FILE_EXTENSIONS, { conjunction: "or" })}.`);
385
392
  const resolved = await require_resolve.resolve(context, input, (0, defu.default)(options, { plugins: [(0, _powerlines_deepkit_esbuild_plugin.esbuildPlugin)(context, {
386
393
  reflection: "default",
387
394
  level: "all"
@@ -395,7 +402,7 @@ async function extractSchemaWithSource(context, input, options = {}) {
395
402
  "valibot",
396
403
  "reflection"
397
404
  ].includes(variant)) source = extractSource(variant, input);
398
- else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "type-definition", "json-schema", "standard-schema", "zod3", "untyped", or "reflection".`);
405
+ else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "untyped", or "reflection".`);
399
406
  return {
400
407
  variant,
401
408
  source,
@@ -1 +1 @@
1
- {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AAyOA;;;;iBAAgB,gBAAA,CAAiB,MAAA,EAAQ,UAAA,GAAa,UAAU;;;;iBAgMhD,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;AAFpB;;;AAAA,iBA2CgB,iBAAA,CAAkB,UAAA,EAAY,IAAA,GAAO,UAAU;;;;iBAW/C,iBAAA,CAAkB,MAAA,YAAkB,UAAU;;AApD1C;AAyCpB;;;;;iBA+CgB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;;;AAjDyC;AAW/D;;;iBAsEgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;AAtER;AAoC9D;;;;;;;AApC8D,iBAsFxC,aAAA,CACpB,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,UAAA;AAnDW;AAgCtB;;;;;;;AAhCsB,iBAwFN,aAAA,CACd,OAAA,EAAS,mBAAA,EACT,KAAA,EAAO,iBAAA,GACN,YAAA;AA3DmE;AAgBtE;;;;;;;;;;;;;;;;AAGqB;AAqCrB;;;;;;;;;AAxDsE,iBAkIhD,uBAAA,CACpB,OAAA,EAAS,OAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,eAAA;;;;;AA3EI;AAuEf;;;;;;;;;;;;;;;;;;;AAI0B;AA6F1B;;;;;iBAAsB,OAAA,CACpB,OAAA,EAAS,OAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,MAAA"}
1
+ {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AA6OA;;;;iBAAgB,gBAAA,CAAiB,MAAA,EAAQ,UAAA,GAAa,UAAU;;;;iBAgMhD,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EA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,CAAQ,UAAA;AAnDW;AAgCtB;;;;;;;AAhCsB,iBAwFN,aAAA,CACd,OAAA,EAAS,mBAAA,EACT,KAAA,EAAO,iBAAA,GACN,YAAA;AA3DmE;AAgBtE;;;;;;;;;;;;;;;;AAGqB;AAqCrB;;;;;;;;;AAxDsE,iBAkIhD,uBAAA,CACpB,OAAA,EAAS,OAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,eAAA;;;;;AA3EI;AAuEf;;;;;;;;;;;;;;;;;;;AAI0B;AAqH1B;;;;;iBAAsB,OAAA,CACpB,OAAA,EAAS,OAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,MAAA"}
package/dist/extract.mjs CHANGED
@@ -1,17 +1,21 @@
1
+ import { VALID_SOURCE_FILE_EXTENSIONS } from "./constants.mjs";
1
2
  import { isJsonSchema, isJsonSchemaObject, isSchema, isSchemaWithSource, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema } from "./type-checks.mjs";
2
3
  import { getCacheDirectory, writeSchema } from "./persistence.mjs";
3
4
  import { reflectionToJsonSchema } from "./reflection.mjs";
4
5
  import { resolve } from "./resolve.mjs";
5
6
  import defu from "defu";
6
7
  import { isSetString } from "@stryke/type-checks";
8
+ import { findFileExtensionSafe } from "@stryke/path/find";
7
9
  import { isSetObject as isSetObject$1 } from "@stryke/type-checks/is-set-object";
8
- import { isTypeDefinition } from "@powerlines/core";
10
+ import { isFileReference } from "@powerlines/core";
9
11
  import { esbuildPlugin } from "@powerlines/deepkit/esbuild-plugin";
10
12
  import { isType, stringifyType } from "@powerlines/deepkit/vendor/type";
13
+ import { extractFileReference } from "@stryke/convert/extract-file-reference";
11
14
  import { murmurhash } from "@stryke/hash";
12
15
  import { deepClone } from "@stryke/helpers/deep-clone";
13
16
  import { isStandardJsonSchema } from "@stryke/json";
14
17
  import { joinPaths } from "@stryke/path/join";
18
+ import { list } from "@stryke/string-format/list";
15
19
  import { extractJsonSchema, isZod3Type } from "@stryke/zod";
16
20
  import { toJsonSchema } from "@valibot/to-json-schema";
17
21
 
@@ -278,7 +282,7 @@ function extractResolvedVariant(input) {
278
282
  * @returns The resolved schema input variant.
279
283
  */
280
284
  function extractVariant(input) {
281
- if (isSetString(input) || isTypeDefinition(input)) return "type-definition";
285
+ if (isFileReference(input)) return "file-reference";
282
286
  return extractResolvedVariant(input);
283
287
  }
284
288
  /**
@@ -379,7 +383,10 @@ async function extractSchemaWithSource(context, input, options = {}) {
379
383
  let source;
380
384
  const variant = extractVariant(input);
381
385
  const hash = extractHash(variant, input);
382
- if (variant === "type-definition") {
386
+ if (variant === "file-reference") {
387
+ const fileReference = extractFileReference(input);
388
+ if (!fileReference) throw new Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(input)}". 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.`);
389
+ if (!VALID_SOURCE_FILE_EXTENSIONS.includes(findFileExtensionSafe(fileReference.file))) throw new Error(`The provided schema file input "${fileReference.file}" has an invalid file extension. Please ensure that the file has one of the following extensions: ${list(VALID_SOURCE_FILE_EXTENSIONS, { conjunction: "or" })}.`);
383
390
  const resolved = await resolve(context, input, defu(options, { plugins: [esbuildPlugin(context, {
384
391
  reflection: "default",
385
392
  level: "all"
@@ -393,7 +400,7 @@ async function extractSchemaWithSource(context, input, options = {}) {
393
400
  "valibot",
394
401
  "reflection"
395
402
  ].includes(variant)) source = extractSource(variant, input);
396
- else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "type-definition", "json-schema", "standard-schema", "zod3", "untyped", or "reflection".`);
403
+ else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "untyped", or "reflection".`);
397
404
  return {
398
405
  variant,
399
406
  source,
@@ -1 +1 @@
1
- {"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchema","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { isStandardJsonSchema } from \"@stryke/json\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport { toJsonSchema } from \"@valibot/to-json-schema\";\nimport defu from \"defu\";\nimport * as z3 from \"zod/v3\";\nimport { BundleOptions } from \"./bundle\";\nimport { getCacheDirectory, writeSchema } from \"./persistence\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isJsonSchema,\n isJsonSchemaObject,\n isSchema,\n isSchemaWithSource,\n isUntypedInput,\n isUntypedInputStrict,\n isUntypedSchema,\n isUntypedSchemaStrict,\n isValibotSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchema,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema,\n ValibotSchema\n} from \"./types\";\n\nconst SCHEMA_BUNDLE_BASE_URI = \"https://powerlines.invalid/\";\n\nfunction normalizeUri(uri: string): string {\n return uri.endsWith(\"#\") ? uri.slice(0, -1) : uri;\n}\n\nfunction stripUriFragment(uri: string): string {\n const hashIndex = uri.indexOf(\"#\");\n\n return hashIndex >= 0 ? uri.slice(0, hashIndex) : uri;\n}\n\nfunction escapeJsonPointerToken(token: string): string {\n return token.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nfunction toJsonPointer(path: string[]): string {\n if (path.length === 0) {\n return \"\";\n }\n\n return `/${path.map(segment => escapeJsonPointerToken(segment)).join(\"/\")}`;\n}\n\nfunction resolveUri(reference: string, baseUri: string): string {\n try {\n return normalizeUri(new URL(reference, baseUri).toString());\n } catch {\n return normalizeUri(reference);\n }\n}\n\nfunction collectReferenceTargets(\n value: unknown,\n path: string[],\n baseUri: string,\n uriToPointer: Map<string, string>,\n dynamicUriToFragment: Map<string, string>\n): void {\n if (!isSetObject(value)) {\n return;\n }\n\n const schema = value as Record<string, unknown>;\n const pointer = toJsonPointer(path);\n\n const currentBaseUri = isSetString(schema.$id)\n ? resolveUri(schema.$id, baseUri)\n : baseUri;\n\n const currentDocumentUri = stripUriFragment(currentBaseUri);\n\n uriToPointer.set(currentBaseUri, pointer);\n uriToPointer.set(currentDocumentUri, pointer);\n\n if (isSetString(schema.$anchor)) {\n uriToPointer.set(`${currentDocumentUri}#${schema.$anchor}`, pointer);\n }\n\n if (isSetString(schema.$dynamicAnchor)) {\n const dynamicTarget = `${currentDocumentUri}#${schema.$dynamicAnchor}`;\n uriToPointer.set(dynamicTarget, pointer);\n dynamicUriToFragment.set(dynamicTarget, `#${schema.$dynamicAnchor}`);\n }\n\n for (const [key, child] of Object.entries(schema)) {\n if (Array.isArray(child)) {\n child.forEach((entry, index) => {\n collectReferenceTargets(\n entry,\n [...path, key, String(index)],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n });\n continue;\n }\n\n collectReferenceTargets(\n child,\n [...path, key],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n }\n}\n\nfunction rewriteReferenceTargets(\n value: unknown,\n path: string[],\n baseUri: string,\n uriToPointer: Map<string, string>,\n dynamicUriToFragment: Map<string, string>\n): void {\n if (!isSetObject(value)) {\n return;\n }\n\n const schema = value as Record<string, unknown>;\n\n const currentBaseUri = isSetString(schema.$id)\n ? resolveUri(schema.$id, baseUri)\n : baseUri;\n\n if (isSetString(schema.$ref)) {\n const resolvedRefUri = resolveUri(schema.$ref, currentBaseUri);\n const pointer =\n uriToPointer.get(resolvedRefUri) ??\n uriToPointer.get(stripUriFragment(resolvedRefUri));\n\n if (pointer !== undefined) {\n schema.$ref = pointer.length > 0 ? `#${pointer}` : \"#\";\n }\n }\n\n if (isSetString(schema.$dynamicRef)) {\n const resolvedDynamicRefUri = resolveUri(\n schema.$dynamicRef,\n currentBaseUri\n );\n const dynamicFragment = dynamicUriToFragment.get(resolvedDynamicRefUri);\n\n if (dynamicFragment) {\n schema.$dynamicRef = dynamicFragment;\n } else {\n const pointer =\n uriToPointer.get(resolvedDynamicRefUri) ??\n uriToPointer.get(stripUriFragment(resolvedDynamicRefUri));\n\n if (pointer !== undefined) {\n schema.$dynamicRef = pointer.length > 0 ? `#${pointer}` : \"#\";\n }\n }\n }\n\n for (const [key, child] of Object.entries(schema)) {\n if (Array.isArray(child)) {\n child.forEach((entry, index) => {\n rewriteReferenceTargets(\n entry,\n [...path, key, String(index)],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n });\n continue;\n }\n\n rewriteReferenceTargets(\n child,\n [...path, key],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n }\n}\n\n/**\n * 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.\n *\n * @param schema - The JSON Schema to bundle references for.\n * @returns A new JSON Schema with all references bundled and rewritten to point to the bundled definitions.\n */\nexport function bundleReferences(schema: JsonSchema): JsonSchema {\n if (!isSetObject(schema)) {\n return schema;\n }\n\n const bundledSchema = deepClone(schema) as Record<string, unknown>;\n const baseUri = isSetString(bundledSchema.$id)\n ? resolveUri(bundledSchema.$id, SCHEMA_BUNDLE_BASE_URI)\n : SCHEMA_BUNDLE_BASE_URI;\n\n const uriToPointer = new Map<string, string>();\n const dynamicUriToFragment = new Map<string, string>();\n\n collectReferenceTargets(\n bundledSchema,\n [],\n baseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n\n rewriteReferenceTargets(\n bundledSchema,\n [],\n baseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n\n return bundledSchema;\n}\n\nfunction convertNestedUntypedSchema(value: unknown): unknown {\n if (isUntypedSchema(value)) {\n return convertUntypedSchemaToJsonSchema(value);\n }\n\n if (isSetObject(value)) {\n if (isUntypedInput(value)) {\n return convertUntypedInputToJsonSchema(value);\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n return convertUntypedSchemaToJsonSchema(nested.$schema);\n }\n }\n\n return value;\n}\n\nfunction convertNestedUntypedSchemaArray(value: unknown): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n\n return value.map(item => convertNestedUntypedSchema(item));\n}\n\nfunction convertValibotSchemaToJsonSchema(schema: unknown): JsonSchema {\n return toJsonSchema(schema as never, {\n target: \"draft-2020-12\"\n }) as JsonSchema;\n}\n\nfunction convertUntypedSchemaToJsonSchema(\n schema: UntypedSchema | Record<string, unknown>\n): JsonSchema {\n const source = schema as Record<string, unknown>;\n const jsonSchema: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(source)) {\n if (\n key === \"tsType\" ||\n key === \"markdownType\" ||\n key === \"tags\" ||\n key === \"args\" ||\n key === \"resolve\"\n ) {\n continue;\n }\n\n if (key === \"id\" && isSetString(value)) {\n jsonSchema.$id = value;\n continue;\n }\n\n if (\n key === \"properties\" ||\n key === \"patternProperties\" ||\n key === \"dependentSchemas\" ||\n key === \"$defs\" ||\n key === \"definitions\"\n ) {\n if (!isSetObject(value)) {\n jsonSchema[key] = value;\n continue;\n }\n\n jsonSchema[key] = Object.fromEntries(\n Object.entries(value).map(([propertyKey, propertyValue]) => [\n propertyKey,\n convertNestedUntypedSchema(propertyValue)\n ])\n );\n continue;\n }\n\n if (\n key === \"items\" ||\n key === \"contains\" ||\n key === \"if\" ||\n key === \"then\" ||\n key === \"else\" ||\n key === \"not\" ||\n key === \"propertyNames\" ||\n key === \"additionalProperties\" ||\n key === \"unevaluatedProperties\"\n ) {\n jsonSchema[key] = convertNestedUntypedSchema(value);\n continue;\n }\n\n if (key === \"oneOf\" || key === \"anyOf\" || key === \"allOf\") {\n jsonSchema[key] = convertNestedUntypedSchemaArray(value);\n continue;\n }\n\n jsonSchema[key] = value;\n }\n\n return jsonSchema;\n}\n\nfunction convertUntypedInputToJsonSchema(\n input: UntypedInputObject\n): JsonSchema {\n const inputObject = input as Record<string, unknown>;\n const base = isUntypedSchema(inputObject.$schema)\n ? convertUntypedSchemaToJsonSchema(inputObject.$schema)\n : {};\n const properties: Record<string, JsonSchema> = {};\n\n for (const [key, value] of Object.entries(inputObject)) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n if (!isSetObject(value)) {\n continue;\n }\n\n if (isUntypedInput(value)) {\n properties[key] = convertUntypedInputToJsonSchema(value);\n continue;\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n properties[key] = convertUntypedSchemaToJsonSchema(nested.$schema);\n continue;\n }\n\n if (isUntypedSchema(value)) {\n properties[key] = convertUntypedSchemaToJsonSchema(value);\n }\n }\n\n if (!isJsonSchemaObject(base)) {\n throw new Error(\n `Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`\n );\n }\n\n const baseProperties = isSetObject(base.properties) ? base.properties : {};\n const mergedProperties = {\n ...baseProperties,\n ...properties\n };\n\n return {\n ...base,\n type: base.type ?? \"object\",\n ...(Object.keys(mergedProperties).length > 0\n ? { properties: mergedProperties }\n : {})\n };\n}\n\n/**\n * Creates a hash string for a given schema definition input.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (typeof input === \"boolean\") {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchema(input)) {\n return murmurhash({ variant, input });\n } else if (isValibotSchema(input)) {\n return murmurhash({\n variant,\n input: convertValibotSchemaToJsonSchema(input)\n });\n } else if (isUntypedInput(input)) {\n return murmurhash({\n variant,\n input: convertUntypedInputToJsonSchema(input)\n });\n } else if (isUntypedSchema(input)) {\n return murmurhash({\n variant,\n input: convertUntypedSchemaToJsonSchema(input)\n });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link Type} into a JSON Schema (draft-2020-12) representation.\n */\nexport function extractReflection(reflection: Type): JsonSchema | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema(reflection);\n}\n\n/**\n * Extracts a JSON Schema from Zod, Standard Schema, Valibot, untyped, or JSON Schema inputs.\n */\nexport function extractJsonSchema(schema: unknown): JsonSchema | undefined {\n if (isSetObject(schema)) {\n if (isZod3Type(schema)) {\n return extractJsonSchemaZod(schema, {\n target: \"draft-2020-12\"\n }) as JsonSchema;\n }\n if (isUntypedInputStrict(schema)) {\n return convertUntypedInputToJsonSchema(schema);\n }\n if (isUntypedSchemaStrict(schema)) {\n return convertUntypedSchemaToJsonSchema(schema);\n }\n if (isStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n }\n if (isValibotSchema(schema)) {\n return convertValibotSchemaToJsonSchema(schema);\n }\n if (isJsonSchema(schema)) {\n return schema;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves the concrete source variant for a schema source input.\n *\n * @param input - The schema source input to inspect.\n * @returns The resolved schema source variant.\n * @throws Will throw an error when the input cannot be mapped to a supported source variant.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (typeof input === \"boolean\") {\n return \"json-schema\";\n }\n\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isUntypedInputStrict(input) || isUntypedSchemaStrict(input)) {\n return \"untyped\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJsonSchema(input)) {\n return \"json-schema\";\n } else if (isValibotSchema(input)) {\n return \"valibot\";\n } else if (isType(input)) {\n return \"reflection\";\n }\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Determines the top-level input variant for schema extraction.\n *\n * @param input - The schema input to classify.\n * @returns The resolved schema input variant.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts and normalizes a JSON Schema from a concrete schema source input.\n *\n * @param input - The schema source input to extract from.\n * @param variant - Optional source variant override. When omitted, the variant is inferred from the input.\n * @returns A promise that resolves to a bundled JSON Schema.\n * @throws Will throw an error if no valid JSON Schema can be extracted from the input.\n */\nexport async function extractSchema(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JsonSchema> {\n if (isSchemaWithSource(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JsonSchema | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\" ||\n resolvedVariant === \"valibot\"\n ) {\n schema = extractJsonSchema(input);\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection(input as Type);\n }\n\n if (schema) {\n return bundleReferences(schema);\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Builds source metadata for a schema input using a known source variant.\n *\n * @param variant - The schema source variant associated with the input.\n * @param input - The schema source input to wrap.\n * @returns The normalized schema source payload, including the source hash and variant.\n * @throws Will throw an error if the provided variant is unsupported.\n */\nexport function extractSource(\n variant: SchemaSourceVariant,\n input: SchemaSourceInput\n): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchema\n };\n } else if (variant === \"valibot\") {\n return {\n hash: extractHash(variant, input),\n variant: \"valibot\",\n schema: input as ValibotSchema\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * 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 Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using Rolldown to obtain the actual schema definition before extraction.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://zod.dev/\n * @see https://valibot.dev/\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n *\n * @param context - The context object providing access to the file system and cache path.\n * @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 reflected Deepkit Type object. If the input is a string or a type definition reference, it will be resolved and bundled to obtain the actual schema definition before extraction.\n * @param options - Optional overrides for the Rolldown configuration used during extraction. This can include custom plugins, loaders, or other build options to control how the schema definition is resolved and bundled when the input is a type definition reference.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object. The function will attempt to extract a valid JSON Schema from the provided input, and if successful, it will return the schema. If the extraction process fails or if the input is not a valid schema definition, it will throw an error indicating the failure.\n */\nexport async function extractSchemaWithSource(\n context: Context,\n input: SchemaInput,\n options: BundleOptions = {}\n): Promise<ExtractedSchema> {\n if (isSchemaWithSource(input)) {\n return input;\n }\n\n if (isSchema(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"json-schema\", input.schema),\n variant: \"json-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n if (variant === \"type-definition\") {\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as TypeDefinitionReference,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"valibot\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"type-definition\", \"json-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchema(source.schema, source.variant),\n hash\n };\n}\n\n/**\n * 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 Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using Rolldown to obtain the actual schema definition before extraction.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://zod.dev/\n * @see https://valibot.dev/\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The context object providing access to the file system and cache path.\n * @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 reflected Deepkit Type object.\n * @param options - Optional overrides for the Rolldown configuration used during extraction.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.\n * @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.\n */\nexport async function extract(\n context: Context,\n input: SchemaInput,\n options: BundleOptions = {}\n): Promise<Schema> {\n if (isSchemaWithSource(input) || isSchema(input)) {\n return input;\n }\n\n let result: Schema | undefined;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n const cacheFilePath = joinPaths(getCacheDirectory(context), `${hash}.json`);\n if (\n context.config.skipCache !== true &&\n context.fs.existsSync(cacheFilePath)\n ) {\n const schema = await context.fs.read(cacheFilePath);\n if (schema) {\n result = {\n variant,\n hash,\n schema: JSON.parse(schema) as JsonSchema\n };\n }\n }\n\n result ??= await extractSchemaWithSource(context, input, options);\n if (!result?.schema) {\n throw new Error(\n `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.`\n );\n }\n\n if (context.config.skipCache !== true) {\n await writeSchema(context, result);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkEA,MAAM,yBAAyB;AAE/B,SAAS,aAAa,KAAqB;CACzC,OAAO,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AAChD;AAEA,SAAS,iBAAiB,KAAqB;CAC7C,MAAM,YAAY,IAAI,QAAQ,GAAG;CAEjC,OAAO,aAAa,IAAI,IAAI,MAAM,GAAG,SAAS,IAAI;AACpD;AAEA,SAAS,uBAAuB,OAAuB;CACrD,OAAO,MAAM,WAAW,KAAK,IAAI,EAAE,WAAW,KAAK,IAAI;AACzD;AAEA,SAAS,cAAc,MAAwB;CAC7C,IAAI,KAAK,WAAW,GAClB,OAAO;CAGT,OAAO,IAAI,KAAK,KAAI,YAAW,uBAAuB,OAAO,CAAC,EAAE,KAAK,GAA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;GACP;GACA;GACA,QAAQ,KAAK,MAAM,MAAM;EAC3B;CAEJ;CAEA,WAAW,MAAM,wBAAwB,SAAS,OAAO,OAAO;CAChE,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MACR,+NACF;CAGF,IAAI,QAAQ,OAAO,cAAc,MAC/B,MAAM,YAAY,SAAS,MAAM;CAGnC,OAAO;AACT"}
1
+ {"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchema","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isFileReference } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { extractFileReference } from \"@stryke/convert/extract-file-reference\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { deepClone } from \"@stryke/helpers/deep-clone\";\nimport { isStandardJsonSchema } from \"@stryke/json\";\nimport { findFileExtensionSafe } from \"@stryke/path/find\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { list } from \"@stryke/string-format/list\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { FileReferenceInput } from \"@stryke/types\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport { toJsonSchema } from \"@valibot/to-json-schema\";\nimport defu from \"defu\";\nimport * as z3 from \"zod/v3\";\nimport { BundleOptions } from \"./bundle\";\nimport { VALID_SOURCE_FILE_EXTENSIONS } from \"./constants\";\nimport { getCacheDirectory, writeSchema } from \"./persistence\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isJsonSchema,\n isJsonSchemaObject,\n isSchema,\n isSchemaWithSource,\n isUntypedInput,\n isUntypedInputStrict,\n isUntypedSchema,\n isUntypedSchemaStrict,\n isValibotSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchema,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n UntypedInputObject,\n UntypedSchema,\n ValibotSchema\n} from \"./types\";\n\nconst SCHEMA_BUNDLE_BASE_URI = \"https://powerlines.invalid/\";\n\nfunction normalizeUri(uri: string): string {\n return uri.endsWith(\"#\") ? uri.slice(0, -1) : uri;\n}\n\nfunction stripUriFragment(uri: string): string {\n const hashIndex = uri.indexOf(\"#\");\n\n return hashIndex >= 0 ? uri.slice(0, hashIndex) : uri;\n}\n\nfunction escapeJsonPointerToken(token: string): string {\n return token.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\");\n}\n\nfunction toJsonPointer(path: string[]): string {\n if (path.length === 0) {\n return \"\";\n }\n\n return `/${path.map(segment => escapeJsonPointerToken(segment)).join(\"/\")}`;\n}\n\nfunction resolveUri(reference: string, baseUri: string): string {\n try {\n return normalizeUri(new URL(reference, baseUri).toString());\n } catch {\n return normalizeUri(reference);\n }\n}\n\nfunction collectReferenceTargets(\n value: unknown,\n path: string[],\n baseUri: string,\n uriToPointer: Map<string, string>,\n dynamicUriToFragment: Map<string, string>\n): void {\n if (!isSetObject(value)) {\n return;\n }\n\n const schema = value as Record<string, unknown>;\n const pointer = toJsonPointer(path);\n\n const currentBaseUri = isSetString(schema.$id)\n ? resolveUri(schema.$id, baseUri)\n : baseUri;\n\n const currentDocumentUri = stripUriFragment(currentBaseUri);\n\n uriToPointer.set(currentBaseUri, pointer);\n uriToPointer.set(currentDocumentUri, pointer);\n\n if (isSetString(schema.$anchor)) {\n uriToPointer.set(`${currentDocumentUri}#${schema.$anchor}`, pointer);\n }\n\n if (isSetString(schema.$dynamicAnchor)) {\n const dynamicTarget = `${currentDocumentUri}#${schema.$dynamicAnchor}`;\n uriToPointer.set(dynamicTarget, pointer);\n dynamicUriToFragment.set(dynamicTarget, `#${schema.$dynamicAnchor}`);\n }\n\n for (const [key, child] of Object.entries(schema)) {\n if (Array.isArray(child)) {\n child.forEach((entry, index) => {\n collectReferenceTargets(\n entry,\n [...path, key, String(index)],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n });\n continue;\n }\n\n collectReferenceTargets(\n child,\n [...path, key],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n }\n}\n\nfunction rewriteReferenceTargets(\n value: unknown,\n path: string[],\n baseUri: string,\n uriToPointer: Map<string, string>,\n dynamicUriToFragment: Map<string, string>\n): void {\n if (!isSetObject(value)) {\n return;\n }\n\n const schema = value as Record<string, unknown>;\n\n const currentBaseUri = isSetString(schema.$id)\n ? resolveUri(schema.$id, baseUri)\n : baseUri;\n\n if (isSetString(schema.$ref)) {\n const resolvedRefUri = resolveUri(schema.$ref, currentBaseUri);\n const pointer =\n uriToPointer.get(resolvedRefUri) ??\n uriToPointer.get(stripUriFragment(resolvedRefUri));\n\n if (pointer !== undefined) {\n schema.$ref = pointer.length > 0 ? `#${pointer}` : \"#\";\n }\n }\n\n if (isSetString(schema.$dynamicRef)) {\n const resolvedDynamicRefUri = resolveUri(\n schema.$dynamicRef,\n currentBaseUri\n );\n const dynamicFragment = dynamicUriToFragment.get(resolvedDynamicRefUri);\n\n if (dynamicFragment) {\n schema.$dynamicRef = dynamicFragment;\n } else {\n const pointer =\n uriToPointer.get(resolvedDynamicRefUri) ??\n uriToPointer.get(stripUriFragment(resolvedDynamicRefUri));\n\n if (pointer !== undefined) {\n schema.$dynamicRef = pointer.length > 0 ? `#${pointer}` : \"#\";\n }\n }\n }\n\n for (const [key, child] of Object.entries(schema)) {\n if (Array.isArray(child)) {\n child.forEach((entry, index) => {\n rewriteReferenceTargets(\n entry,\n [...path, key, String(index)],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n });\n continue;\n }\n\n rewriteReferenceTargets(\n child,\n [...path, key],\n currentBaseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n }\n}\n\n/**\n * 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.\n *\n * @param schema - The JSON Schema to bundle references for.\n * @returns A new JSON Schema with all references bundled and rewritten to point to the bundled definitions.\n */\nexport function bundleReferences(schema: JsonSchema): JsonSchema {\n if (!isSetObject(schema)) {\n return schema;\n }\n\n const bundledSchema = deepClone(schema) as Record<string, unknown>;\n const baseUri = isSetString(bundledSchema.$id)\n ? resolveUri(bundledSchema.$id, SCHEMA_BUNDLE_BASE_URI)\n : SCHEMA_BUNDLE_BASE_URI;\n\n const uriToPointer = new Map<string, string>();\n const dynamicUriToFragment = new Map<string, string>();\n\n collectReferenceTargets(\n bundledSchema,\n [],\n baseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n\n rewriteReferenceTargets(\n bundledSchema,\n [],\n baseUri,\n uriToPointer,\n dynamicUriToFragment\n );\n\n return bundledSchema;\n}\n\nfunction convertNestedUntypedSchema(value: unknown): unknown {\n if (isUntypedSchema(value)) {\n return convertUntypedSchemaToJsonSchema(value);\n }\n\n if (isSetObject(value)) {\n if (isUntypedInput(value)) {\n return convertUntypedInputToJsonSchema(value);\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n return convertUntypedSchemaToJsonSchema(nested.$schema);\n }\n }\n\n return value;\n}\n\nfunction convertNestedUntypedSchemaArray(value: unknown): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n\n return value.map(item => convertNestedUntypedSchema(item));\n}\n\nfunction convertValibotSchemaToJsonSchema(schema: unknown): JsonSchema {\n return toJsonSchema(schema as never, {\n target: \"draft-2020-12\"\n }) as JsonSchema;\n}\n\nfunction convertUntypedSchemaToJsonSchema(\n schema: UntypedSchema | Record<string, unknown>\n): JsonSchema {\n const source = schema as Record<string, unknown>;\n const jsonSchema: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(source)) {\n if (\n key === \"tsType\" ||\n key === \"markdownType\" ||\n key === \"tags\" ||\n key === \"args\" ||\n key === \"resolve\"\n ) {\n continue;\n }\n\n if (key === \"id\" && isSetString(value)) {\n jsonSchema.$id = value;\n continue;\n }\n\n if (\n key === \"properties\" ||\n key === \"patternProperties\" ||\n key === \"dependentSchemas\" ||\n key === \"$defs\" ||\n key === \"definitions\"\n ) {\n if (!isSetObject(value)) {\n jsonSchema[key] = value;\n continue;\n }\n\n jsonSchema[key] = Object.fromEntries(\n Object.entries(value).map(([propertyKey, propertyValue]) => [\n propertyKey,\n convertNestedUntypedSchema(propertyValue)\n ])\n );\n continue;\n }\n\n if (\n key === \"items\" ||\n key === \"contains\" ||\n key === \"if\" ||\n key === \"then\" ||\n key === \"else\" ||\n key === \"not\" ||\n key === \"propertyNames\" ||\n key === \"additionalProperties\" ||\n key === \"unevaluatedProperties\"\n ) {\n jsonSchema[key] = convertNestedUntypedSchema(value);\n continue;\n }\n\n if (key === \"oneOf\" || key === \"anyOf\" || key === \"allOf\") {\n jsonSchema[key] = convertNestedUntypedSchemaArray(value);\n continue;\n }\n\n jsonSchema[key] = value;\n }\n\n return jsonSchema;\n}\n\nfunction convertUntypedInputToJsonSchema(\n input: UntypedInputObject\n): JsonSchema {\n const inputObject = input as Record<string, unknown>;\n const base = isUntypedSchema(inputObject.$schema)\n ? convertUntypedSchemaToJsonSchema(inputObject.$schema)\n : {};\n const properties: Record<string, JsonSchema> = {};\n\n for (const [key, value] of Object.entries(inputObject)) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n if (!isSetObject(value)) {\n continue;\n }\n\n if (isUntypedInput(value)) {\n properties[key] = convertUntypedInputToJsonSchema(value);\n continue;\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n properties[key] = convertUntypedSchemaToJsonSchema(nested.$schema);\n continue;\n }\n\n if (isUntypedSchema(value)) {\n properties[key] = convertUntypedSchemaToJsonSchema(value);\n }\n }\n\n if (!isJsonSchemaObject(base)) {\n throw new Error(\n `Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`\n );\n }\n\n const baseProperties = isSetObject(base.properties) ? base.properties : {};\n const mergedProperties = {\n ...baseProperties,\n ...properties\n };\n\n return {\n ...base,\n type: base.type ?? \"object\",\n ...(Object.keys(mergedProperties).length > 0\n ? { properties: mergedProperties }\n : {})\n };\n}\n\n/**\n * Creates a hash string for a given schema definition input.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (typeof input === \"boolean\") {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchema(input)) {\n return murmurhash({ variant, input });\n } else if (isValibotSchema(input)) {\n return murmurhash({\n variant,\n input: convertValibotSchemaToJsonSchema(input)\n });\n } else if (isUntypedInput(input)) {\n return murmurhash({\n variant,\n input: convertUntypedInputToJsonSchema(input)\n });\n } else if (isUntypedSchema(input)) {\n return murmurhash({\n variant,\n input: convertUntypedSchemaToJsonSchema(input)\n });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link Type} into a JSON Schema (draft-2020-12) representation.\n */\nexport function extractReflection(reflection: Type): JsonSchema | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema(reflection);\n}\n\n/**\n * Extracts a JSON Schema from Zod, Standard Schema, Valibot, untyped, or JSON Schema inputs.\n */\nexport function extractJsonSchema(schema: unknown): JsonSchema | undefined {\n if (isSetObject(schema)) {\n if (isZod3Type(schema)) {\n return extractJsonSchemaZod(schema, {\n target: \"draft-2020-12\"\n }) as JsonSchema;\n }\n if (isUntypedInputStrict(schema)) {\n return convertUntypedInputToJsonSchema(schema);\n }\n if (isUntypedSchemaStrict(schema)) {\n return convertUntypedSchemaToJsonSchema(schema);\n }\n if (isStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n }\n if (isValibotSchema(schema)) {\n return convertValibotSchemaToJsonSchema(schema);\n }\n if (isJsonSchema(schema)) {\n return schema;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves the concrete source variant for a schema source input.\n *\n * @param input - The schema source input to inspect.\n * @returns The resolved schema source variant.\n * @throws Will throw an error when the input cannot be mapped to a supported source variant.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (typeof input === \"boolean\") {\n return \"json-schema\";\n }\n\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isUntypedInputStrict(input) || isUntypedSchemaStrict(input)) {\n return \"untyped\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJsonSchema(input)) {\n return \"json-schema\";\n } else if (isValibotSchema(input)) {\n return \"valibot\";\n } else if (isType(input)) {\n return \"reflection\";\n }\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Determines the top-level input variant for schema extraction.\n *\n * @param input - The schema input to classify.\n * @returns The resolved schema input variant.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isFileReference(input)) {\n return \"file-reference\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts and normalizes a JSON Schema from a concrete schema source input.\n *\n * @param input - The schema source input to extract from.\n * @param variant - Optional source variant override. When omitted, the variant is inferred from the input.\n * @returns A promise that resolves to a bundled JSON Schema.\n * @throws Will throw an error if no valid JSON Schema can be extracted from the input.\n */\nexport async function extractSchema(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JsonSchema> {\n if (isSchemaWithSource(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JsonSchema | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\" ||\n resolvedVariant === \"valibot\"\n ) {\n schema = extractJsonSchema(input);\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection(input as Type);\n }\n\n if (schema) {\n return bundleReferences(schema);\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * Builds source metadata for a schema input using a known source variant.\n *\n * @param variant - The schema source variant associated with the input.\n * @param input - The schema source input to wrap.\n * @returns The normalized schema source payload, including the source hash and variant.\n * @throws Will throw an error if the provided variant is unsupported.\n */\nexport function extractSource(\n variant: SchemaSourceVariant,\n input: SchemaSourceInput\n): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchema\n };\n } else if (variant === \"valibot\") {\n return {\n hash: extractHash(variant, input),\n variant: \"valibot\",\n schema: input as ValibotSchema\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n }\n\n throw new Error(\n `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.`\n );\n}\n\n/**\n * 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 Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using Rolldown to obtain the actual schema definition before extraction.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://zod.dev/\n * @see https://valibot.dev/\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n *\n * @param context - The context object providing access to the file system and cache path.\n * @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 reflected Deepkit Type object. If the input is a string or a type definition reference, it will be resolved and bundled to obtain the actual schema definition before extraction.\n * @param options - Optional overrides for the Rolldown configuration used during extraction. This can include custom plugins, loaders, or other build options to control how the schema definition is resolved and bundled when the input is a type definition reference.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object. The function will attempt to extract a valid JSON Schema from the provided input, and if successful, it will return the schema. If the extraction process fails or if the input is not a valid schema definition, it will throw an error indicating the failure.\n */\nexport async function extractSchemaWithSource(\n context: Context,\n input: SchemaInput,\n options: BundleOptions = {}\n): Promise<ExtractedSchema> {\n if (isSchemaWithSource(input)) {\n return input;\n }\n\n if (isSchema(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"json-schema\", input.schema),\n variant: \"json-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n if (variant === \"file-reference\") {\n const fileReference = extractFileReference(input as FileReferenceInput);\n if (!fileReference) {\n throw new Error(\n `Failed to extract a valid file reference from the provided input \"${JSON.stringify(\n input\n )}\". 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.`\n );\n }\n\n if (\n !VALID_SOURCE_FILE_EXTENSIONS.includes(\n findFileExtensionSafe(fileReference.file)\n )\n ) {\n throw new Error(\n `The provided schema file input \"${\n fileReference.file\n }\" has an invalid file extension. Please ensure that the file has one of the following extensions: ${list(\n VALID_SOURCE_FILE_EXTENSIONS,\n { conjunction: \"or\" }\n )}.`\n );\n }\n\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as FileReferenceInput,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"valibot\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"file-reference\", \"json-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchema(source.schema, source.variant),\n hash\n };\n}\n\n/**\n * 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 Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using Rolldown to obtain the actual schema definition before extraction.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://zod.dev/\n * @see https://valibot.dev/\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The context object providing access to the file system and cache path.\n * @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 reflected Deepkit Type object.\n * @param options - Optional overrides for the Rolldown configuration used during extraction.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.\n * @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.\n */\nexport async function extract(\n context: Context,\n input: SchemaInput,\n options: BundleOptions = {}\n): Promise<Schema> {\n if (isSchemaWithSource(input) || isSchema(input)) {\n return input;\n }\n\n let result: Schema | undefined;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n const cacheFilePath = joinPaths(getCacheDirectory(context), `${hash}.json`);\n if (\n context.config.skipCache !== true &&\n context.fs.existsSync(cacheFilePath)\n ) {\n const schema = await context.fs.read(cacheFilePath);\n if (schema) {\n result = {\n variant,\n hash,\n schema: JSON.parse(schema) as JsonSchema\n };\n }\n }\n\n result ??= await extractSchemaWithSource(context, input, options);\n if (!result?.schema) {\n throw new Error(\n `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.`\n );\n }\n\n if (context.config.skipCache !== true) {\n await writeSchema(context, result);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsEA,MAAM,yBAAyB;AAE/B,SAAS,aAAa,KAAqB;CACzC,OAAO,IAAI,SAAS,GAAG,IAAI,IAAI,MAAM,GAAG,EAAE,IAAI;AAChD;AAEA,SAAS,iBAAiB,KAAqB;CAC7C,MAAM,YAAY,IAAI,QAAQ,GAAG;CAEjC,OAAO,aAAa,IAAI,IAAI,MAAM,GAAG,SAAS,IAAI;AACpD;AAEA,SAAS,uBAAuB,OAAuB;CACrD,OAAO,MAAM,WAAW,KAAK,IAAI,EAAE,WAAW,KAAK,IAAI;AACzD;AAEA,SAAS,cAAc,MAAwB;CAC7C,IAAI,KAAK,WAAW,GAClB,OAAO;CAGT,OAAO,IAAI,KAAK,KAAI,YAAW,uBAAuB,OAAO,CAAC,EAAE,KAAK,GAAG;AAC1E;AAEA,SAAS,WAAW,WAAmB,SAAyB;CAC9D,IAAI;EACF,OAAO,aAAa,IAAI,IAAI,WAAW,OAAO,EAAE,SAAS,CAAC;CAC5D,QAAQ;EACN,OAAO,aAAa,SAAS;CAC/B;AACF;AAEA,SAAS,wBACP,OACA,MACA,SACA,cACA,sBACM;CACN,IAAI,CAACA,cAAY,KAAK,GACpB;CAGF,MAAM,SAAS;CACf,MAAM,UAAU,cAAc,IAAI;CAElC,MAAM,iBAAiB,YAAY,OAAO,GAAG,IACzC,WAAW,OAAO,KAAK,OAAO,IAC9B;CAEJ,MAAM,qBAAqB,iBAAiB,cAAc;CAE1D,aA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IAAI,QAAQ,OAAO,cAAc,MAC/B,MAAM,YAAY,SAAS,MAAM;CAGnC,OAAO;AACT"}
package/dist/helpers.cjs CHANGED
@@ -1,10 +1,43 @@
1
+ const require_constants = require('./constants.cjs');
1
2
  const require_metadata = require('./metadata.cjs');
2
3
  const require_type_checks = require('./type-checks.cjs');
3
4
  let defu = require("defu");
4
5
  let _stryke_type_checks = require("@stryke/type-checks");
6
+ let _stryke_helpers_get_unique = require("@stryke/helpers/get-unique");
7
+ let _stryke_path_find = require("@stryke/path/find");
5
8
 
6
9
  //#region src/helpers.ts
7
10
  /**
11
+ * Retrieves the JSON Schema from a Schema wrapper or returns the input if it's already a JSON Schema.
12
+ *
13
+ * @remarks
14
+ * This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
15
+ *
16
+ * @param input - The input which can be either a Schema wrapper or a JSON Schema object.
17
+ * @returns The JSON Schema object.
18
+ * @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
19
+ */
20
+ function getJsonSchema(input) {
21
+ const schema = require_type_checks.isSchema(input) ? input.schema : input;
22
+ if (!require_type_checks.isJsonSchema(schema)) throw new TypeError("The provided input is not a valid JSON Schema");
23
+ return schema;
24
+ }
25
+ /**
26
+ * Retrieves the JSON Schema in Object form from a Schema wrapper or returns the input if it's already a JSON Schema.
27
+ *
28
+ * @remarks
29
+ * This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema object, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
30
+ *
31
+ * @param input - The input which can be either a Schema wrapper or a JSON Schema object.
32
+ * @returns The JSON Schema object.
33
+ * @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
34
+ */
35
+ function getJsonSchemaObject(input) {
36
+ const schema = getJsonSchema(input);
37
+ if (!require_type_checks.isJsonSchemaObject(schema)) throw new TypeError("The provided input is not a valid JSON Schema object");
38
+ return schema;
39
+ }
40
+ /**
8
41
  * Extracts object properties from a JSON Schema object form.
9
42
  *
10
43
  * @remarks
@@ -15,8 +48,7 @@ let _stryke_type_checks = require("@stryke/type-checks");
15
48
  */
16
49
  function getProperties(obj) {
17
50
  const properties = {};
18
- const schema = require_type_checks.isSchema(obj) ? obj.schema : obj;
19
- if (!require_type_checks.isJsonSchemaObject(schema)) return properties;
51
+ const schema = getJsonSchemaObject(obj);
20
52
  if (!(0, _stryke_type_checks.isSetObject)(schema.properties)) return properties;
21
53
  for (const [key, value] of Object.entries(schema.properties)) {
22
54
  const propertySchema = {};
@@ -54,8 +86,7 @@ function getPropertiesList(obj) {
54
86
  * @throws Will throw an error if the provided schema is not an object form.
55
87
  */
56
88
  function addProperty(obj, name, property) {
57
- const schema = require_type_checks.isSchema(obj) ? obj.schema : obj;
58
- if (!require_type_checks.isJsonSchemaObject(schema)) throw new Error("Cannot add property to non-object schema");
89
+ const schema = getJsonSchemaObject(obj);
59
90
  schema.properties ??= {};
60
91
  schema.required ??= [];
61
92
  schema.properties[name] = {
@@ -66,20 +97,19 @@ function addProperty(obj, name, property) {
66
97
  if (schema.required.length === 0) delete schema.required;
67
98
  }
68
99
  /**
69
- * Merges multiple JSON Schema object forms into one.
100
+ * Merges multiple JSON Schemas into one.
70
101
  *
71
102
  * @remarks
72
- * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
103
+ * This function takes multiple JSON Schemas or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
73
104
  *
74
- * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
75
- * @returns A new JSON Schema object that is the result of merging all input schemas.
105
+ * @param schemas - An array of JSON Schemas or Schema wrappers to merge.
106
+ * @returns A new JSON Schema that is the result of merging all input schemas.
76
107
  */
77
- function mergeSchemas(...schemas) {
78
- const result = {};
79
- for (const schema of schemas) {
80
- const jsonSchema = require_type_checks.isSchema(schema) ? schema.schema : schema;
81
- if (!require_type_checks.isJsonSchemaObject(jsonSchema)) continue;
82
- (0, defu.defu)(result, jsonSchema);
108
+ function merge(...schemas) {
109
+ let result = {};
110
+ for (const schema of schemas.reverse()) if (!result.type || result.type === schema.type) {
111
+ result = (0, defu.defu)(result, getJsonSchema(schema));
112
+ if (require_type_checks.isJsonSchemaObject(result)) result.required = (0, _stryke_helpers_get_unique.getUnique)(result.required ?? []);
83
113
  }
84
114
  return result;
85
115
  }
@@ -111,11 +141,23 @@ function isPropertyOptional(parent, propertyName) {
111
141
  if (!parent.properties?.[propertyName]) throw new Error(`The property "${propertyName}" does not exist in the parent schema.`);
112
142
  return !(parent.required ?? []).includes(propertyName);
113
143
  }
144
+ /**
145
+ * Checks if a given file name has a valid schema input file extension.
146
+ *
147
+ * @param fileName - The file name to check for a valid schema input extension.
148
+ * @returns `true` if the file name has a valid schema input extension, otherwise `false`.
149
+ */
150
+ function isValidSchemaInputFile(fileName) {
151
+ return require_constants.VALID_SOURCE_FILE_EXTENSIONS.includes((0, _stryke_path_find.findFileExtensionSafe)(fileName));
152
+ }
114
153
 
115
154
  //#endregion
116
155
  exports.addProperty = addProperty;
156
+ exports.getJsonSchema = getJsonSchema;
157
+ exports.getJsonSchemaObject = getJsonSchemaObject;
117
158
  exports.getProperties = getProperties;
118
159
  exports.getPropertiesList = getPropertiesList;
119
160
  exports.isPropertyOptional = isPropertyOptional;
120
161
  exports.isSchemaNullable = isSchemaNullable;
121
- exports.mergeSchemas = mergeSchemas;
162
+ exports.isValidSchemaInputFile = isValidSchemaInputFile;
163
+ exports.merge = merge;
@@ -6,6 +6,28 @@ type GetPropertiesResult = JsonSchema & {
6
6
  required: boolean;
7
7
  default?: unknown;
8
8
  };
9
+ /**
10
+ * Retrieves the JSON Schema from a Schema wrapper or returns the input if it's already a JSON Schema.
11
+ *
12
+ * @remarks
13
+ * This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
14
+ *
15
+ * @param input - The input which can be either a Schema wrapper or a JSON Schema object.
16
+ * @returns The JSON Schema object.
17
+ * @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
18
+ */
19
+ declare function getJsonSchema(input: Schema | JsonSchema): JsonSchema;
20
+ /**
21
+ * Retrieves the JSON Schema in Object form from a Schema wrapper or returns the input if it's already a JSON Schema.
22
+ *
23
+ * @remarks
24
+ * This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema object, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
25
+ *
26
+ * @param input - The input which can be either a Schema wrapper or a JSON Schema object.
27
+ * @returns The JSON Schema object.
28
+ * @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
29
+ */
30
+ declare function getJsonSchemaObject(input: Schema | JsonSchema): JsonSchemaObject;
9
31
  /**
10
32
  * Extracts object properties from a JSON Schema object form.
11
33
  *
@@ -47,15 +69,15 @@ declare function getPropertiesList(obj: Schema | JsonSchemaObject): (JsonSchema
47
69
  */
48
70
  declare function addProperty(obj: Schema | JsonSchemaObject, name: string, property: JsonSchema): void;
49
71
  /**
50
- * Merges multiple JSON Schema object forms into one.
72
+ * Merges multiple JSON Schemas into one.
51
73
  *
52
74
  * @remarks
53
- * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
75
+ * This function takes multiple JSON Schemas or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
54
76
  *
55
- * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
56
- * @returns A new JSON Schema object that is the result of merging all input schemas.
77
+ * @param schemas - An array of JSON Schemas or Schema wrappers to merge.
78
+ * @returns A new JSON Schema that is the result of merging all input schemas.
57
79
  */
58
- declare function mergeSchemas(...schemas: (JsonSchema | Schema)[]): JsonSchema;
80
+ declare function merge(...schemas: (JsonSchema | Schema)[]): JsonSchema;
59
81
  /**
60
82
  * Returns whether a JSON Schema fragment accepts `null`.
61
83
  *
@@ -77,6 +99,13 @@ declare function isSchemaNullable(schema?: JsonSchema): boolean;
77
99
  * @returns `true` if the property is optional, otherwise `false`.
78
100
  */
79
101
  declare function isPropertyOptional(parent: JsonSchemaObject, propertyName: string): boolean;
102
+ /**
103
+ * Checks if a given file name has a valid schema input file extension.
104
+ *
105
+ * @param fileName - The file name to check for a valid schema input extension.
106
+ * @returns `true` if the file name has a valid schema input extension, otherwise `false`.
107
+ */
108
+ declare function isValidSchemaInputFile(fileName: string): boolean;
80
109
  //#endregion
81
- export { GetPropertiesResult, addProperty, getProperties, getPropertiesList, isPropertyOptional, isSchemaNullable, mergeSchemas };
110
+ export { GetPropertiesResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge };
82
111
  //# sourceMappingURL=helpers.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;KAwBY,mBAAA,GAAsB,UAAU;EAC1C,IAAA;EACA,QAAA;EACA,OAAA;AAAA;;;;;;;AAAO;AAYT;;iBAAgB,aAAA,CACd,GAAA,EAAK,MAAA,GAAS,gBAAA,GACb,MAAA,SAED,UAAA;EAA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