@power-plant/schema 0.0.2

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 (81) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +45 -0
  3. package/dist/bundle.cjs +1 -0
  4. package/dist/bundle.d.cts +18 -0
  5. package/dist/bundle.d.cts.map +1 -0
  6. package/dist/bundle.d.mts +18 -0
  7. package/dist/bundle.d.mts.map +1 -0
  8. package/dist/bundle.mjs +2 -0
  9. package/dist/bundle.mjs.map +1 -0
  10. package/dist/codegen.cjs +77 -0
  11. package/dist/codegen.d.cts +49 -0
  12. package/dist/codegen.d.cts.map +1 -0
  13. package/dist/codegen.d.mts +49 -0
  14. package/dist/codegen.d.mts.map +1 -0
  15. package/dist/codegen.mjs +78 -0
  16. package/dist/codegen.mjs.map +1 -0
  17. package/dist/constants-Cx9_Shfk.d.cts +32 -0
  18. package/dist/constants-Cx9_Shfk.d.cts.map +1 -0
  19. package/dist/constants-Cx9_Shfk.d.mts +32 -0
  20. package/dist/constants-Cx9_Shfk.d.mts.map +1 -0
  21. package/dist/constants.cjs +1 -0
  22. package/dist/constants.d.cts +2 -0
  23. package/dist/constants.d.mts +2 -0
  24. package/dist/constants.mjs +2 -0
  25. package/dist/constants.mjs.map +1 -0
  26. package/dist/extract.cjs +1 -0
  27. package/dist/extract.d.cts +130 -0
  28. package/dist/extract.d.cts.map +1 -0
  29. package/dist/extract.d.mts +130 -0
  30. package/dist/extract.d.mts.map +1 -0
  31. package/dist/extract.mjs +1 -0
  32. package/dist/helpers.cjs +1 -0
  33. package/dist/helpers.d.cts +123 -0
  34. package/dist/helpers.d.cts.map +1 -0
  35. package/dist/helpers.d.mts +123 -0
  36. package/dist/helpers.d.mts.map +1 -0
  37. package/dist/helpers.mjs +2 -0
  38. package/dist/helpers.mjs.map +1 -0
  39. package/dist/index.cjs +1 -0
  40. package/dist/index.d.cts +37 -0
  41. package/dist/index.d.cts.map +1 -0
  42. package/dist/index.d.mts +37 -0
  43. package/dist/index.d.mts.map +1 -0
  44. package/dist/index.mjs +1 -0
  45. package/dist/metadata.cjs +1 -0
  46. package/dist/metadata.d.cts +31 -0
  47. package/dist/metadata.d.cts.map +1 -0
  48. package/dist/metadata.d.mts +31 -0
  49. package/dist/metadata.d.mts.map +1 -0
  50. package/dist/metadata.mjs +2 -0
  51. package/dist/metadata.mjs.map +1 -0
  52. package/dist/persistence-B9pzElsC.mjs +2 -0
  53. package/dist/persistence-B9pzElsC.mjs.map +1 -0
  54. package/dist/persistence-CLni2zCP.cjs +1 -0
  55. package/dist/persistence.cjs +1 -0
  56. package/dist/persistence.d.cts +58 -0
  57. package/dist/persistence.d.cts.map +1 -0
  58. package/dist/persistence.d.mts +58 -0
  59. package/dist/persistence.d.mts.map +1 -0
  60. package/dist/persistence.mjs +1 -0
  61. package/dist/resolve.cjs +1 -0
  62. package/dist/resolve.d.cts +45 -0
  63. package/dist/resolve.d.cts.map +1 -0
  64. package/dist/resolve.d.mts +45 -0
  65. package/dist/resolve.d.mts.map +1 -0
  66. package/dist/resolve.mjs +2 -0
  67. package/dist/resolve.mjs.map +1 -0
  68. package/dist/type-checks.cjs +1 -0
  69. package/dist/type-checks.d.cts +324 -0
  70. package/dist/type-checks.d.cts.map +1 -0
  71. package/dist/type-checks.d.mts +324 -0
  72. package/dist/type-checks.d.mts.map +1 -0
  73. package/dist/type-checks.mjs +2 -0
  74. package/dist/type-checks.mjs.map +1 -0
  75. package/dist/types.cjs +0 -0
  76. package/dist/types.d.cts +1254 -0
  77. package/dist/types.d.cts.map +1 -0
  78. package/dist/types.d.mts +1254 -0
  79. package/dist/types.d.mts.map +1 -0
  80. package/dist/types.mjs +1 -0
  81. package/package.json +254 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ <!-- START header -->
