@powerlines/schema 0.11.27 → 0.11.37

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 (82) hide show
  1. package/dist/bundle.cjs +34 -20
  2. package/dist/bundle.d.cts +3 -3
  3. package/dist/bundle.d.cts.map +1 -1
  4. package/dist/bundle.d.mts +3 -3
  5. package/dist/bundle.d.mts.map +1 -1
  6. package/dist/bundle.mjs +35 -21
  7. package/dist/bundle.mjs.map +1 -1
  8. package/dist/codegen.cjs +40 -36
  9. package/dist/codegen.d.cts +10 -22
  10. package/dist/codegen.d.cts.map +1 -1
  11. package/dist/codegen.d.mts +10 -22
  12. package/dist/codegen.d.mts.map +1 -1
  13. package/dist/codegen.mjs +39 -36
  14. package/dist/codegen.mjs.map +1 -1
  15. package/dist/constants.cjs +34 -11
  16. package/dist/constants.d.cts +9 -11
  17. package/dist/constants.d.cts.map +1 -1
  18. package/dist/constants.d.mts +9 -11
  19. package/dist/constants.d.mts.map +1 -1
  20. package/dist/constants.mjs +32 -11
  21. package/dist/constants.mjs.map +1 -1
  22. package/dist/extract.cjs +122 -92
  23. package/dist/extract.d.cts +34 -69
  24. package/dist/extract.d.cts.map +1 -1
  25. package/dist/extract.d.mts +34 -69
  26. package/dist/extract.d.mts.map +1 -1
  27. package/dist/extract.mjs +123 -93
  28. package/dist/extract.mjs.map +1 -1
  29. package/dist/helpers.cjs +45 -52
  30. package/dist/helpers.d.cts +28 -24
  31. package/dist/helpers.d.cts.map +1 -1
  32. package/dist/helpers.d.mts +28 -24
  33. package/dist/helpers.d.mts.map +1 -1
  34. package/dist/helpers.mjs +46 -52
  35. package/dist/helpers.mjs.map +1 -1
  36. package/dist/index.cjs +14 -7
  37. package/dist/index.d.cts +6 -6
  38. package/dist/index.d.mts +6 -6
  39. package/dist/index.mjs +5 -5
  40. package/dist/metadata.cjs +80 -0
  41. package/dist/metadata.d.cts +52 -0
  42. package/dist/metadata.d.cts.map +1 -0
  43. package/dist/metadata.d.mts +52 -0
  44. package/dist/metadata.d.mts.map +1 -0
  45. package/dist/metadata.mjs +76 -0
  46. package/dist/metadata.mjs.map +1 -0
  47. package/dist/persistence.cjs +1 -2
  48. package/dist/persistence.d.cts +5 -5
  49. package/dist/persistence.d.cts.map +1 -1
  50. package/dist/persistence.d.mts +5 -5
  51. package/dist/persistence.d.mts.map +1 -1
  52. package/dist/persistence.mjs +1 -1
  53. package/dist/persistence.mjs.map +1 -1
  54. package/dist/reflection.cjs +289 -303
  55. package/dist/reflection.d.cts +3 -16
  56. package/dist/reflection.d.cts.map +1 -1
  57. package/dist/reflection.d.mts +3 -16
  58. package/dist/reflection.d.mts.map +1 -1
  59. package/dist/reflection.mjs +290 -304
  60. package/dist/reflection.mjs.map +1 -1
  61. package/dist/resolve.cjs +7 -7
  62. package/dist/resolve.mjs +7 -7
  63. package/dist/resolve.mjs.map +1 -1
  64. package/dist/type-checks.cjs +122 -40
  65. package/dist/type-checks.d.cts +41 -33
  66. package/dist/type-checks.d.cts.map +1 -1
  67. package/dist/type-checks.d.mts +41 -33
  68. package/dist/type-checks.d.mts.map +1 -1
  69. package/dist/type-checks.mjs +120 -37
  70. package/dist/type-checks.mjs.map +1 -1
  71. package/dist/types.d.cts +225 -113
  72. package/dist/types.d.cts.map +1 -1
  73. package/dist/types.d.mts +225 -113
  74. package/dist/types.d.mts.map +1 -1
  75. package/package.json +11 -7
  76. package/dist/jtd.cjs +0 -385
  77. package/dist/jtd.d.cts +0 -15
  78. package/dist/jtd.d.cts.map +0 -1
  79. package/dist/jtd.d.mts +0 -15
  80. package/dist/jtd.d.mts.map +0 -1
  81. package/dist/jtd.mjs +0 -384
  82. package/dist/jtd.mjs.map +0 -1
