@powerlines/schema 0.11.25 → 0.11.27

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.
Files changed (57) hide show
  1. package/dist/bundle.mjs.map +1 -1
  2. package/dist/codegen.cjs +49 -6
  3. package/dist/codegen.d.cts +21 -3
  4. package/dist/codegen.d.cts.map +1 -1
  5. package/dist/codegen.d.mts +21 -3
  6. package/dist/codegen.d.mts.map +1 -1
  7. package/dist/codegen.mjs +44 -3
  8. package/dist/codegen.mjs.map +1 -1
  9. package/dist/constants.cjs +19 -0
  10. package/dist/constants.d.cts +17 -0
  11. package/dist/constants.d.cts.map +1 -0
  12. package/dist/constants.d.mts +17 -0
  13. package/dist/constants.d.mts.map +1 -0
  14. package/dist/constants.mjs +18 -0
  15. package/dist/constants.mjs.map +1 -0
  16. package/dist/extract.cjs +23 -4
  17. package/dist/extract.d.cts.map +1 -1
  18. package/dist/extract.d.mts.map +1 -1
  19. package/dist/extract.mjs +23 -4
  20. package/dist/extract.mjs.map +1 -1
  21. package/dist/helpers.cjs +94 -0
  22. package/dist/helpers.d.cts +44 -0
  23. package/dist/helpers.d.cts.map +1 -0
  24. package/dist/helpers.d.mts +44 -0
  25. package/dist/helpers.d.mts.map +1 -0
  26. package/dist/helpers.mjs +90 -0
  27. package/dist/helpers.mjs.map +1 -0
  28. package/dist/index.cjs +19 -2
  29. package/dist/index.d.cts +7 -4
  30. package/dist/index.d.mts +7 -4
  31. package/dist/index.mjs +6 -3
  32. package/dist/jtd.mjs.map +1 -1
  33. package/dist/persistence.cjs +76 -0
  34. package/dist/persistence.d.cts +47 -0
  35. package/dist/persistence.d.cts.map +1 -0
  36. package/dist/persistence.d.mts +47 -0
  37. package/dist/persistence.d.mts.map +1 -0
  38. package/dist/persistence.mjs +71 -0
  39. package/dist/persistence.mjs.map +1 -0
  40. package/dist/reflection.cjs +13 -6
  41. package/dist/reflection.d.cts.map +1 -1
  42. package/dist/reflection.d.mts.map +1 -1
  43. package/dist/reflection.mjs +12 -6
  44. package/dist/reflection.mjs.map +1 -1
  45. package/dist/resolve.mjs.map +1 -1
  46. package/dist/type-checks.cjs +21 -2
  47. package/dist/type-checks.d.cts +16 -2
  48. package/dist/type-checks.d.cts.map +1 -1
  49. package/dist/type-checks.d.mts +16 -2
  50. package/dist/type-checks.d.mts.map +1 -1
  51. package/dist/type-checks.mjs +21 -4
  52. package/dist/type-checks.mjs.map +1 -1
  53. package/dist/types.d.cts +42 -12
  54. package/dist/types.d.cts.map +1 -1
  55. package/dist/types.d.mts +42 -12
  56. package/dist/types.d.mts.map +1 -1
  57. package/package.json +19 -7
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.mjs","names":[],"sources":["../src/bundle.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 {\n CreateUnpluginResolverOptions,\n ResolveOptions,\n UnresolvedContext\n} from \"@powerlines/core\";\nimport { createUnpluginResolver } from \"@powerlines/core/lib/unplugin\";\nimport { resolveOptions } from \"@powerlines/unplugin/esbuild\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { DeepPartial } from \"@stryke/types/base\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport { build, OutputFile } from \"esbuild\";\nimport { createEsbuildPlugin } from \"unplugin\";\n\nexport type BundleOptions = DeepPartial<BuildOptions> & {\n name?: string;\n resolve?: DeepPartial<ResolveOptions>;\n};\n\n/**\n * Bundle a type definition to a module.\n *\n * @param context - The context object containing the environment paths.\n * @param file - The file path to bundle.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the bundled module.\n */\nexport async function bundle<TContext extends UnresolvedContext>(\n context: TContext,\n file: string,\n options: BundleOptions = {}\n): Promise<OutputFile> {\n const path = await context.fs.resolve(file);\n if (!path || !context.fs.existsSync(path)) {\n throw new Error(\n `Module not found: \"${file}\". Please check the path and try again.`\n );\n }\n\n const result = await build(\n defu(\n {\n entryPoints: [path],\n write: false,\n sourcemap: false,\n splitting: false,\n treeShaking: true,\n bundle: true,\n packages: \"bundle\",\n platform: \"node\",\n logLevel: \"silent\",\n ...omit(options, [\"name\", \"resolve\"])\n },\n resolveOptions(context),\n {\n plugins: [\n createEsbuildPlugin(\n createUnpluginResolver(context, {\n name: options.name ?? `${findFileName(file)} Bundler`,\n prefix: false,\n overrides: defu(\n options.resolve ?? {},\n { skipNodeModulesBundle: false },\n context.config.resolve\n ) as CreateUnpluginResolverOptions[\"overrides\"],\n silenceHookLogging: true\n })\n )()\n ]\n }\n )\n );\n if (result.errors.length > 0) {\n throw new Error(\n `Failed to bundle ${file}: ${result.errors\n .map(error => error.text)\n .join(\", \")}`\n );\n }\n if (result.warnings.length > 0) {\n context.warn(\n `Warnings while bundling ${file}: ${result.warnings\n .map(warning => warning.text)\n .join(\", \")}`\n );\n }\n if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) {\n throw new Error(\n `No output files generated for ${\n file\n }. Please check the configuration and try again.`\n );\n }\n\n return result.outputFiles.filter(Boolean)[0]!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8CA,eAAsB,OACpB,SACA,MACA,UAAyB,EAAE,EACN;CACrB,MAAM,OAAO,MAAM,QAAQ,GAAG,QAAQ,KAAK;AAC3C,KAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,WAAW,KAAK,CACvC,OAAM,IAAI,MACR,sBAAsB,KAAK,yCAC5B;CAGH,MAAM,SAAS,MAAM,MACnB,KACE;EACE,aAAa,CAAC,KAAK;EACnB,OAAO;EACP,WAAW;EACX,WAAW;EACX,aAAa;EACb,QAAQ;EACR,UAAU;EACV,UAAU;EACV,UAAU;EACV,GAAG,KAAK,SAAS,CAAC,QAAQ,UAAU,CAAC;EACtC,EACD,eAAe,QAAQ,EACvB,EACE,SAAS,CACP,oBACE,uBAAuB,SAAS;EAC9B,MAAM,QAAQ,QAAQ,GAAG,aAAa,KAAK,CAAC;EAC5C,QAAQ;EACR,WAAW,KACT,QAAQ,WAAW,EAAE,EACrB,EAAE,uBAAuB,OAAO,EAChC,QAAQ,OAAO,QAChB;EACD,oBAAoB;EACrB,CAAC,CACH,EAAE,CACJ,EACF,CACF,CACF;AACD,KAAI,OAAO,OAAO,SAAS,EACzB,OAAM,IAAI,MACR,oBAAoB,KAAK,IAAI,OAAO,OACjC,KAAI,UAAS,MAAM,KAAK,CACxB,KAAK,KAAK,GACd;AAEH,KAAI,OAAO,SAAS,SAAS,EAC3B,SAAQ,KACN,2BAA2B,KAAK,IAAI,OAAO,SACxC,KAAI,YAAW,QAAQ,KAAK,CAC5B,KAAK,KAAK,GACd;AAEH,KAAI,CAAC,OAAO,eAAe,OAAO,YAAY,OAAO,QAAQ,CAAC,WAAW,EACvE,OAAM,IAAI,MACR,iCACE,KACD,iDACF;AAGH,QAAO,OAAO,YAAY,OAAO,QAAQ,CAAC"}
1
+ {"version":3,"file":"bundle.mjs","names":[],"sources":["../src/bundle.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 {\n CreateUnpluginResolverOptions,\n ResolveOptions,\n UnresolvedContext\n} from \"@powerlines/core\";\nimport { createUnpluginResolver } from \"@powerlines/core/lib/unplugin\";\nimport { resolveOptions } from \"@powerlines/unplugin/esbuild\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { DeepPartial } from \"@stryke/types/base\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport { build, OutputFile } from \"esbuild\";\nimport { createEsbuildPlugin } from \"unplugin\";\n\nexport type BundleOptions = DeepPartial<BuildOptions> & {\n name?: string;\n resolve?: DeepPartial<ResolveOptions>;\n};\n\n/**\n * Bundle a type definition to a module.\n *\n * @param context - The context object containing the environment paths.\n * @param file - The file path to bundle.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the bundled module.\n */\nexport async function bundle<TContext extends UnresolvedContext>(\n context: TContext,\n file: string,\n options: BundleOptions = {}\n): Promise<OutputFile> {\n const path = await context.fs.resolve(file);\n if (!path || !context.fs.existsSync(path)) {\n throw new Error(\n `Module not found: \"${file}\". Please check the path and try again.`\n );\n }\n\n const result = await build(\n defu(\n {\n entryPoints: [path],\n write: false,\n sourcemap: false,\n splitting: false,\n treeShaking: true,\n bundle: true,\n packages: \"bundle\",\n platform: \"node\",\n logLevel: \"silent\",\n ...omit(options, [\"name\", \"resolve\"])\n },\n resolveOptions(context),\n {\n plugins: [\n createEsbuildPlugin(\n createUnpluginResolver(context, {\n name: options.name ?? `${findFileName(file)} Bundler`,\n prefix: false,\n overrides: defu(\n options.resolve ?? {},\n { skipNodeModulesBundle: false },\n context.config.resolve\n ) as CreateUnpluginResolverOptions[\"overrides\"],\n silenceHookLogging: true\n })\n )()\n ]\n }\n )\n );\n if (result.errors.length > 0) {\n throw new Error(\n `Failed to bundle ${file}: ${result.errors\n .map(error => error.text)\n .join(\", \")}`\n );\n }\n if (result.warnings.length > 0) {\n context.warn(\n `Warnings while bundling ${file}: ${result.warnings\n .map(warning => warning.text)\n .join(\", \")}`\n );\n }\n if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) {\n throw new Error(\n `No output files generated for ${\n file\n }. Please check the configuration and try again.`\n );\n }\n\n return result.outputFiles.filter(Boolean)[0]!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8CA,eAAsB,OACpB,SACA,MACA,UAAyB,CAAC,GACL;CACrB,MAAM,OAAO,MAAM,QAAQ,GAAG,QAAQ,IAAI;CAC1C,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,WAAW,IAAI,GACtC,MAAM,IAAI,MACR,sBAAsB,KAAK,wCAC7B;CAGF,MAAM,SAAS,MAAM,MACnB,KACE;EACE,aAAa,CAAC,IAAI;EAClB,OAAO;EACP,WAAW;EACX,WAAW;EACX,aAAa;EACb,QAAQ;EACR,UAAU;EACV,UAAU;EACV,UAAU;EACV,GAAG,KAAK,SAAS,CAAC,QAAQ,SAAS,CAAC;CACtC,GACA,eAAe,OAAO,GACtB,EACE,SAAS,CACP,oBACE,uBAAuB,SAAS;EAC9B,MAAM,QAAQ,QAAQ,GAAG,aAAa,IAAI,EAAE;EAC5C,QAAQ;EACR,WAAW,KACT,QAAQ,WAAW,CAAC,GACpB,EAAE,uBAAuB,MAAM,GAC/B,QAAQ,OAAO,OACjB;EACA,oBAAoB;CACtB,CAAC,CACH,EAAE,CACJ,EACF,CACF,CACF;CACA,IAAI,OAAO,OAAO,SAAS,GACzB,MAAM,IAAI,MACR,oBAAoB,KAAK,IAAI,OAAO,OACjC,KAAI,UAAS,MAAM,IAAI,EACvB,KAAK,IAAI,GACd;CAEF,IAAI,OAAO,SAAS,SAAS,GAC3B,QAAQ,KACN,2BAA2B,KAAK,IAAI,OAAO,SACxC,KAAI,YAAW,QAAQ,IAAI,EAC3B,KAAK,IAAI,GACd;CAEF,IAAI,CAAC,OAAO,eAAe,OAAO,YAAY,OAAO,OAAO,EAAE,WAAW,GACvE,MAAM,IAAI,MACR,iCACE,KACD,gDACH;CAGF,OAAO,OAAO,YAAY,OAAO,OAAO,EAAE;AAC5C"}
package/dist/codegen.cjs CHANGED
@@ -1,12 +1,53 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
- let ajv = require("ajv");
4
- ajv = require_runtime.__toESM(ajv, 1);
5
- let ajv_dist_standalone_index_js = require("ajv/dist/standalone/index.js");
6
- ajv_dist_standalone_index_js = require_runtime.__toESM(ajv_dist_standalone_index_js, 1);
3
+ const require_helpers = require('./helpers.cjs');
4
+ let _stryke_convert_to_bool = require("@stryke/convert/to-bool");
5
+ let _stryke_type_checks_is_boolean = require("@stryke/type-checks/is-boolean");
6
+ let _stryke_type_checks_is_null = require("@stryke/type-checks/is-null");
7
+ let _stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
8
+ let _stryke_type_checks_is_undefined = require("@stryke/type-checks/is-undefined");
9
+ let ajv_lib_jtd_ts = require("ajv/lib/jtd.ts");
10
+ ajv_lib_jtd_ts = require_runtime.__toESM(ajv_lib_jtd_ts, 1);
11
+ let ajv_lib_standalone_index_ts = require("ajv/lib/standalone/index.ts");
12
+ ajv_lib_standalone_index_ts = require_runtime.__toESM(ajv_lib_standalone_index_ts, 1);
7
13
 
8
14
  //#region src/codegen.ts
9
15
  /**
16
+ * Stringifies a value as a string.
17
+ *
18
+ * @remarks
19
+ * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
20
+ *
21
+ * @param value - The value to stringify.
22
+ * @returns A string representation of the value.
23
+ */
24
+ function stringifyValue(value, type) {
25
+ return (0, _stryke_type_checks_is_undefined.isUndefined)(value) ? "undefined" : (0, _stryke_type_checks_is_null.isNull)(value) ? "null" : type === "boolean" || (0, _stryke_type_checks_is_boolean.isBoolean)(value) ? String((0, _stryke_convert_to_bool.toBool)(value)) : type && type.startsWith("float") ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type && ["int", "uint"].some((prefix) => type.startsWith(prefix)) || (0, _stryke_type_checks_is_number.isNumber)(value) ? Number.parseInt(String(value)).toLocaleString() : type === "timestamp" ? `"${new Date(String(value)).toISOString()}"` : JSON.stringify(String(value).replaceAll("\"", "\\\""), void 0, 2);
26
+ }
27
+ /**
28
+ * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
29
+ *
30
+ * @param schema - The JTD schema type to stringify.
31
+ * @returns A string representation of the JTD schema type.
32
+ */
33
+ function stringifyType(schema) {
34
+ if (!schema) return "unknown";
35
+ if ("ref" in schema) return schema.ref;
36
+ if ("type" in schema) return [
37
+ "float",
38
+ "uint",
39
+ "int"
40
+ ].some((prefix) => schema.type.startsWith(prefix)) ? "number" : schema.type === "timestamp" ? "string" : schema.type;
41
+ if ("enum" in schema) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
42
+ if ("elements" in schema) return `${stringifyType(schema.elements)}[]`;
43
+ if ("values" in schema) return `{ [key: string]: ${stringifyType(schema.values)} }`;
44
+ if ("properties" in schema || "optionalProperties" in schema) return `{ ${Object.entries(require_helpers.getProperties(schema)).map(([key, value]) => {
45
+ return `${key}${value.optional ? "?" : ""}: ${stringifyType(value)}`;
46
+ }).join(";\n")} }`;
47
+ if ("discriminator" in schema) return "object";
48
+ return "unknown";
49
+ }
50
+ /**
10
51
  * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
11
52
  *
12
53
  * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.
@@ -14,7 +55,7 @@ ajv_dist_standalone_index_js = require_runtime.__toESM(ajv_dist_standalone_index
14
55
  * @returns A promise that resolves to a string containing the generated standalone validation code.
15
56
  */
16
57
  async function generateCode(schemas, refsOrFuncts) {
17
- return (0, ajv_dist_standalone_index_js.default)(new ajv.default({
58
+ return (0, ajv_lib_standalone_index_ts.default)(new ajv_lib_jtd_ts.default({
18
59
  schemas,
19
60
  code: {
20
61
  source: true,
@@ -24,4 +65,6 @@ async function generateCode(schemas, refsOrFuncts) {
24
65
  }
25
66
 
26
67
  //#endregion
27
- exports.generateCode = generateCode;
68
+ exports.generateCode = generateCode;
69
+ exports.stringifyType = stringifyType;
70
+ exports.stringifyValue = stringifyValue;
@@ -1,7 +1,25 @@
1
- import { Options } from "ajv";
2
- import standaloneCode from "ajv/dist/standalone/index.js";
1
+ import { JTDSchemaType, JTDType } from "./types.cjs";
2
+ import { Options } from "ajv/lib/jtd.ts";
3
+ import standaloneCode from "ajv/lib/standalone/index.ts";
3
4
 
4
5
  //#region src/codegen.d.ts
6
+ /**
7
+ * Stringifies a value as a string.
8
+ *
9
+ * @remarks
10
+ * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
11
+ *
12
+ * @param value - The value to stringify.
13
+ * @returns A string representation of the value.
14
+ */
15
+ declare function stringifyValue(value?: unknown, type?: JTDType): string;
16
+ /**
17
+ * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
18
+ *
19
+ * @param schema - The JTD schema type to stringify.
20
+ * @returns A string representation of the JTD schema type.
21
+ */
22
+ declare function stringifyType(schema?: JTDSchemaType): string;
5
23
  /**
6
24
  * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
7
25
  *
@@ -11,5 +29,5 @@ import standaloneCode from "ajv/dist/standalone/index.js";
11
29
  */
12
30
  declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
13
31
  //#endregion
14
- export { generateCode };
32
+ export { generateCode, stringifyType, stringifyValue };
15
33
  //# sourceMappingURL=codegen.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;AA6BA;;;;;iBAAsB,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
1
+ {"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAsCA;;;;;;;iBAAgB,cAAA,CAAe,KAAA,YAAiB,IAAA,GAAO,OAAO;AAAA;AA6B9D;;;;AAAoD;AA7BU,iBA6B9C,aAAA,CAAc,MAAsB,GAAb,aAAa;;;;;;;;iBAqD9B,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
@@ -1,7 +1,25 @@
1
- import { Options } from "ajv";
2
- import standaloneCode from "ajv/dist/standalone/index.js";
1
+ import { JTDSchemaType, JTDType } from "./types.mjs";
2
+ import { Options } from "ajv/lib/jtd.ts";
3
+ import standaloneCode from "ajv/lib/standalone/index.ts";
3
4
 
4
5
  //#region src/codegen.d.ts
6
+ /**
7
+ * Stringifies a value as a string.
8
+ *
9
+ * @remarks
10
+ * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
11
+ *
12
+ * @param value - The value to stringify.
13
+ * @returns A string representation of the value.
14
+ */
15
+ declare function stringifyValue(value?: unknown, type?: JTDType): string;
16
+ /**
17
+ * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
18
+ *
19
+ * @param schema - The JTD schema type to stringify.
20
+ * @returns A string representation of the JTD schema type.
21
+ */
22
+ declare function stringifyType(schema?: JTDSchemaType): string;
5
23
  /**
6
24
  * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
7
25
  *
@@ -11,5 +29,5 @@ import standaloneCode from "ajv/dist/standalone/index.js";
11
29
  */
12
30
  declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
13
31
  //#endregion
14
- export { generateCode };
32
+ export { generateCode, stringifyType, stringifyValue };
15
33
  //# sourceMappingURL=codegen.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;AA6BA;;;;;iBAAsB,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
1
+ {"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAsCA;;;;;;;iBAAgB,cAAA,CAAe,KAAA,YAAiB,IAAA,GAAO,OAAO;AAAA;AA6B9D;;;;AAAoD;AA7BU,iBA6B9C,aAAA,CAAc,MAAsB,GAAb,aAAa;;;;;;;;iBAqD9B,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
package/dist/codegen.mjs CHANGED
@@ -1,8 +1,49 @@
1
- import Ajv from "ajv";
2
- import standaloneCode from "ajv/dist/standalone/index.js";
1
+ import { getProperties } from "./helpers.mjs";
2
+ import { toBool } from "@stryke/convert/to-bool";
3
+ import { isBoolean } from "@stryke/type-checks/is-boolean";
4
+ import { isNull } from "@stryke/type-checks/is-null";
5
+ import { isNumber } from "@stryke/type-checks/is-number";
6
+ import { isUndefined } from "@stryke/type-checks/is-undefined";
7
+ import Ajv from "ajv/lib/jtd.ts";
8
+ import standaloneCode from "ajv/lib/standalone/index.ts";
3
9
 
4
10
  //#region src/codegen.ts
5
11
  /**
12
+ * Stringifies a value as a string.
13
+ *
14
+ * @remarks
15
+ * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
16
+ *
17
+ * @param value - The value to stringify.
18
+ * @returns A string representation of the value.
19
+ */
20
+ function stringifyValue(value, type) {
21
+ return isUndefined(value) ? "undefined" : isNull(value) ? "null" : type === "boolean" || isBoolean(value) ? String(toBool(value)) : type && type.startsWith("float") ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type && ["int", "uint"].some((prefix) => type.startsWith(prefix)) || isNumber(value) ? Number.parseInt(String(value)).toLocaleString() : type === "timestamp" ? `"${new Date(String(value)).toISOString()}"` : JSON.stringify(String(value).replaceAll("\"", "\\\""), void 0, 2);
22
+ }
23
+ /**
24
+ * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
25
+ *
26
+ * @param schema - The JTD schema type to stringify.
27
+ * @returns A string representation of the JTD schema type.
28
+ */
29
+ function stringifyType(schema) {
30
+ if (!schema) return "unknown";
31
+ if ("ref" in schema) return schema.ref;
32
+ if ("type" in schema) return [
33
+ "float",
34
+ "uint",
35
+ "int"
36
+ ].some((prefix) => schema.type.startsWith(prefix)) ? "number" : schema.type === "timestamp" ? "string" : schema.type;
37
+ if ("enum" in schema) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
38
+ if ("elements" in schema) return `${stringifyType(schema.elements)}[]`;
39
+ if ("values" in schema) return `{ [key: string]: ${stringifyType(schema.values)} }`;
40
+ if ("properties" in schema || "optionalProperties" in schema) return `{ ${Object.entries(getProperties(schema)).map(([key, value]) => {
41
+ return `${key}${value.optional ? "?" : ""}: ${stringifyType(value)}`;
42
+ }).join(";\n")} }`;
43
+ if ("discriminator" in schema) return "object";
44
+ return "unknown";
45
+ }
46
+ /**
6
47
  * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
7
48
  *
8
49
  * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.
@@ -20,5 +61,5 @@ async function generateCode(schemas, refsOrFuncts) {
20
61
  }
21
62
 
22
63
  //#endregion
23
- export { generateCode };
64
+ export { generateCode, stringifyType, stringifyValue };
24
65
  //# sourceMappingURL=codegen.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"codegen.mjs","names":[],"sources":["../src/codegen.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 { Options } from \"ajv\";\nimport Ajv from \"ajv\";\nimport standaloneCode from \"ajv/dist/standalone\";\n\n/**\n * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.\n *\n * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.\n * @param refsOrFuncts - An optional parameter that can be either an object containing schema references or a function that returns such an object. This parameter allows you to provide additional schemas that may be referenced by the main schemas, or to define custom functions that can be used in the generated validation code. If not provided, the function will generate code based solely on the provided schemas.\n * @returns A promise that resolves to a string containing the generated standalone validation code.\n */\nexport async function generateCode(\n schemas: Options[\"schemas\"],\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(\n new Ajv({\n schemas,\n code: { source: true, esm: true }\n }),\n refsOrFuncts\n );\n}\n"],"mappings":";;;;;;;;;;;AA6BA,eAAsB,aACpB,SACA,cACA;AACA,QAAO,eACL,IAAI,IAAI;EACN;EACA,MAAM;GAAE,QAAQ;GAAM,KAAK;GAAM;EAClC,CAAC,EACF,aACD"}
1
+ {"version":3,"file":"codegen.mjs","names":[],"sources":["../src/codegen.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 { toBool } from \"@stryke/convert/to-bool\";\nimport { isBoolean } from \"@stryke/type-checks/is-boolean\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isUndefined } from \"@stryke/type-checks/is-undefined\";\nimport type { Options } from \"ajv/lib/jtd\";\nimport Ajv from \"ajv/lib/jtd\";\nimport standaloneCode from \"ajv/lib/standalone\";\nimport { getProperties } from \"./helpers\";\nimport { JTDSchemaType, JTDType } from \"./types\";\n\n/**\n * Stringifies a value as a string.\n *\n * @remarks\n * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to \"true\" or \"false\", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the value.\n */\nexport function stringifyValue(value?: unknown, type?: JTDType): string {\n return isUndefined(value)\n ? \"undefined\"\n : isNull(value)\n ? \"null\"\n : type === \"boolean\" || isBoolean(value)\n ? String(toBool(value))\n : type && type.startsWith(\"float\")\n ? Number.parseFloat(String(value)).toLocaleString(undefined, {\n maximumFractionDigits: 20\n })\n : (type && [\"int\", \"uint\"].some(prefix => type.startsWith(prefix))) ||\n isNumber(value)\n ? Number.parseInt(String(value)).toLocaleString()\n : type === \"timestamp\"\n ? `\"${new Date(String(value)).toISOString()}\"`\n : JSON.stringify(\n String(value).replaceAll('\"', '\\\\\"'),\n undefined,\n 2\n );\n}\n\n/**\n * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.\n *\n * @param schema - The JTD schema type to stringify.\n * @returns A string representation of the JTD schema type.\n */\nexport function stringifyType(schema?: JTDSchemaType): string {\n if (!schema) {\n return \"unknown\";\n }\n\n if (\"ref\" in schema) {\n return schema.ref;\n }\n\n if (\"type\" in schema) {\n return [\"float\", \"uint\", \"int\"].some(prefix =>\n schema.type.startsWith(prefix)\n )\n ? \"number\"\n : schema.type === \"timestamp\"\n ? \"string\"\n : schema.type;\n }\n\n if (\"enum\" in schema) {\n return schema.enum.map(value => JSON.stringify(value)).join(\" | \");\n }\n\n if (\"elements\" in schema) {\n return `${stringifyType(schema.elements)}[]`;\n }\n\n if (\"values\" in schema) {\n return `{ [key: string]: ${stringifyType(schema.values)} }`;\n }\n\n if (\"properties\" in schema || \"optionalProperties\" in schema) {\n return `{ ${Object.entries(getProperties(schema))\n .map(([key, value]) => {\n return `${key}${value.optional ? \"?\" : \"\"}: ${stringifyType(value)}`;\n })\n .join(\";\\n\")} }`;\n }\n\n if (\"discriminator\" in schema) {\n return \"object\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.\n *\n * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.\n * @param refsOrFuncts - An optional parameter that can be either an object containing schema references or a function that returns such an object. This parameter allows you to provide additional schemas that may be referenced by the main schemas, or to define custom functions that can be used in the generated validation code. If not provided, the function will generate code based solely on the provided schemas.\n * @returns A promise that resolves to a string containing the generated standalone validation code.\n */\nexport async function generateCode(\n schemas: Options[\"schemas\"],\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(\n new Ajv({\n schemas,\n code: { source: true, esm: true }\n }),\n refsOrFuncts\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,eAAe,OAAiB,MAAwB;CACtE,OAAO,YAAY,KAAK,IACpB,cACA,OAAO,KAAK,IACV,SACA,SAAS,aAAa,UAAU,KAAK,IACnC,OAAO,OAAO,KAAK,CAAC,IACpB,QAAQ,KAAK,WAAW,OAAO,IAC7B,OAAO,WAAW,OAAO,KAAK,CAAC,EAAE,eAAe,QAAW,EACzD,uBAAuB,GACzB,CAAC,IACA,QAAQ,CAAC,OAAO,MAAM,EAAE,MAAK,WAAU,KAAK,WAAW,MAAM,CAAC,KAC7D,SAAS,KAAK,IACd,OAAO,SAAS,OAAO,KAAK,CAAC,EAAE,eAAe,IAC9C,SAAS,cACP,IAAI,IAAI,KAAK,OAAO,KAAK,CAAC,EAAE,YAAY,EAAE,KAC1C,KAAK,UACH,OAAO,KAAK,EAAE,WAAW,MAAK,MAAK,GACnC,QACA,CACF;AAChB;;;;;;;AAQA,SAAgB,cAAc,QAAgC;CAC5D,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,SAAS,QACX,OAAO,OAAO;CAGhB,IAAI,UAAU,QACZ,OAAO;EAAC;EAAS;EAAQ;CAAK,EAAE,MAAK,WACnC,OAAO,KAAK,WAAW,MAAM,CAC/B,IACI,WACA,OAAO,SAAS,cACd,WACA,OAAO;CAGf,IAAI,UAAU,QACZ,OAAO,OAAO,KAAK,KAAI,UAAS,KAAK,UAAU,KAAK,CAAC,EAAE,KAAK,KAAK;CAGnE,IAAI,cAAc,QAChB,OAAO,GAAG,cAAc,OAAO,QAAQ,EAAE;CAG3C,IAAI,YAAY,QACd,OAAO,oBAAoB,cAAc,OAAO,MAAM,EAAE;CAG1D,IAAI,gBAAgB,UAAU,wBAAwB,QACpD,OAAO,KAAK,OAAO,QAAQ,cAAc,MAAM,CAAC,EAC7C,KAAK,CAAC,KAAK,WAAW;EACrB,OAAO,GAAG,MAAM,MAAM,WAAW,MAAM,GAAG,IAAI,cAAc,KAAK;CACnE,CAAC,EACA,KAAK,KAAK,EAAE;CAGjB,IAAI,mBAAmB,QACrB,OAAO;CAGT,OAAO;AACT;;;;;;;;AASA,eAAsB,aACpB,SACA,cACA;CACA,OAAO,eACL,IAAI,IAAI;EACN;EACA,MAAM;GAAE,QAAQ;GAAM,KAAK;EAAK;CAClC,CAAC,GACD,YACF;AACF"}
@@ -0,0 +1,19 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+
3
+ //#region src/constants.ts
4
+ const JTDTypes = {
5
+ STRING: "string",
6
+ TIMESTAMP: "timestamp",
7
+ BOOLEAN: "boolean",
8
+ FLOAT32: "float32",
9
+ FLOAT64: "float64",
10
+ INT8: "int8",
11
+ UINT8: "uint8",
12
+ INT16: "int16",
13
+ UINT16: "uint16",
14
+ INT32: "int32",
15
+ UINT32: "uint32"
16
+ };
17
+
18
+ //#endregion
19
+ exports.JTDTypes = JTDTypes;
@@ -0,0 +1,17 @@
1
+ //#region src/constants.d.ts
2
+ declare const JTDTypes: {
3
+ readonly STRING: "string";
4
+ readonly TIMESTAMP: "timestamp";
5
+ readonly BOOLEAN: "boolean";
6
+ readonly FLOAT32: "float32";
7
+ readonly FLOAT64: "float64";
8
+ readonly INT8: "int8";
9
+ readonly UINT8: "uint8";
10
+ readonly INT16: "int16";
11
+ readonly UINT16: "uint16";
12
+ readonly INT32: "int32";
13
+ readonly UINT32: "uint32";
14
+ };
15
+ //#endregion
16
+ export { JTDTypes };
17
+ //# sourceMappingURL=constants.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAkBa,QAAA;EAAA"}
@@ -0,0 +1,17 @@
1
+ //#region src/constants.d.ts
2
+ declare const JTDTypes: {
3
+ readonly STRING: "string";
4
+ readonly TIMESTAMP: "timestamp";
5
+ readonly BOOLEAN: "boolean";
6
+ readonly FLOAT32: "float32";
7
+ readonly FLOAT64: "float64";
8
+ readonly INT8: "int8";
9
+ readonly UINT8: "uint8";
10
+ readonly INT16: "int16";
11
+ readonly UINT16: "uint16";
12
+ readonly INT32: "int32";
13
+ readonly UINT32: "uint32";
14
+ };
15
+ //#endregion
16
+ export { JTDTypes };
17
+ //# sourceMappingURL=constants.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":";cAkBa,QAAA;EAAA"}
@@ -0,0 +1,18 @@
1
+ //#region src/constants.ts
2
+ const JTDTypes = {
3
+ STRING: "string",
4
+ TIMESTAMP: "timestamp",
5
+ BOOLEAN: "boolean",
6
+ FLOAT32: "float32",
7
+ FLOAT64: "float64",
8
+ INT8: "int8",
9
+ UINT8: "uint8",
10
+ INT16: "int16",
11
+ UINT16: "uint16",
12
+ INT32: "int32",
13
+ UINT32: "uint32"
14
+ };
15
+
16
+ //#endregion
17
+ export { JTDTypes };
18
+ //# sourceMappingURL=constants.mjs.map
@@ -0,0 +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\nexport const JTDTypes = {\n STRING: \"string\",\n TIMESTAMP: \"timestamp\",\n BOOLEAN: \"boolean\",\n FLOAT32: \"float32\",\n FLOAT64: \"float64\",\n INT8: \"int8\",\n UINT8: \"uint8\",\n INT16: \"int16\",\n UINT16: \"uint16\",\n INT32: \"int32\",\n UINT32: \"uint32\"\n} as const;\n"],"mappings":";AAkBA,MAAa,WAAW;CACtB,QAAQ;CACR,WAAW;CACX,SAAS;CACT,SAAS;CACT,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;CACP,QAAQ;CACR,OAAO;CACP,QAAQ;AACV"}
package/dist/extract.cjs CHANGED
@@ -1,17 +1,19 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ const require_type_checks = require('./type-checks.cjs');
3
4
  const require_jtd = require('./jtd.cjs');
5
+ const require_persistence = require('./persistence.cjs');
4
6
  const require_reflection = require('./reflection.cjs');
5
7
  const require_resolve = require('./resolve.cjs');
6
- const require_type_checks = require('./type-checks.cjs');
7
8
  let defu = require("defu");
8
9
  defu = require_runtime.__toESM(defu, 1);
10
+ let _stryke_type_checks = require("@stryke/type-checks");
9
11
  let _powerlines_core = require("@powerlines/core");
10
12
  let _powerlines_deepkit_esbuild_plugin = require("@powerlines/deepkit/esbuild-plugin");
11
13
  let _powerlines_deepkit_vendor_type = require("@powerlines/deepkit/vendor/type");
12
14
  let _stryke_hash = require("@stryke/hash");
13
15
  let _stryke_json = require("@stryke/json");
14
- let _stryke_type_checks = require("@stryke/type-checks");
16
+ let _stryke_path_join = require("@stryke/path/join");
15
17
  let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
16
18
  let _stryke_zod = require("@stryke/zod");
17
19
 
@@ -199,6 +201,7 @@ async function extractSchema(context, input, options = {}) {
199
201
  };
200
202
  let source;
201
203
  const variant = extractVariant(input);
204
+ const hash = extractHash(variant, input);
202
205
  if (variant === "type-definition") {
203
206
  const resolved = await require_resolve.resolve(context, input, (0, defu.default)(options, { plugins: [(0, _powerlines_deepkit_esbuild_plugin.esbuildPlugin)(context, {
204
207
  reflection: "default",
@@ -218,7 +221,7 @@ async function extractSchema(context, input, options = {}) {
218
221
  variant,
219
222
  source,
220
223
  schema: await extractSchemaSchema(source.schema, source.variant),
221
- hash: extractHash(variant, input)
224
+ hash
222
225
  };
223
226
  }
224
227
  /**
@@ -250,7 +253,23 @@ async function extractSchema(context, input, options = {}) {
250
253
  * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.
251
254
  */
252
255
  async function extract(context, input, options = {}) {
253
- return await extractSchema(context, input, options);
256
+ if (require_type_checks.isExtractedSchema(input) || require_type_checks.isSchema(input)) return input;
257
+ let result;
258
+ const variant = extractVariant(input);
259
+ const hash = extractHash(variant, input);
260
+ const cacheFilePath = (0, _stryke_path_join.joinPaths)(require_persistence.getCacheDirectory(context), `${hash}.json`);
261
+ if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
262
+ const schema = await context.fs.read(cacheFilePath);
263
+ if (schema) result = {
264
+ variant,
265
+ hash,
266
+ schema: JSON.parse(schema)
267
+ };
268
+ }
269
+ result ??= await extractSchema(context, input, options);
270
+ if (!result?.schema) 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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`);
271
+ if (context.config.skipCache !== true) await require_persistence.writeSchema(context, result);
272
+ return result;
254
273
  }
255
274
 
256
275
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AAmEA;iBAAg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AAA,EAAO,iBAAA,GAAoB,YAAA;;;;;;;AA7FrC;AA6BtB;;;;;;;;AAAsE;AAgBtE;;;;iBAgHsB,aAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,eAAA,CAAgB,SAAA;;;;;;;;;;;;;;;;;;;;;;;AAlHO;AAyClC;;;;;iBAoKsB,OAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,MAAA,CAAO,SAAA"}
package/dist/extract.mjs CHANGED
@@ -1,14 +1,16 @@
1
+ import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
1
2
  import { jsonSchemaToJtd } from "./jtd.mjs";
3
+ import { getCacheDirectory, writeSchema } from "./persistence.mjs";
2
4
  import { reflectionToJsonSchema } from "./reflection.mjs";
3
5
  import { resolve } from "./resolve.mjs";
4
- import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
5
6
  import defu from "defu";
7
+ import { isSetString } from "@stryke/type-checks";
6
8
  import { isTypeDefinition } from "@powerlines/core";
7
9
  import { esbuildPlugin } from "@powerlines/deepkit/esbuild-plugin";
8
10
  import { isType, stringifyType } from "@powerlines/deepkit/vendor/type";
9
11
  import { murmurhash } from "@stryke/hash";
10
12
  import { isJsonSchemaObjectType, isStandardJsonSchema } from "@stryke/json";
11
- import { isSetString } from "@stryke/type-checks";
13
+ import { joinPaths } from "@stryke/path/join";
12
14
  import { isSetObject as isSetObject$1 } from "@stryke/type-checks/is-set-object";
13
15
  import { extractJsonSchema as extractJsonSchema$1, isZod3Type } from "@stryke/zod";
14
16
 
@@ -196,6 +198,7 @@ async function extractSchema(context, input, options = {}) {
196
198
  };
197
199
  let source;
198
200
  const variant = extractVariant(input);
201
+ const hash = extractHash(variant, input);
199
202
  if (variant === "type-definition") {
200
203
  const resolved = await resolve(context, input, defu(options, { plugins: [esbuildPlugin(context, {
201
204
  reflection: "default",
@@ -215,7 +218,7 @@ async function extractSchema(context, input, options = {}) {
215
218
  variant,
216
219
  source,
217
220
  schema: await extractSchemaSchema(source.schema, source.variant),
218
- hash: extractHash(variant, input)
221
+ hash
219
222
  };
220
223
  }
221
224
  /**
@@ -247,7 +250,23 @@ async function extractSchema(context, input, options = {}) {
247
250
  * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.
248
251
  */
249
252
  async function extract(context, input, options = {}) {
250
- return await extractSchema(context, input, options);
253
+ if (isExtractedSchema(input) || isSchema(input)) return input;
254
+ let result;
255
+ const variant = extractVariant(input);
256
+ const hash = extractHash(variant, input);
257
+ const cacheFilePath = joinPaths(getCacheDirectory(context), `${hash}.json`);
258
+ if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
259
+ const schema = await context.fs.read(cacheFilePath);
260
+ if (schema) result = {
261
+ variant,
262
+ hash,
263
+ schema: JSON.parse(schema)
264
+ };
265
+ }
266
+ result ??= await extractSchema(context, input, options);
267
+ if (!result?.schema) 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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`);
268
+ if (context.config.skipCache !== true) await writeSchema(context, result);
269
+ return result;
251
270
  }
252
271
 
253
272
  //#endregion