2
+
3
+ <!-- END header -->
4
+
5
+ # Power Plant - Schema
6
+
7
+ **Power Plant Schema** allows you to generate anything from a spec.
8
+
9
+ ## Installing
10
+
11
+ Using [pnpm](http://pnpm.io):
12
+
13
+ ```bash
14
+ pnpm add -D @power-plant/schema
15
+ ```
16
+
17
+ <details>
18
+ <summary>Using npm</summary>
19
+
20
+ ```bash
21
+ npm install -D @power-plant/schema
22
+ ```
23
+
24
+ </details>
25
+
26
+ <details>
27
+ <summary>Using yarn</summary>
28
+
29
+ ```bash
30
+ yarn add -D @power-plant/schema
31
+ ```
32
+
33
+ </details>
34
+
35
+ ## Building
36
+
37
+ Run `nx build schema` to build the library.
38
+
39
+ ## Running unit tests
40
+
41
+ Run `nx test schema` to execute the unit tests via [Vitest](https://vitest.dev/).
42
+
43
+ <!-- START footer -->
44
+
45
+ <!-- END footer -->
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@stryke/helpers/omit"),t=require("esbuild"),n=require("node:fs");async function r(r,i={}){if(!r||!(0,n.existsSync)(r))throw Error(`Module not found: "${r}". Please check the path and try again.`);let a=await(0,t.build)({platform:`node`,format:`esm`,...(0,e.omit)(i,[`debug`]),logLevel:`silent`,entryPoints:[r],write:!1,sourcemap:!1,splitting:!1,treeShaking:!0,bundle:!0,packages:`bundle`,keepNames:!0,metafile:!1});if(a.errors.length>0)throw Error(`Failed to bundle ${r}: ${a.errors.map(e=>e.text).join(`, `)}`);if(!a.outputFiles||a.outputFiles.filter(Boolean).length===0)throw Error(`No output files generated for ${r}. Please check the configuration and try again.`);return a.outputFiles.filter(Boolean)[0]}exports.bundle=r;
@@ -0,0 +1,18 @@
1
+ import { DeepPartial } from "@stryke/types/base";
2
+ import { BuildOptions, OutputFile } from "esbuild";
3
+
4
+ //#region src/bundle.d.ts
5
+ type BundleOptions = DeepPartial<BuildOptions> & {
6
+ debug?: boolean;
7
+ };
8
+ /**
9
+ * Bundle a type definition to a module.
10
+ *
11
+ * @param file - The file path to bundle.
12
+ * @param options - Optional overrides for the ESBuild configuration.
13
+ * @returns A promise that resolves to the bundled module.
14
+ */
15
+ declare function bundle(file: string, options?: BundleOptions): Promise<OutputFile>;
16
+ //#endregion
17
+ export { BundleOptions, bundle };
18
+ //# sourceMappingURL=bundle.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.d.cts","names":[],"sources":["../src/bundle.ts"],"mappings":";;;;KAwBY,aAAA,GAAgB,WAAW,CAAC,YAAA;EACtC,KAAA;AAAA;;;;;;;;iBAUoB,MAAA,CACpB,IAAA,UACA,OAAA,GAAS,aAAA,GACR,OAAA,CAAQ,UAAA"}
@@ -0,0 +1,18 @@
1
+ import { BuildOptions, OutputFile } from "esbuild";
2
+ import { DeepPartial } from "@stryke/types/base";
3
+
4
+ //#region src/bundle.d.ts
5
+ type BundleOptions = DeepPartial<BuildOptions> & {
6
+ debug?: boolean;
7
+ };
8
+ /**
9
+ * Bundle a type definition to a module.
10
+ *
11
+ * @param file - The file path to bundle.
12
+ * @param options - Optional overrides for the ESBuild configuration.
13
+ * @returns A promise that resolves to the bundled module.
14
+ */
15
+ declare function bundle(file: string, options?: BundleOptions): Promise<OutputFile>;
16
+ //#endregion
17
+ export { BundleOptions, bundle };
18
+ //# sourceMappingURL=bundle.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.d.mts","names":[],"sources":["../src/bundle.ts"],"mappings":""}
@@ -0,0 +1,2 @@
1
+ import{omit as e}from"@stryke/helpers/omit";import{build as t}from"esbuild";import{existsSync as n}from"node:fs";async function r(r,i={}){if(!r||!n(r))throw Error(`Module not found: "${r}". Please check the path and try again.`);let a=await t({platform:`node`,format:`esm`,...e(i,[`debug`]),logLevel:`silent`,entryPoints:[r],write:!1,sourcemap:!1,splitting:!1,treeShaking:!0,bundle:!0,packages:`bundle`,keepNames:!0,metafile:!1});if(a.errors.length>0)throw Error(`Failed to bundle ${r}: ${a.errors.map(e=>e.text).join(`, `)}`);if(!a.outputFiles||a.outputFiles.filter(Boolean).length===0)throw Error(`No output files generated for ${r}. Please check the configuration and try again.`);return a.outputFiles.filter(Boolean)[0]}export{r as bundle};
2
+ //# sourceMappingURL=bundle.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.mjs","names":[],"sources":[],"mappings":""}
@@ -0,0 +1,77 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./type-checks.cjs"),t=require("./metadata.cjs"),n=require("./helpers.cjs");let r=require("@stryke/type-checks"),i=require("@stryke/type-checks/is-set-string"),a=require("@stryke/string-format/list"),o=require("@stryke/convert/to-bool"),s=require("@stryke/string-format/camel-case"),c=require("@stryke/type-checks/is-boolean"),l=require("@stryke/type-checks/is-null"),u=require("@stryke/type-checks/is-number"),d=require("@stryke/type-checks/is-undefined");function f(e,t){return(0,d.isUndefined)(e)?`undefined`:(0,l.isNull)(e)?`null`:t===`boolean`||(0,c.isBoolean)(e)?String((0,o.toBool)(e)):t===`number`||(0,u.isNumber)(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function p(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(e.isJsonSchemaObject(r)&&(0,i.isSetString)(r.name))return r.name;let a=r;if((0,i.isSetString)(a.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(a.$ref)?.[1]??a.$ref;if(e.isJsonSchemaLiteral(r)&&!(0,d.isUndefined)(r.const))return JSON.stringify((0,i.isSetString)(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let o=t.getPrimarySchemaType(r);if(o)return o===`integer`||o===`number`?`number`:o;if(a.type===`array`&&Array.isArray(a.enum))return a.enum.map(e=>JSON.stringify(e)).join(` | `);if(a.const!==void 0)return JSON.stringify(a.const);if(a.type===`array`||a.items)return`${p(Array.isArray(a.items)?a.items[0]:a.items)}[]`;if(a.type===`object`||a.properties||a.additionalProperties){if(e.isJsonSchema(a.additionalProperties))return`{ [key: string]: ${p(a.additionalProperties)} }`;if(e.isJsonSchemaObject(a)){let e=a.required??[];return`{ ${n.getPropertiesList(a).map(t=>{let r=!e.includes(t.name)||n.isSchemaNullable(t)?`${e.includes(t.name)?``:`?`}${n.isSchemaNullable(t)?` | null`:``}`:``;return`${t.name}${r}: ${p(t)}`}).join(`;
2
+ `)} }`}}return a.oneOf||a.anyOf?(a.oneOf??a.anyOf??[]).map(e=>p(e)).join(` | `):a.allOf?`object`:`unknown`}function m(e){return(0,l.isNull)(e)?`null`:(0,c.isBoolean)(e)?`boolean`:(0,r.isInteger)(e)?`integer`:(0,u.isNumber)(e)?`number`:(0,r.isString)(e)?`string`:(0,r.isObject)(e)?`object`:Array.isArray(e)?`array`:void 0}function h(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function g(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function _(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function v(e,t){return`${e} + ${JSON.stringify(t)}`}function y(o,c={}){let l=o,u=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},d={};function f(e){let t=d[e]??0;return d[e]=t+1,`${e}${t>0?`${t}`:``}`}function m(e,t,r,a,o=`errors`){if(typeof e==`boolean`)return e?[`${a} = ${t};`]:[`${o}.push({ path: ${r}, failure: "No value is allowed at this location" });`,`${a} = ${t};`];if((0,i.isSetString)(e.$ref)){let n=h(e.$ref);return n&&n in u?[`${a} = ${g(n)}(${t}, ${r}, ${o});`]:[`${a} = ${t};`]}let l=f(e.name?`${(0,s.camelCase)(e.name)}Value`:`value`),d=f(e.name?`${(0,s.camelCase)(e.name)}Path`:`path`),p=[`const ${l} = ${t};`,`const ${d} = ${r};`];return!c.ignoreDefaults&&e.default!==void 0?(p.push(`if (${l} === undefined${e.type===`string`?` || ${l} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${l})`:``}) {`,` ${a} = ${JSON.stringify(e.default)};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,o)),p.push(` }`)):p.push(...y(e,l,d,a,o)),p.push(`}`),p):(p.push(`if (${l} === undefined) {`,` ${o}.push({ path: ${d}, failure: "A value is required" });`,` ${a} = ${l};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,o)),p.push(` }`)):p.push(...y(e,l,d,a,o)),p.push(`}`),p)}function y(e,r,i,o,c){let l=[];if(e.const!==void 0){let t=JSON.stringify(e.const);return l.push(`if (${e.type===`string`?r:`JSON.stringify(${r})`} !== ${t}) { ${c}.push({ path: ${i}, failure: "Expected the constant value " + ${t} }); }`,`${o} = ${t};`),l}if(Array.isArray(e.enum)){let t=JSON.stringify(e.enum);return l.push(`if (!${t}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${r}))) { ${c}.push({ path: ${i}, failure: \`Expected one of: ${(0,a.list)(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${r})}\` }); }`,`${o} = ${r};`),l}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let t=e.oneOf??e.anyOf??[],n=f(e.name?`${(0,s.camelCase)(e.name)}Matched`:`matched`);l.push(`let ${n} = false;`);for(let a of t){let t=f(e.name?`${(0,s.camelCase)(e.name)}BranchErrors`:`branchErrors`),c=f(e.name?`${(0,s.camelCase)(e.name)}BranchResult`:`branchResult`);l.push(`if (!${n}) {`),l.push(` const ${t}: { path: string; failure: string }[] = [];`,` let ${c};`),l.push(...m(a,r,i,c,t)),l.push(` if (${t}.length === 0) {`,` ${o} = ${c};`,` ${n} = true;`,` }`,`}`)}return l.push(`if (!${n}) {`,` ${c}.push({ path: ${i}, failure: \`The provided value \${JSON.stringify(${r})} does not match the allowed schemas\` });`,` ${o} = ${r};`,`}`),l}if(Array.isArray(e.allOf)){let{allOf:t,...a}=e,s=n.merge(a,...t);return l.push(...m(s,r,i,o,c)),l}let u=_(e);switch(t.getPrimarySchemaType(e)??u.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:l.push(...b(e,r,i,o,c));break;case`array`:l.push(...x(e,r,i,o,c));break;case`string`:l.push(`if (typeof ${r} === "string") {`,` ${o} = ${r};`,`} else if (typeof ${r} === "number" || typeof ${r} === "boolean") {`,` ${o} = String(${r});`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a string value" });`,` ${o} = ${r};`,`}`);break;case`integer`:l.push(`if (typeof ${r} === "number" && Number.isInteger(${r})) {`,` ${o} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && Number.isInteger(Number(${r}))) {`,` ${o} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${o} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected an integer value" });`,` ${o} = ${r};`,`}`);break;case`number`:l.push(`if (typeof ${r} === "number") {`,` ${o} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && !Number.isNaN(Number(${r}))) {`,` ${o} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${o} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a number value" });`,` ${o} = ${r};`,`}`);break;case`boolean`:l.push(`if (typeof ${r} === "boolean") {`,` ${o} = ${r};`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "true" || ${r}.toLowerCase() === "t" || ${r}.toLowerCase() === "yes" || ${r}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) > 0))) || (typeof ${r} === "number" && ${r} > 0)) {`,` ${o} = true;`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "false" || ${r}.toLowerCase() === "f" || ${r}.toLowerCase() === "no" || ${r}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) <= 0))) || (typeof ${r} === "number" && ${r} <= 0)) {`,` ${o} = false;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a boolean value" });`,` ${o} = ${r};`,`}`);break;case`null`:l.push(`if (${r} === null) {`,` ${o} = null;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a null value" });`,` ${o} = ${r};`,`}`);break;case void 0:default:l.push(`${o} = ${r};`);break}return l}function b(t,i,a,o,c){let l=p(t),u=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${a}, failure: "Expected an object value" });`,` ${o} = ${i};`,`} else {`],d=f(l||t.name?`${(0,s.camelCase)(l||t.name)}Schema`:`schema`);if(u.push(`const ${d} = {} as Record<string, any>`),e.isJsonSchemaObject(t)){let o=new Set;for(let l of n.getPropertiesList(t)){o.add(l.name);let t;(0,r.isSetArray)(l.alias)?(t=`(${l.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${e.isJsonSchemaString(l)?`||`:`??`} `)} ${e.isJsonSchemaString(l)?`||`:`??`} ${i}[${JSON.stringify(l.name)}])`,l.alias.forEach(e=>o.add(e))):t=`${i}[${JSON.stringify(l.name)}]`;let n=v(a,`.${l.name}`),p=f(l.name?`${(0,s.camelCase)(l.name)}Property`:`property`),h=l.default===void 0?l.required?`${c}.push({ path: ${n}, failure: "Required property is missing" });`:``:`${d}[${JSON.stringify(l.name)}] = ${JSON.stringify(l.default)};`;u.push(` if (${t} !== undefined) {`,` let ${p};`),u.push(...m(l,t,n,p,c)),u.push(`${d}[${JSON.stringify(l.name)}] = ${p};`),h?u.push(`} else { ${h} }`):u.push(`}`)}let p=t.additionalProperties;if(e.isJsonSchema(p)){let e=f(l||t.name?`${(0,s.camelCase)(l||t.name)}AdditionalProperties`:`additionalProperties`);u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...o])}.includes(key)) { continue; }`,` let ${e};`),u.push(...m(p,`${i}[key]`,`${a} + "." + key`,e,c)),u.push(`${d}[key] = ${e};`,`}`)}else p!==!1&&u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...o])}.includes(key)) { continue; }`,` ${d}[key] = ${i}[key];`,`}`)}return u.push(`${o} = ${d};`,`}`),u}function x(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=f(e.name?`${(0,s.camelCase)(e.name)}Array`:`array`);a.push(`const ${o}: unknown[] = [];`);let c=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(c){let s=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),c.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(...m(e,`item`,v(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),s?(a.push(`else {`),a.push(...m(s,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let l=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(...m(l,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}return`/**
3
+ * Parser error constructor function.
4
+ */
5
+ function ParserError(path, failure) {
6
+ this.path = path;
7
+ this.failure = failure;
8
+ this.name = "ParserError";
9
+ this.message = path + ": " + failure;
10
+ }
11
+ ParserError.prototype = Object.create(Error.prototype);
12
+ ParserError.prototype.constructor = ParserError;
13
+
14
+ /**
15
+ * Represents a parser error with path and failure message.
16
+ */
17
+ export class ParserError extends Error {
18
+ constructor(
19
+ public path: string,
20
+ public failure: string
21
+ ) {
22
+ super(\`\${path}: \${failure}\`);
23
+ this.name = "ParserError";
24
+ }
25
+ }
26
+
27
+ ${Object.entries(u).map(([e,t])=>`function ${g(e)}(inputValue, inputPath, errors) {
28
+ let result;
29
+ ${m(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
30
+ `)}
31
+
32
+ return result;
33
+ }`).join(`
34
+
35
+ `)}
36
+
37
+ /**
38
+ * Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
39
+ *
40
+ * @remarks
41
+ * The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
42
+ *
43
+ * @param value - The input value to parse.
44
+ * @returns The parsed value conforming to the schema or an array of validation errors.
45
+ */
46
+ export function parseSafe(inputValue) {
47
+ const errors = [];
48
+
49
+ let result;
50
+ ${m(o,`inputValue`,`"$"`,`result`,`errors`).join(`
51
+ `)}
52
+
53
+ if (errors.length > 0) {
54
+ return errors;
55
+ }
56
+
57
+ return result;
58
+ }
59
+
60
+ /**
61
+ * Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
62
+ *
63
+ * @remarks
64
+ * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
65
+ *
66
+ * @param value - The input value to parse.
67
+ * @returns The parsed value conforming to the schema.
68
+ * @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
69
+ */
70
+ export function parse(inputValue) {
71
+ const result = parseSafe(inputValue);
72
+ if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
73
+ throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
74
+ }
75
+
76
+ return result;
77
+ }`}exports.generateParserCode=y,exports.getJsonSchemaType=m,exports.stringifyType=p,exports.stringifyValue=f;
@@ -0,0 +1,49 @@
1
+ import { JsonSchema, JsonSchemaType } from "./types.cjs";
2
+
3
+ //#region src/codegen.d.ts
4
+ /**
5
+ * Stringifies a value for generated TypeScript code.
6
+ */
7
+ declare function stringifyValue(value?: unknown, type?: JsonSchemaType | string): string;
8
+ /**
9
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
10
+ */
11
+ declare function stringifyType(schema?: JsonSchema): string;
12
+ /**
13
+ * Returns a string type representation of a value based on its type and an optional JSON Schema primitive type hint.
14
+ *
15
+ * @param value - The value whose type is to be represented as a string.
16
+ * @returns A string representation of the value's type, which may be influenced by the provided JSON Schema primitive type hint. The function handles various JavaScript types and formats them accordingly, including special handling for `undefined`, `null`, booleans, numbers (with formatting), strings, objects, and arrays. If a specific type hint is provided, it will take precedence in determining the string representation of the value.
17
+ */
18
+ declare function getJsonSchemaType(value?: unknown): JsonSchemaType | undefined;
19
+ interface GenerateParserCodeOptions {
20
+ /**
21
+ * The name of the parser function to generate.
22
+ *
23
+ * @defaultValue "parse"
24
+ */
25
+ name?: string;
26
+ /**
27
+ * Whether to ignore `default` values in the schema when generating the parser code. By default, the generated code will apply default values for missing properties and root/array values. Set this option to `true` to disable default value application, causing the generated parser to treat missing values as validation errors instead.
28
+ */
29
+ ignoreDefaults?: boolean;
30
+ }
31
+ /**
32
+ * Generates standalone parser code for a JSON Schema.
33
+ *
34
+ * @remarks
35
+ * The generated `parse` function reads an arbitrary input value and converts it into the shape described by the schema. It walks the schema recursively to:
36
+ * - Resolve local `$ref` pointers (`#/$defs/*` and `#/definitions/*`) into dedicated parser functions so recursive schemas are supported,
37
+ * - If {@link GenerateParserCodeOptions.ignoreDefaults | options.ignoreDefaults} is not `true`, apply `default` values for object properties (and root/array values) that are missing from the input,
38
+ * - Coerce primitive values to the declared type (for example `"42"` to `42` for an `integer` schema, or `1` to `true` for a `boolean` schema),
39
+ * - Validate `const`, `enum`, `oneOf`/`anyOf` and `allOf` constraints, and
40
+ * - Collect detailed, path-aware errors and throw a `Error` when the input cannot be converted into a valid value.
41
+ *
42
+ * @param schema - The JSON Schema to generate parser code for.
43
+ * @param options - Options to customize the generated code. By default, the generated code will apply default values from the schema for missing properties and root/array values. Set `options.ignoreDefaults` to `true` to disable default value application.
44
+ * @returns The generated standalone parser code as a string.
45
+ */
46
+ declare function generateParserCode(schema: JsonSchema, options?: GenerateParserCodeOptions): string;
47
+ //#endregion
48
+ export { GenerateParserCodeOptions, generateParserCode, getJsonSchemaType, stringifyType, stringifyValue };
49
+ //# sourceMappingURL=codegen.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;AAwCA;iBAAgB,cAAA,CACd,KAAA,YACA,IAAA,GAAO,cAAc;;;;iBAsBP,aAAA,CAAc,MAAmB,GAAV,UAAU;;;AAtBjB;AAsBhC;;;iBAsGgB,iBAAA,CAAkB,KAAA,aAAkB,cAAc;AAAA,UAsDjD,yBAAA;EAtDD;;;;AAAkD;EA4DhE,IAAA;EANwC;;;EAWxC,cAAc;AAAA;;;;;;;;;AAoByB;;;;;;;iBAFzB,kBAAA,CACd,MAAA,EAAQ,UAAA,EACR,OAAA,GAAS,yBAA8B"}
@@ -0,0 +1,49 @@
1
+ import { JsonSchema, JsonSchemaType } from "./types.mjs";
2
+
3
+ //#region src/codegen.d.ts
4
+ /**
5
+ * Stringifies a value for generated TypeScript code.
6
+ */
7
+ declare function stringifyValue(value?: unknown, type?: JsonSchemaType | string): string;
8
+ /**
9
+ * Stringifies a JSON Schema fragment into a TypeScript-like type string.
10
+ */
11
+ declare function stringifyType(schema?: JsonSchema): string;
12
+ /**
13
+ * Returns a string type representation of a value based on its type and an optional JSON Schema primitive type hint.
14
+ *
15
+ * @param value - The value whose type is to be represented as a string.
16
+ * @returns A string representation of the value's type, which may be influenced by the provided JSON Schema primitive type hint. The function handles various JavaScript types and formats them accordingly, including special handling for `undefined`, `null`, booleans, numbers (with formatting), strings, objects, and arrays. If a specific type hint is provided, it will take precedence in determining the string representation of the value.
17
+ */
18
+ declare function getJsonSchemaType(value?: unknown): JsonSchemaType | undefined;
19
+ interface GenerateParserCodeOptions {
20
+ /**
21
+ * The name of the parser function to generate.
22
+ *
23
+ * @defaultValue "parse"
24
+ */
25
+ name?: string;
26
+ /**
27
+ * Whether to ignore `default` values in the schema when generating the parser code. By default, the generated code will apply default values for missing properties and root/array values. Set this option to `true` to disable default value application, causing the generated parser to treat missing values as validation errors instead.
28
+ */
29
+ ignoreDefaults?: boolean;
30
+ }
31
+ /**
32
+ * Generates standalone parser code for a JSON Schema.
33
+ *
34
+ * @remarks
35
+ * The generated `parse` function reads an arbitrary input value and converts it into the shape described by the schema. It walks the schema recursively to:
36
+ * - Resolve local `$ref` pointers (`#/$defs/*` and `#/definitions/*`) into dedicated parser functions so recursive schemas are supported,
37
+ * - If {@link GenerateParserCodeOptions.ignoreDefaults | options.ignoreDefaults} is not `true`, apply `default` values for object properties (and root/array values) that are missing from the input,
38
+ * - Coerce primitive values to the declared type (for example `"42"` to `42` for an `integer` schema, or `1` to `true` for a `boolean` schema),
39
+ * - Validate `const`, `enum`, `oneOf`/`anyOf` and `allOf` constraints, and
40
+ * - Collect detailed, path-aware errors and throw a `Error` when the input cannot be converted into a valid value.
41
+ *
42
+ * @param schema - The JSON Schema to generate parser code for.
43
+ * @param options - Options to customize the generated code. By default, the generated code will apply default values from the schema for missing properties and root/array values. Set `options.ignoreDefaults` to `true` to disable default value application.
44
+ * @returns The generated standalone parser code as a string.
45
+ */
46
+ declare function generateParserCode(schema: JsonSchema, options?: GenerateParserCodeOptions): string;
47
+ //#endregion
48
+ export { GenerateParserCodeOptions, generateParserCode, getJsonSchemaType, stringifyType, stringifyValue };
49
+ //# sourceMappingURL=codegen.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":""}
@@ -0,0 +1,78 @@
1
+ import{isJsonSchema as e,isJsonSchemaLiteral as t,isJsonSchemaObject as n,isJsonSchemaString as r}from"./type-checks.mjs";import{getPrimarySchemaType as i}from"./metadata.mjs";import{getPropertiesList as a,isSchemaNullable as o,merge as s}from"./helpers.mjs";import{isInteger as c,isObject as l,isSetArray as u,isString as d}from"@stryke/type-checks";import{isSetString as f}from"@stryke/type-checks/is-set-string";import{list as p}from"@stryke/string-format/list";import{toBool as m}from"@stryke/convert/to-bool";import{camelCase as h}from"@stryke/string-format/camel-case";import{isBoolean as g}from"@stryke/type-checks/is-boolean";import{isNull as _}from"@stryke/type-checks/is-null";import{isNumber as v}from"@stryke/type-checks/is-number";import{isUndefined as y}from"@stryke/type-checks/is-undefined";function b(e,t){return y(e)?`undefined`:_(e)?`null`:t===`boolean`||g(e)?String(m(e)):t===`number`||v(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function x(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(n(r)&&f(r.name))return r.name;let s=r;if(f(s.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(s.$ref)?.[1]??s.$ref;if(t(r)&&!y(r.const))return JSON.stringify(f(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let c=i(r);if(c)return c===`integer`||c===`number`?`number`:c;if(s.type===`array`&&Array.isArray(s.enum))return s.enum.map(e=>JSON.stringify(e)).join(` | `);if(s.const!==void 0)return JSON.stringify(s.const);if(s.type===`array`||s.items)return`${x(Array.isArray(s.items)?s.items[0]:s.items)}[]`;if(s.type===`object`||s.properties||s.additionalProperties){if(e(s.additionalProperties))return`{ [key: string]: ${x(s.additionalProperties)} }`;if(n(s)){let e=s.required??[];return`{ ${a(s).map(t=>{let n=!e.includes(t.name)||o(t)?`${e.includes(t.name)?``:`?`}${o(t)?` | null`:``}`:``;return`${t.name}${n}: ${x(t)}`}).join(`;
2
+ `)} }`}}return s.oneOf||s.anyOf?(s.oneOf??s.anyOf??[]).map(e=>x(e)).join(` | `):s.allOf?`object`:`unknown`}function S(e){return _(e)?`null`:g(e)?`boolean`:c(e)?`integer`:v(e)?`number`:d(e)?`string`:l(e)?`object`:Array.isArray(e)?`array`:void 0}function C(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function w(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function T(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function E(e,t){return`${e} + ${JSON.stringify(t)}`}function D(t,c={}){let l=t,d=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},m={};function g(e){let t=m[e]??0;return m[e]=t+1,`${e}${t>0?`${t}`:``}`}function _(e,t,n,r,i=`errors`){if(typeof e==`boolean`)return e?[`${r} = ${t};`]:[`${i}.push({ path: ${n}, failure: "No value is allowed at this location" });`,`${r} = ${t};`];if(f(e.$ref)){let a=C(e.$ref);return a&&a in d?[`${r} = ${w(a)}(${t}, ${n}, ${i});`]:[`${r} = ${t};`]}let a=g(e.name?`${h(e.name)}Value`:`value`),s=g(e.name?`${h(e.name)}Path`:`path`),l=[`const ${a} = ${t};`,`const ${s} = ${n};`];return!c.ignoreDefaults&&e.default!==void 0?(l.push(`if (${a} === undefined${e.type===`string`?` || ${a} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${a})`:``}) {`,` ${r} = ${JSON.stringify(e.default)};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l):(l.push(`if (${a} === undefined) {`,` ${i}.push({ path: ${s}, failure: "A value is required" });`,` ${r} = ${a};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l)}function v(e,t,n,r,a){let o=[];if(e.const!==void 0){let i=JSON.stringify(e.const);return o.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${i}) { ${a}.push({ path: ${n}, failure: "Expected the constant value " + ${i} }); }`,`${r} = ${i};`),o}if(Array.isArray(e.enum)){let i=JSON.stringify(e.enum);return o.push(`if (!${i}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${a}.push({ path: ${n}, failure: \`Expected one of: ${p(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),o}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let i=e.oneOf??e.anyOf??[],s=g(e.name?`${h(e.name)}Matched`:`matched`);o.push(`let ${s} = false;`);for(let a of i){let i=g(e.name?`${h(e.name)}BranchErrors`:`branchErrors`),c=g(e.name?`${h(e.name)}BranchResult`:`branchResult`);o.push(`if (!${s}) {`),o.push(` const ${i}: { path: string; failure: string }[] = [];`,` let ${c};`),o.push(..._(a,t,n,c,i)),o.push(` if (${i}.length === 0) {`,` ${r} = ${c};`,` ${s} = true;`,` }`,`}`)}return o.push(`if (!${s}) {`,` ${a}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),o}if(Array.isArray(e.allOf)){let{allOf:i,...c}=e,l=s(c,...i);return o.push(..._(l,t,n,r,a)),o}let c=T(e);switch(i(e)??c.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:o.push(...y(e,t,n,r,a));break;case`array`:o.push(...b(e,t,n,r,a));break;case`string`:o.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:o.push(`if (typeof ${t} === "number" && Number.isInteger(${t})) {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && Number.isInteger(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:o.push(`if (typeof ${t} === "number") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && !Number.isNaN(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:o.push(`if (typeof ${t} === "boolean") {`,` ${r} = ${t};`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "true" || ${t}.toLowerCase() === "t" || ${t}.toLowerCase() === "yes" || ${t}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) > 0))) || (typeof ${t} === "number" && ${t} > 0)) {`,` ${r} = true;`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "false" || ${t}.toLowerCase() === "f" || ${t}.toLowerCase() === "no" || ${t}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) <= 0))) || (typeof ${t} === "number" && ${t} <= 0)) {`,` ${r} = false;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:o.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:o.push(`${r} = ${t};`);break}return o}function y(t,i,o,s,c){let l=x(t),d=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${o}, failure: "Expected an object value" });`,` ${s} = ${i};`,`} else {`],f=g(l||t.name?`${h(l||t.name)}Schema`:`schema`);if(d.push(`const ${f} = {} as Record<string, any>`),n(t)){let n=new Set;for(let e of a(t)){n.add(e.name);let t;u(e.alias)?(t=`(${e.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${r(e)?`||`:`??`} `)} ${r(e)?`||`:`??`} ${i}[${JSON.stringify(e.name)}])`,e.alias.forEach(e=>n.add(e))):t=`${i}[${JSON.stringify(e.name)}]`;let a=E(o,`.${e.name}`),s=g(e.name?`${h(e.name)}Property`:`property`),l=e.default===void 0?e.required?`${c}.push({ path: ${a}, failure: "Required property is missing" });`:``:`${f}[${JSON.stringify(e.name)}] = ${JSON.stringify(e.default)};`;d.push(` if (${t} !== undefined) {`,` let ${s};`),d.push(..._(e,t,a,s,c)),d.push(`${f}[${JSON.stringify(e.name)}] = ${s};`),l?d.push(`} else { ${l} }`):d.push(`}`)}let s=t.additionalProperties;if(e(s)){let e=g(l||t.name?`${h(l||t.name)}AdditionalProperties`:`additionalProperties`);d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` let ${e};`),d.push(..._(s,`${i}[key]`,`${o} + "." + key`,e,c)),d.push(`${f}[key] = ${e};`,`}`)}else s!==!1&&d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` ${f}[key] = ${i}[key];`,`}`)}return d.push(`${s} = ${f};`,`}`),d}function b(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=g(e.name?`${h(e.name)}Array`:`array`);a.push(`const ${o}: unknown[] = [];`);let s=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(s){let c=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),s.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(..._(e,`item`,E(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),c?(a.push(`else {`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let c=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}return`/**
3
+ * Parser error constructor function.
4
+ */
5
+ function ParserError(path, failure) {
6
+ this.path = path;
7
+ this.failure = failure;
8
+ this.name = "ParserError";
9
+ this.message = path + ": " + failure;
10
+ }
11
+ ParserError.prototype = Object.create(Error.prototype);
12
+ ParserError.prototype.constructor = ParserError;
13
+
14
+ /**
15
+ * Represents a parser error with path and failure message.
16
+ */
17
+ export class ParserError extends Error {
18
+ constructor(
19
+ public path: string,
20
+ public failure: string
21
+ ) {
22
+ super(\`\${path}: \${failure}\`);
23
+ this.name = "ParserError";
24
+ }
25
+ }
26
+
27
+ ${Object.entries(d).map(([e,t])=>`function ${w(e)}(inputValue, inputPath, errors) {
28
+ let result;
29
+ ${_(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
30
+ `)}
31
+
32
+ return result;
33
+ }`).join(`
34
+
35
+ `)}
36
+
37
+ /**
38
+ * Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
39
+ *
40
+ * @remarks
41
+ * The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
42
+ *
43
+ * @param value - The input value to parse.
44
+ * @returns The parsed value conforming to the schema or an array of validation errors.
45
+ */
46
+ export function parseSafe(inputValue) {
47
+ const errors = [];
48
+
49
+ let result;
50
+ ${_(t,`inputValue`,`"$"`,`result`,`errors`).join(`
51
+ `)}
52
+
53
+ if (errors.length > 0) {
54
+ return errors;
55
+ }
56
+
57
+ return result;
58
+ }
59
+
60
+ /**
61
+ * Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
62
+ *
63
+ * @remarks
64
+ * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
65
+ *
66
+ * @param value - The input value to parse.
67
+ * @returns The parsed value conforming to the schema.
68
+ * @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
69
+ */
70
+ export function parse(inputValue) {
71
+ const result = parseSafe(inputValue);
72
+ if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
73
+ throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
74
+ }
75
+
76
+ return result;
77
+ }`}export{D as generateParserCode,S as getJsonSchemaType,x as stringifyType,b as stringifyValue};
78
+ //# sourceMappingURL=codegen.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codegen.mjs","names":[],"sources":[],"mappings":""}
@@ -0,0 +1,32 @@
1
+ //#region src/constants.d.ts
2
+ declare const VALID_SOURCE_FILE_EXTENSIONS: string[];
3
+ declare const JsonSchemaTypeNames: {
4
+ readonly STRING: "string";
5
+ readonly NUMBER: "number";
6
+ readonly INTEGER: "integer";
7
+ readonly BOOLEAN: "boolean";
8
+ readonly NULL: "null";
9
+ readonly OBJECT: "object";
10
+ readonly ARRAY: "array";
11
+ };
12
+ declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "integer", "boolean", "null"];
13
+ declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
14
+ declare const JSON_SCHEMA_METADATA_KEYS: ("title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
15
+ /**
16
+ * Keywords whose values are a flat record of named JSON Schema fragments.
17
+ * Each child schema is merged recursively with its counterpart.
18
+ */
19
+ declare const SCHEMA_RECORD_KEYWORDS: Set<string>;
20
+ /**
21
+ * Keywords whose value is a single JSON Schema fragment that should be
22
+ * recursively merged when both sides define it.
23
+ */
24
+ declare const SCHEMA_SINGLE_KEYWORDS: Set<string>;
25
+ /**
26
+ * Keywords whose values are arrays of JSON Schema fragments that should be
27
+ * concatenated (rather than overridden) during a merge.
28
+ */
29
+ declare const SCHEMA_ARRAY_CONCAT_KEYWORDS: Set<string>;
30
+ //#endregion
31
+ export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, VALID_SOURCE_FILE_EXTENSIONS as c, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
32
+ //# sourceMappingURL=constants-Cx9_Shfk.d.cts.map