package/dist/bundle.cjs CHANGED
@@ -1,12 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
3
  let _powerlines_core_lib_unplugin = require("@powerlines/core/lib/unplugin");
4
- let _powerlines_unplugin_esbuild = require("@powerlines/unplugin/esbuild");
4
+ let _powerlines_unplugin_rolldown = require("@powerlines/unplugin/rolldown");
5
+ let _stryke_convert_to_array = require("@stryke/convert/to-array");
5
6
  let _stryke_helpers_omit = require("@stryke/helpers/omit");
6
7
  let _stryke_path_file_path_fns = require("@stryke/path/file-path-fns");
7
8
  let defu = require("defu");
8
9
  defu = require_runtime.__toESM(defu, 1);
9
- let esbuild = require("esbuild");
10
+ let rolldown = require("rolldown");
10
11
  let unplugin = require("unplugin");
11
12
 
12
13
  //#region src/bundle.ts
@@ -21,27 +22,40 @@ let unplugin = require("unplugin");
21
22
  async function bundle(context, file, options = {}) {
22
23
  const path = await context.fs.resolve(file);
23
24
  if (!path || !context.fs.existsSync(path)) throw new Error(`Module not found: "${file}". Please check the path and try again.`);
24
- const result = await (0, esbuild.build)((0, defu.default)({
25
- entryPoints: [path],
26
- write: false,
27
- sourcemap: false,
28
- splitting: false,
29
- treeShaking: true,
25
+ const userOptions = (0, _stryke_helpers_omit.omit)(options, [
26
+ "name",
27
+ "resolve",
28
+ "plugins"
29
+ ]);
30
+ const plugins = await Promise.resolve(options.plugins);
31
+ const result = await (0, rolldown.build)({
30
32
  bundle: true,
31
- packages: "bundle",
32
33
  platform: "node",
34
+ ...(0, _powerlines_unplugin_rolldown.resolveOptions)(context),
35
+ ...userOptions,
33
36
  logLevel: "silent",
34
- ...(0, _stryke_helpers_omit.omit)(options, ["name", "resolve"])
35
- }, (0, _powerlines_unplugin_esbuild.resolveOptions)(context), { plugins: [(0, unplugin.createEsbuildPlugin)((0, _powerlines_core_lib_unplugin.createUnpluginResolver)(context, {
36
- name: options.name ?? `${(0, _stryke_path_file_path_fns.findFileName)(file)} Bundler`,
37
- prefix: false,
38
- overrides: (0, defu.default)(options.resolve ?? {}, { skipNodeModulesBundle: false }, context.config.resolve),
39
- silenceHookLogging: true
40
- }))()] }));
41
- if (result.errors.length > 0) throw new Error(`Failed to bundle ${file}: ${result.errors.map((error) => error.text).join(", ")}`);
42
- if (result.warnings.length > 0) context.warn(`Warnings while bundling ${file}: ${result.warnings.map((warning) => warning.text).join(", ")}`);
43
- if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) throw new Error(`No output files generated for ${file}. Please check the configuration and try again.`);
44
- return result.outputFiles.filter(Boolean)[0];
37
+ output: {
38
+ dir: context.config.output.path,
39
+ format: "es",
40
+ sourcemap: false,
41
+ codeSplitting: false,
42
+ minify: false,
43
+ keepNames: true,
44
+ exports: "named",
45
+ ...userOptions.output
46
+ },
47
+ input: [path],
48
+ write: false,
49
+ plugins: [...plugins ? (0, _stryke_convert_to_array.toArray)(plugins) : [], (0, unplugin.createRolldownPlugin)((0, _powerlines_core_lib_unplugin.createUnpluginResolver)(context, {
50
+ name: options.name ?? `${(0, _stryke_path_file_path_fns.findFileName)(file)} Bundler`,
51
+ prefix: false,
52
+ overrides: (0, defu.default)(options.resolve ?? {}, { skipNodeModulesBundle: false }, context.config.resolve),
53
+ silenceHookLogging: true
54
+ }))()].filter(Boolean)
55
+ });
56
+ if (!result.output || result.output.length === 0) throw new Error(`No output files generated for ${file}. Please check the configuration and try again.`);
57
+ if (result.output.length > 1) context.warn(`Multiple output files generated for "${file}". Only the first file will be used. Please check the configuration to ensure only one output file is generated.`);
58
+ return result.output[0];
45
59
  }
46
60
 
47
61
  //#endregion
package/dist/bundle.d.cts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { ResolveOptions, UnresolvedContext } from "@powerlines/core";
2
2
  import { DeepPartial } from "@stryke/types/base";
3
- import { BuildOptions, OutputFile } from "esbuild";
3
+ import { BuildOptions, OutputChunk } from "rolldown";
4
4
 
5
5
  //#region src/bundle.d.ts
6
- type BundleOptions = DeepPartial<BuildOptions> & {
6
+ type BundleOptions = DeepPartial<Omit<BuildOptions, "input" | "write">> & {
7
7
  name?: string;
8
8
  resolve?: DeepPartial<ResolveOptions>;
9
9
  };
@@ -15,7 +15,7 @@ type BundleOptions = DeepPartial<BuildOptions> & {
15
15
  * @param options - Optional overrides for the ESBuild configuration.
16
16
  * @returns A promise that resolves to the bundled module.
17
17
  */
18
- declare function bundle<TContext extends UnresolvedContext>(context: TContext, file: string, options?: BundleOptions): Promise<OutputFile>;
18
+ declare function bundle<TContext extends UnresolvedContext>(context: TContext, file: string, options?: BundleOptions): Promise<OutputChunk>;
19
19
  //#endregion
20
20
  export { BundleOptions, bundle };
21
21
  //# sourceMappingURL=bundle.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.d.cts","names":[],"sources":["../src/bundle.ts"],"mappings":";;;;;KAiCY,aAAA,GAAgB,WAAA,CAAY,YAAA;EACtC,IAAA;EACA,OAAA,GAAU,WAAA,CAAY,cAAA;AAAA;;;;;;;;;iBAWF,MAAA,kBAAwB,iBAAA,CAAA,CAC5C,OAAA,EAAS,QAAA,EACT,IAAA,UACA,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,UAAA"}
1
+ {"version":3,"file":"bundle.d.cts","names":[],"sources":["../src/bundle.ts"],"mappings":";;;;;KAkCY,aAAA,GAAgB,WAAA,CAC1B,IAAA,CAAK,YAAA;EAEL,IAAA;EACA,OAAA,GAAU,WAAA,CAAY,cAAA;AAAA;;;;;;;;;iBAWF,MAAA,kBAAwB,iBAAA,CAAA,CAC5C,OAAA,EAAS,QAAA,EACT,IAAA,UACA,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,WAAA"}
package/dist/bundle.d.mts CHANGED
@@ -1,9 +1,9 @@
1
- import { BuildOptions, OutputFile } from "esbuild";
1
+ import { BuildOptions, OutputChunk } from "rolldown";
2
2
  import { ResolveOptions, UnresolvedContext } from "@powerlines/core";
3
3
  import { DeepPartial } from "@stryke/types/base";
4
4
 
5
5
  //#region src/bundle.d.ts
6
- type BundleOptions = DeepPartial<BuildOptions> & {
6
+ type BundleOptions = DeepPartial<Omit<BuildOptions, "input" | "write">> & {
7
7
  name?: string;
8
8
  resolve?: DeepPartial<ResolveOptions>;
9
9
  };
@@ -15,7 +15,7 @@ type BundleOptions = DeepPartial<BuildOptions> & {
15
15
  * @param options - Optional overrides for the ESBuild configuration.
16
16
  * @returns A promise that resolves to the bundled module.
17
17
  */
18
- declare function bundle<TContext extends UnresolvedContext>(context: TContext, file: string, options?: BundleOptions): Promise<OutputFile>;
18
+ declare function bundle<TContext extends UnresolvedContext>(context: TContext, file: string, options?: BundleOptions): Promise<OutputChunk>;
19
19
  //#endregion
20
20
  export { BundleOptions, bundle };
21
21
  //# sourceMappingURL=bundle.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bundle.d.mts","names":[],"sources":["../src/bundle.ts"],"mappings":";;;;;KAiCY,aAAA,GAAgB,WAAA,CAAY,YAAA;EACtC,IAAA;EACA,OAAA,GAAU,WAAA,CAAY,cAAA;AAAA;;;;;;;;;iBAWF,MAAA,kBAAwB,iBAAA,CAAA,CAC5C,OAAA,EAAS,QAAA,EACT,IAAA,UACA,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,UAAA"}
1
+ {"version":3,"file":"bundle.d.mts","names":[],"sources":["../src/bundle.ts"],"mappings":";;;;;KAkCY,aAAA,GAAgB,WAAA,CAC1B,IAAA,CAAK,YAAA;EAEL,IAAA;EACA,OAAA,GAAU,WAAA,CAAY,cAAA;AAAA;;;;;;;;;iBAWF,MAAA,kBAAwB,iBAAA,CAAA,CAC5C,OAAA,EAAS,QAAA,EACT,IAAA,UACA,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,WAAA"}
package/dist/bundle.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  import { createUnpluginResolver } from "@powerlines/core/lib/unplugin";
2
- import { resolveOptions } from "@powerlines/unplugin/esbuild";
2
+ import { resolveOptions } from "@powerlines/unplugin/rolldown";
3
+ import { toArray } from "@stryke/convert/to-array";
3
4
  import { omit } from "@stryke/helpers/omit";
4
5
  import { findFileName } from "@stryke/path/file-path-fns";
5
6
  import defu from "defu";
6
- import { build } from "esbuild";
7
- import { createEsbuildPlugin } from "unplugin";
7
+ import { build } from "rolldown";
8
+ import { createRolldownPlugin } from "unplugin";
8
9
 
9
10
  //#region src/bundle.ts
10
11
  /**
@@ -18,27 +19,40 @@ import { createEsbuildPlugin } from "unplugin";
18
19
  async function bundle(context, file, options = {}) {
19
20
  const path = await context.fs.resolve(file);
20
21
  if (!path || !context.fs.existsSync(path)) throw new Error(`Module not found: "${file}". Please check the path and try again.`);
21
- const result = await build(defu({
22
- entryPoints: [path],
23
- write: false,
24
- sourcemap: false,
25
- splitting: false,
26
- treeShaking: true,
22
+ const userOptions = omit(options, [
23
+ "name",
24
+ "resolve",
25
+ "plugins"
26
+ ]);
27
+ const plugins = await Promise.resolve(options.plugins);
28
+ const result = await build({
27
29
  bundle: true,
28
- packages: "bundle",
29
30
  platform: "node",
31
+ ...resolveOptions(context),
32
+ ...userOptions,
30
33
  logLevel: "silent",
31
- ...omit(options, ["name", "resolve"])
32
- }, resolveOptions(context), { plugins: [createEsbuildPlugin(createUnpluginResolver(context, {
33
- name: options.name ?? `${findFileName(file)} Bundler`,
34
- prefix: false,
35
- overrides: defu(options.resolve ?? {}, { skipNodeModulesBundle: false }, context.config.resolve),
36
- silenceHookLogging: true
37
- }))()] }));
38
- if (result.errors.length > 0) throw new Error(`Failed to bundle ${file}: ${result.errors.map((error) => error.text).join(", ")}`);
39
- if (result.warnings.length > 0) context.warn(`Warnings while bundling ${file}: ${result.warnings.map((warning) => warning.text).join(", ")}`);
40
- if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) throw new Error(`No output files generated for ${file}. Please check the configuration and try again.`);
41
- return result.outputFiles.filter(Boolean)[0];
34
+ output: {
35
+ dir: context.config.output.path,
36
+ format: "es",
37
+ sourcemap: false,
38
+ codeSplitting: false,
39
+ minify: false,
40
+ keepNames: true,
41
+ exports: "named",
42
+ ...userOptions.output
43
+ },
44
+ input: [path],
45
+ write: false,
46
+ plugins: [...plugins ? toArray(plugins) : [], createRolldownPlugin(createUnpluginResolver(context, {
47
+ name: options.name ?? `${findFileName(file)} Bundler`,
48
+ prefix: false,
49
+ overrides: defu(options.resolve ?? {}, { skipNodeModulesBundle: false }, context.config.resolve),
50
+ silenceHookLogging: true
51
+ }))()].filter(Boolean)
52
+ });
53
+ if (!result.output || result.output.length === 0) throw new Error(`No output files generated for ${file}. Please check the configuration and try again.`);
54
+ if (result.output.length > 1) context.warn(`Multiple output files generated for "${file}". Only the first file will be used. Please check the configuration to ensure only one output file is generated.`);
55
+ return result.output[0];
42
56
  }
43
57
 
44
58
  //#endregion
@@ -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,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"}
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/rolldown\";\nimport { toArray } from \"@stryke/convert/to-array\";\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, OutputChunk } from \"rolldown\";\nimport { build } from \"rolldown\";\nimport { createRolldownPlugin } from \"unplugin\";\n\nexport type BundleOptions = DeepPartial<\n Omit<BuildOptions, \"input\" | \"write\">\n> & {\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<OutputChunk> {\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 userOptions = omit(options, [\"name\", \"resolve\", \"plugins\"]);\n const plugins = await Promise.resolve(options.plugins);\n\n const resolvedOptions = resolveOptions(context);\n\n const result = await build({\n bundle: true,\n platform: \"node\",\n ...resolvedOptions,\n ...userOptions,\n logLevel: \"silent\",\n output: {\n dir: context.config.output.path,\n format: \"es\",\n sourcemap: false,\n codeSplitting: false,\n minify: false,\n keepNames: true,\n exports: \"named\",\n ...userOptions.output\n },\n input: [path],\n write: false,\n plugins: [\n ...(plugins ? toArray(plugins) : []),\n createRolldownPlugin(\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 ].filter(Boolean)\n } as BuildOptions);\n if (!result.output || result.output.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 if (result.output.length > 1) {\n context.warn(\n `Multiple output files generated for \"${\n file\n }\". Only the first file will be used. Please check the configuration to ensure only one output file is generated.`\n );\n }\n\n return result.output[0];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiDA,eAAsB,OACpB,SACA,MACA,UAAyB,CAAC,GACJ;CACtB,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,cAAc,KAAK,SAAS;EAAC;EAAQ;EAAW;CAAS,CAAC;CAChE,MAAM,UAAU,MAAM,QAAQ,QAAQ,QAAQ,OAAO;CAIrD,MAAM,SAAS,MAAM,MAAM;EACzB,QAAQ;EACR,UAAU;EACV,GALsB,eAAe,OAKpB;EACjB,GAAG;EACH,UAAU;EACV,QAAQ;GACN,KAAK,QAAQ,OAAO,OAAO;GAC3B,QAAQ;GACR,WAAW;GACX,eAAe;GACf,QAAQ;GACR,WAAW;GACX,SAAS;GACT,GAAG,YAAY;EACjB;EACA,OAAO,CAAC,IAAI;EACZ,OAAO;EACP,SAAS,CACP,GAAI,UAAU,QAAQ,OAAO,IAAI,CAAC,GAClC,qBACE,uBAAuB,SAAS;GAC9B,MAAM,QAAQ,QAAQ,GAAG,aAAa,IAAI,EAAE;GAC5C,QAAQ;GACR,WAAW,KACT,QAAQ,WAAW,CAAC,GACpB,EAAE,uBAAuB,MAAM,GAC/B,QAAQ,OAAO,OACjB;GACA,oBAAoB;EACtB,CAAC,CACH,EAAE,CACJ,EAAE,OAAO,OAAO;CAClB,CAAiB;CACjB,IAAI,CAAC,OAAO,UAAU,OAAO,OAAO,WAAW,GAC7C,MAAM,IAAI,MACR,iCACE,KACD,gDACH;CAEF,IAAI,OAAO,OAAO,SAAS,GACzB,QAAQ,KACN,wCACE,KACD,iHACH;CAGF,OAAO,OAAO,OAAO;AACvB"}
package/dist/codegen.cjs CHANGED
@@ -1,70 +1,74 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ const require_metadata = require('./metadata.cjs');
4
+ const require_type_checks = require('./type-checks.cjs');
3
5
  const require_helpers = require('./helpers.cjs');
4
6
  let _stryke_convert_to_bool = require("@stryke/convert/to-bool");
5
7
  let _stryke_type_checks_is_boolean = require("@stryke/type-checks/is-boolean");
6
8
  let _stryke_type_checks_is_null = require("@stryke/type-checks/is-null");
7
9
  let _stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
10
+ let _stryke_type_checks_is_set_string = require("@stryke/type-checks/is-set-string");
8
11
  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);
12
+ let ajv = require("ajv");
13
+ ajv = require_runtime.__toESM(ajv, 1);
14
+ let ajv_formats_dist_formats_js = require("ajv-formats/dist/formats.js");
15
+ let ajv_dist_compile_codegen_index_js = require("ajv/dist/compile/codegen/index.js");
16
+ let ajv_dist_standalone_index_js = require("ajv/dist/standalone/index.js");
17
+ ajv_dist_standalone_index_js = require_runtime.__toESM(ajv_dist_standalone_index_js, 1);
13
18
 
14
19
  //#region src/codegen.ts
15
20
  /**
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.
21
+ * Stringifies a value for generated TypeScript code.
23
22
  */
24
23
  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);
24
+ 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 === "number" || (0, _stryke_type_checks_is_number.isNumber)(value) ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type === "integer" ? Number.parseInt(String(value)).toLocaleString() : JSON.stringify(value);
26
25
  }
27
26
  /**
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.
27
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
32
28
  */
33
29
  function stringifyType(schema) {
34
30
  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";
31
+ if ((0, _stryke_type_checks_is_set_string.isSetString)(schema.$ref)) return /^#\/(?:definitions|\$defs)\/(.+)$/.exec(schema.$ref)?.[1] ?? schema.$ref;
32
+ const primaryType = require_metadata.getPrimarySchemaType(schema);
33
+ if (primaryType) {
34
+ if (primaryType === "integer" || primaryType === "number") return "number";
35
+ return primaryType;
36
+ }
37
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
38
+ if (schema.const !== void 0) return JSON.stringify(schema.const);
39
+ if (schema.type === "array" || schema.items) return `${stringifyType(Array.isArray(schema.items) ? schema.items[0] : schema.items)}[]`;
40
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
41
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") return `{ [key: string]: ${stringifyType(schema.additionalProperties)} }`;
42
+ if (require_type_checks.isJsonSchemaObject(schema)) return `{ ${require_helpers.getPropertiesList(schema).map((property) => {
43
+ const suffix = property.optional || property.nullable ? `${property.optional ? "?" : ""}${property.nullable ? " | null" : ""}` : "";
44
+ return `${property.key}${suffix}: ${stringifyType(property.value)}`;
45
+ }).join(";\n")} }`;
46
+ }
47
+ if (schema.oneOf || schema.anyOf) return (schema.oneOf ?? schema.anyOf ?? []).map((branch) => stringifyType(branch)).join(" | ");
48
+ if (schema.allOf) return "object";
48
49
  return "unknown";
49
50
  }
50
51
  /**
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.
52
- *
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.
54
- * @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.
55
- * @returns A promise that resolves to a string containing the generated standalone validation code.
52
+ * Generates standalone JSON Schema validation code using Ajv.
56
53
  */
57
54
  async function generateCode(schemas, refsOrFuncts) {
58
- return (0, ajv_lib_standalone_index_ts.default)(new ajv_lib_jtd_ts.default({
55
+ const ajv$1 = new ajv.default({
59
56
  schemas,
60
57
  code: {
61
58
  source: true,
62
59
  esm: true
63
60
  }
64
- }), refsOrFuncts);
61
+ });
62
+ ajv$1.opts.code.formats ??= ajv_dist_compile_codegen_index_js._`await import("ajv-formats/dist/formats").${new ajv_dist_compile_codegen_index_js.Name("fullFormats")}`;
63
+ for (const formatName of ajv_formats_dist_formats_js.formatNames) ajv$1.addFormat(formatName, ajv_formats_dist_formats_js.fullFormats[formatName]);
64
+ return (0, ajv_dist_standalone_index_js.default)(ajv$1, refsOrFuncts);
65
+ }
66
+ function isNullableSchema(schema) {
67
+ return require_metadata.isSchemaNullable(schema);
65
68
  }
66
69
 
67
70
  //#endregion
68
71
  exports.generateCode = generateCode;
72
+ exports.isNullableSchema = isNullableSchema;
69
73
  exports.stringifyType = stringifyType;
70
74
  exports.stringifyValue = stringifyValue;
@@ -1,33 +1,21 @@
1
- import { JTDSchemaType, JTDType } from "./types.cjs";
2
- import { Options } from "ajv/lib/jtd.ts";
3
- import standaloneCode from "ajv/lib/standalone/index.ts";
1
+ import { JsonSchema, JsonSchemaPrimitiveType } from "./types.cjs";
2
+ import { Options } from "ajv";
3
+ import standaloneCode from "ajv/dist/standalone/index.js";
4
4
 
5
5
  //#region src/codegen.d.ts
6
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.
7
+ * Stringifies a value for generated TypeScript code.
14
8
  */
15
- declare function stringifyValue(value?: unknown, type?: JTDType): string;
9
+ declare function stringifyValue(value?: unknown, type?: JsonSchemaPrimitiveType | string): string;
16
10
  /**
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.
11
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
21
12
  */
22
- declare function stringifyType(schema?: JTDSchemaType): string;
13
+ declare function stringifyType<T = unknown>(schema?: JsonSchema<T>): string;
23
14
  /**
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.
25
- *
26
- * @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.
27
- * @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.
28
- * @returns A promise that resolves to a string containing the generated standalone validation code.
15
+ * Generates standalone JSON Schema validation code using Ajv.
29
16
  */
30
17
  declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
18
+ declare function isNullableSchema(schema?: JsonSchema): boolean;
31
19
  //#endregion
32
- export { generateCode, stringifyType, stringifyValue };
20
+ export { generateCode, isNullableSchema, stringifyType, stringifyValue };
33
21
  //# sourceMappingURL=codegen.d.cts.map
@@ -1 +1 @@
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
+ {"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAqCA;iBAAgB,cAAA,CACd,KAAA,YACA,IAAA,GAAO,uBAAuB;;;;iBAoBhB,aAAA,aAAA,CAA2B,MAAA,GAAS,UAAU,CAAC,CAAA;;;AApBtB;iBAgGnB,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA;AAAA,iBAiBrC,gBAAA,CAAiB,MAAmB,GAAV,UAAU"}
@@ -1,33 +1,21 @@
1
- import { JTDSchemaType, JTDType } from "./types.mjs";
2
- import { Options } from "ajv/lib/jtd.ts";
3
- import standaloneCode from "ajv/lib/standalone/index.ts";
1
+ import { JsonSchema, JsonSchemaPrimitiveType } from "./types.mjs";
2
+ import { Options } from "ajv";
3
+ import standaloneCode from "ajv/dist/standalone/index.js";
4
4
 
5
5
  //#region src/codegen.d.ts
6
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.
7
+ * Stringifies a value for generated TypeScript code.
14
8
  */
15
- declare function stringifyValue(value?: unknown, type?: JTDType): string;
9
+ declare function stringifyValue(value?: unknown, type?: JsonSchemaPrimitiveType | string): string;
16
10
  /**
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.
11
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
21
12
  */
22
- declare function stringifyType(schema?: JTDSchemaType): string;
13
+ declare function stringifyType<T = unknown>(schema?: JsonSchema<T>): string;
23
14
  /**
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.
25
- *
26
- * @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.
27
- * @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.
28
- * @returns A promise that resolves to a string containing the generated standalone validation code.
15
+ * Generates standalone JSON Schema validation code using Ajv.
29
16
  */
30
17
  declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
18
+ declare function isNullableSchema(schema?: JsonSchema): boolean;
31
19
  //#endregion
32
- export { generateCode, stringifyType, stringifyValue };
20
+ export { generateCode, isNullableSchema, stringifyType, stringifyValue };
33
21
  //# sourceMappingURL=codegen.d.mts.map
@@ -1 +1 @@
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"}
1
+ {"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAqCA;iBAAgB,cAAA,CACd,KAAA,YACA,IAAA,GAAO,uBAAuB;;;;iBAoBhB,aAAA,aAAA,CAA2B,MAAA,GAAS,UAAU,CAAC,CAAA;;;AApBtB;iBAgGnB,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA;AAAA,iBAiBrC,gBAAA,CAAiB,MAAmB,GAAV,UAAU"}
package/dist/codegen.mjs CHANGED
@@ -1,65 +1,68 @@
1
- import { getProperties } from "./helpers.mjs";
1
+ import { getPrimarySchemaType, isSchemaNullable } from "./metadata.mjs";
2
+ import { isJsonSchemaObject } from "./type-checks.mjs";
3
+ import { getPropertiesList } from "./helpers.mjs";
2
4
  import { toBool } from "@stryke/convert/to-bool";
3
5
  import { isBoolean } from "@stryke/type-checks/is-boolean";
4
6
  import { isNull } from "@stryke/type-checks/is-null";
5
7
  import { isNumber } from "@stryke/type-checks/is-number";
8
+ import { isSetString } from "@stryke/type-checks/is-set-string";
6
9
  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";
10
+ import Ajv from "ajv";
11
+ import { formatNames, fullFormats } from "ajv-formats/dist/formats.js";
12
+ import { Name, _ } from "ajv/dist/compile/codegen/index.js";
13
+ import standaloneCode from "ajv/dist/standalone/index.js";
9
14
 
10
15
  //#region src/codegen.ts
11
16
  /**
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.
17
+ * Stringifies a value for generated TypeScript code.
19
18
  */
20
19
  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);
20
+ return isUndefined(value) ? "undefined" : isNull(value) ? "null" : type === "boolean" || isBoolean(value) ? String(toBool(value)) : type === "number" || isNumber(value) ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type === "integer" ? Number.parseInt(String(value)).toLocaleString() : JSON.stringify(value);
22
21
  }
23
22
  /**
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.
23
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
28
24
  */
29
25
  function stringifyType(schema) {
30
26
  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";
27
+ if (isSetString(schema.$ref)) return /^#\/(?:definitions|\$defs)\/(.+)$/.exec(schema.$ref)?.[1] ?? schema.$ref;
28
+ const primaryType = getPrimarySchemaType(schema);
29
+ if (primaryType) {
30
+ if (primaryType === "integer" || primaryType === "number") return "number";
31
+ return primaryType;
32
+ }
33
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
34
+ if (schema.const !== void 0) return JSON.stringify(schema.const);
35
+ if (schema.type === "array" || schema.items) return `${stringifyType(Array.isArray(schema.items) ? schema.items[0] : schema.items)}[]`;
36
+ if (schema.type === "object" || schema.properties || schema.additionalProperties) {
37
+ if (schema.additionalProperties && typeof schema.additionalProperties === "object") return `{ [key: string]: ${stringifyType(schema.additionalProperties)} }`;
38
+ if (isJsonSchemaObject(schema)) return `{ ${getPropertiesList(schema).map((property) => {
39
+ const suffix = property.optional || property.nullable ? `${property.optional ? "?" : ""}${property.nullable ? " | null" : ""}` : "";
40
+ return `${property.key}${suffix}: ${stringifyType(property.value)}`;
41
+ }).join(";\n")} }`;
42
+ }
43
+ if (schema.oneOf || schema.anyOf) return (schema.oneOf ?? schema.anyOf ?? []).map((branch) => stringifyType(branch)).join(" | ");
44
+ if (schema.allOf) return "object";
44
45
  return "unknown";
45
46
  }
46
47
  /**
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.
48
- *
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.
50
- * @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.
51
- * @returns A promise that resolves to a string containing the generated standalone validation code.
48
+ * Generates standalone JSON Schema validation code using Ajv.
52
49
  */
53
50
  async function generateCode(schemas, refsOrFuncts) {
54
- return standaloneCode(new Ajv({
51
+ const ajv = new Ajv({
55
52
  schemas,
56
53
  code: {
57
54
  source: true,
58
55
  esm: true
59
56
  }
60
- }), refsOrFuncts);
57
+ });
58
+ ajv.opts.code.formats ??= _`await import("ajv-formats/dist/formats").${new Name("fullFormats")}`;
59
+ for (const formatName of formatNames) ajv.addFormat(formatName, fullFormats[formatName]);
60
+ return standaloneCode(ajv, refsOrFuncts);
61
+ }
62
+ function isNullableSchema(schema) {
63
+ return isSchemaNullable(schema);
61
64
  }
62
65
 
63
66
  //#endregion
64
- export { generateCode, stringifyType, stringifyValue };
67
+ export { generateCode, isNullableSchema, stringifyType, stringifyValue };
65
68
  //# sourceMappingURL=codegen.mjs.map