@power-plant/schema 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +77 -1
- package/dist/codegen.d.cts +1 -1
- package/dist/codegen.d.mts +1 -1
- package/dist/codegen.mjs +78 -1
- package/dist/codegen.mjs.map +1 -0
- package/dist/constants-CwyhgVEl.cjs +1 -0
- package/dist/constants-lk1mMbgx.mjs +2 -0
- package/dist/constants-lk1mMbgx.mjs.map +1 -0
- package/dist/helpers-B5sr5S3X.cjs +1 -0
- package/dist/helpers-Bh_V7xwV.mjs +2 -0
- package/dist/helpers-Bh_V7xwV.mjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +616 -31
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +616 -31
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -1
- package/dist/index.mjs.map +1 -0
- package/dist/{types.d.cts → types-BawP3FVI.d.mts} +81 -180
- package/dist/types-BawP3FVI.d.mts.map +1 -0
- package/dist/{types.d.mts → types-BmNamqlM.d.cts} +80 -179
- package/dist/types-BmNamqlM.d.cts.map +1 -0
- package/dist/valibot.cjs +1 -0
- package/dist/valibot.d.cts +14 -0
- package/dist/valibot.d.cts.map +1 -0
- package/dist/valibot.d.mts +14 -0
- package/dist/valibot.d.mts.map +1 -0
- package/dist/valibot.mjs +2 -0
- package/dist/valibot.mjs.map +1 -0
- package/dist/zod.cjs +1 -0
- package/dist/zod.d.cts +14 -0
- package/dist/zod.d.cts.map +1 -0
- package/dist/zod.d.mts +14 -0
- package/dist/zod.d.mts.map +1 -0
- package/dist/zod.mjs +2 -0
- package/dist/zod.mjs.map +1 -0
- package/package.json +26 -91
- package/dist/constants-u7ovYS9e.d.cts +0 -31
- package/dist/constants-u7ovYS9e.d.cts.map +0 -1
- package/dist/constants-u7ovYS9e.d.mts +0 -31
- package/dist/constants-u7ovYS9e.d.mts.map +0 -1
- package/dist/constants.cjs +0 -1
- package/dist/constants.d.cts +0 -2
- package/dist/constants.d.mts +0 -2
- package/dist/constants.mjs +0 -2
- package/dist/constants.mjs.map +0 -1
- package/dist/extract.cjs +0 -1
- package/dist/extract.d.cts +0 -143
- package/dist/extract.d.cts.map +0 -1
- package/dist/extract.d.mts +0 -143
- package/dist/extract.d.mts.map +0 -1
- package/dist/extract.mjs +0 -2
- package/dist/extract.mjs.map +0 -1
- package/dist/helpers.cjs +0 -1
- package/dist/helpers.d.cts +0 -134
- package/dist/helpers.d.cts.map +0 -1
- package/dist/helpers.d.mts +0 -134
- package/dist/helpers.d.mts.map +0 -1
- package/dist/helpers.mjs +0 -1
- package/dist/metadata-CsY3HrP2.cjs +0 -77
- package/dist/metadata-DIEpQjbq.mjs +0 -78
- package/dist/metadata-DIEpQjbq.mjs.map +0 -1
- package/dist/metadata.cjs +0 -1
- package/dist/metadata.d.cts +0 -94
- package/dist/metadata.d.cts.map +0 -1
- package/dist/metadata.d.mts +0 -94
- package/dist/metadata.d.mts.map +0 -1
- package/dist/metadata.mjs +0 -1
- package/dist/type-checks.cjs +0 -1
- package/dist/type-checks.d.cts +0 -331
- package/dist/type-checks.d.cts.map +0 -1
- package/dist/type-checks.d.mts +0 -331
- package/dist/type-checks.d.mts.map +0 -1
- package/dist/type-checks.mjs +0 -2
- package/dist/type-checks.mjs.map +0 -1
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts.map +0 -1
- package/dist/types.d.mts.map +0 -1
- package/dist/types.mjs +0 -1
package/dist/helpers.d.cts
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf, Schema } from "./types.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/helpers.d.ts
|
|
4
|
-
type GetPropertyResult = JsonSchema & {
|
|
5
|
-
name: string;
|
|
6
|
-
required: boolean;
|
|
7
|
-
default?: unknown;
|
|
8
|
-
};
|
|
9
|
-
/**
|
|
10
|
-
* Retrieves the JSON Schema from a Schema wrapper or returns the input if it's already a JSON Schema.
|
|
11
|
-
*
|
|
12
|
-
* @remarks
|
|
13
|
-
* This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
|
|
14
|
-
*
|
|
15
|
-
* @param input - The input which can be either a Schema wrapper or a JSON Schema object.
|
|
16
|
-
* @returns The JSON Schema object.
|
|
17
|
-
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
18
|
-
*/
|
|
19
|
-
declare function getJsonSchema(input: Schema | JsonSchema): JsonSchema;
|
|
20
|
-
/**
|
|
21
|
-
* Retrieves the JSON Schema in Object form from a Schema wrapper or returns the input if it's already a JSON Schema.
|
|
22
|
-
*
|
|
23
|
-
* @remarks
|
|
24
|
-
* This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema object, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
|
|
25
|
-
*
|
|
26
|
-
* @param input - The input which can be either a Schema wrapper or a JSON Schema object.
|
|
27
|
-
* @returns The JSON Schema object.
|
|
28
|
-
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
29
|
-
*/
|
|
30
|
-
declare function getJsonSchemaObject(input: Schema | JsonSchema): JsonSchemaObject;
|
|
31
|
-
/**
|
|
32
|
-
* Extracts object properties from a JSON Schema object form.
|
|
33
|
-
*
|
|
34
|
-
* @remarks
|
|
35
|
-
* This function returns an empty object if the schema is not an object form or if it has no properties.
|
|
36
|
-
*
|
|
37
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
38
|
-
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
39
|
-
*/
|
|
40
|
-
declare function getProperties(obj: Schema | JsonSchemaObject): Record<string, GetPropertyResult>;
|
|
41
|
-
/**
|
|
42
|
-
* Returns object properties as an array.
|
|
43
|
-
*
|
|
44
|
-
* @remarks
|
|
45
|
-
* This is a convenience function that extracts properties using `getProperties` and returns them as an array.
|
|
46
|
-
*
|
|
47
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
48
|
-
* @returns An array of JSON Schema fragments representing the properties, each including metadata.
|
|
49
|
-
*/
|
|
50
|
-
declare function getPropertiesList(obj: Schema | JsonSchemaObject): GetPropertyResult[];
|
|
51
|
-
/**
|
|
52
|
-
* Extracts object properties from a JSON Schema object form.
|
|
53
|
-
*
|
|
54
|
-
* @remarks
|
|
55
|
-
* This function returns an empty object if the schema is not an object form or if it has no properties.
|
|
56
|
-
*
|
|
57
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
58
|
-
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
59
|
-
*/
|
|
60
|
-
declare function getProperty<TSchema extends JsonSchemaObject>(obj: Schema<TSchema> | TSchema, name: keyof TSchema["properties"] & string): GetPropertyResult;
|
|
61
|
-
/**
|
|
62
|
-
* Adds a property to a JSON Schema object form.
|
|
63
|
-
*
|
|
64
|
-
* @remarks
|
|
65
|
-
* This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
|
|
66
|
-
*
|
|
67
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
|
|
68
|
-
* @param name - The name of the property to add.
|
|
69
|
-
* @param property - The JSON Schema fragment representing the property's schema, including metadata.
|
|
70
|
-
* @throws Will throw an error if the provided schema is not an object form.
|
|
71
|
-
*/
|
|
72
|
-
declare function addProperty(obj: Schema | JsonSchemaObject, name: string, property: JsonSchema): void;
|
|
73
|
-
/**
|
|
74
|
-
* Merges multiple JSON Schemas into one.
|
|
75
|
-
*
|
|
76
|
-
* @remarks
|
|
77
|
-
* This function takes multiple JSON Schemas or Schema wrappers and merges them
|
|
78
|
-
* into a single JSON Schema object. Later schemas in the argument list take
|
|
79
|
-
* precedence over earlier ones for scalar conflicts.
|
|
80
|
-
*
|
|
81
|
-
* Structured keywords are merged recursively:
|
|
82
|
-
* - Named child schemas (`properties`, `$defs`, etc.) are merged
|
|
83
|
-
* per-property via recursive calls to `merge`.
|
|
84
|
-
* - Composition arrays (`allOf`, `anyOf`, `oneOf`) are concatenated.
|
|
85
|
-
* - Single-schema keywords (`if`, `then`, `else`, `not`, `items`, etc.)
|
|
86
|
-
* are merged recursively when both sides define them.
|
|
87
|
-
* - `required` arrays are union'ed and deduplicated.
|
|
88
|
-
*
|
|
89
|
-
* @param schemas - An array of JSON Schemas or Schema wrappers to merge.
|
|
90
|
-
* @returns A new JSON Schema that is the result of merging all input schemas.
|
|
91
|
-
*/
|
|
92
|
-
declare function merge(...schemas: (JsonSchema | Schema)[]): JsonSchema;
|
|
93
|
-
/**
|
|
94
|
-
* Merges metadata into a JSON Schema fragment.
|
|
95
|
-
*
|
|
96
|
-
* @remarks
|
|
97
|
-
* This function takes a JSON Schema fragment and a metadata object, and merges the metadata into the schema. Only the keys defined in {@link JSON_SCHEMA_METADATA_KEYS} are considered for merging. The resulting schema will include the original schema properties along with the provided metadata.
|
|
98
|
-
*
|
|
99
|
-
* @param schema - The JSON Schema fragment to merge metadata into.
|
|
100
|
-
* @param metadata - The metadata to merge into the schema.
|
|
101
|
-
* @returns A new JSON Schema fragment that includes the merged metadata.
|
|
102
|
-
*/
|
|
103
|
-
declare function mergeMetadata<TSpec>(schema: JsonSchemaOf<TSpec>, metadata: JsonSchemaMetadataKeywords): JsonSchemaOf<TSpec>;
|
|
104
|
-
/**
|
|
105
|
-
* Returns whether a JSON Schema fragment accepts `null`.
|
|
106
|
-
*
|
|
107
|
-
* @remarks
|
|
108
|
-
* This is true if the schema has `nullable: true` or if its `type` includes `"null"`.
|
|
109
|
-
*
|
|
110
|
-
* @param schema - The JSON Schema fragment to check.
|
|
111
|
-
* @returns `true` if the schema accepts `null`, otherwise `false`.
|
|
112
|
-
*/
|
|
113
|
-
declare function isSchemaNullable(schema?: JsonSchema): boolean;
|
|
114
|
-
/**
|
|
115
|
-
* Returns whether an object property is optional (not listed in `required`).
|
|
116
|
-
*
|
|
117
|
-
* @remarks
|
|
118
|
-
* In JSON Schema, object properties are optional by default unless they are listed in the `required` array of the parent schema. This function checks whether a given property name is not included in the `required` array of its parent schema, indicating that it is optional.
|
|
119
|
-
*
|
|
120
|
-
* @param parent - The parent JSON Schema object containing the property.
|
|
121
|
-
* @param propertyName - The name of the property to check for optionality.
|
|
122
|
-
* @returns `true` if the property is optional, otherwise `false`.
|
|
123
|
-
*/
|
|
124
|
-
declare function isPropertyOptional(parent: JsonSchemaObject, propertyName: string): boolean;
|
|
125
|
-
/**
|
|
126
|
-
* Checks if a given file name has a valid schema input file extension.
|
|
127
|
-
*
|
|
128
|
-
* @param fileName - The file name to check for a valid schema input extension.
|
|
129
|
-
* @returns `true` if the file name has a valid schema input extension, otherwise `false`.
|
|
130
|
-
*/
|
|
131
|
-
declare function isValidSchemaInputFile(fileName: string): boolean;
|
|
132
|
-
//#endregion
|
|
133
|
-
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata };
|
|
134
|
-
//# sourceMappingURL=helpers.d.cts.map
|
package/dist/helpers.d.cts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;KAwCY,iBAAA,GAAoB,UAAU;EACxC,IAAA;EACA,QAAA;EACA,OAAA;AAAA;;;;;;;AAAO;AAaT;;;iBAAgB,aAAA,CAAc,KAAA,EAAO,MAAA,GAAS,UAAA,GAAa,UAAA;;;;;;;;;;AAAU;iBAmBrD,mBAAA,CACd,KAAA,EAAO,MAAA,GAAS,UAAA,GACf,gBAAA;;;;;;;;;;iBAkBa,aAAA,CACd,GAAA,EAAK,MAAA,GAAS,gBAAA,GACb,MAAA,SAAe,iBAAA;;;AApBC;AAkBnB;;;;;;iBA+BgB,iBAAA,CAAkB,GAAA,EAAK,MAAA,GAAS,gBAAA,GAAgB,iBAAA;;;;;;;;;AA7B7B;iBA0CnB,WAAA,iBAA4B,gBAAA,EAC1C,GAAA,EAAK,MAAA,CAAO,OAAA,IAAW,OAAA,EACvB,IAAA,QAAY,OAAA,0BACX,iBAAA;;;;;;;;;;;;iBAgCa,WAAA,CACd,GAAA,EAAK,MAAA,GAAS,gBAAA,EACd,IAAA,UACA,QAAA,EAAU,UAAA;AAnDoD;AAahE;;;;;;;;;;;;;;;;;;AAbgE,iBA4JhD,KAAA,IAAS,OAAA,GAAU,UAAA,GAAa,MAAA,MAAY,UAAA;;;AA5IxC;AAgCpB;;;;;;;iBAyIgB,aAAA,QACd,MAAA,EAAQ,YAAA,CAAa,KAAA,GACrB,QAAA,EAAU,0BAAA,GACT,YAAA,CAAa,KAAA;;;;;;;;AAzIM;AAyGtB;iBAoDgB,gBAAA,CAAiB,MAAmB,GAAV,UAAU;;;;;;;;;;;iBAsBpC,kBAAA,CACd,MAAA,EAAQ,gBAAgB,EACxB,YAAA;AA5EoE;AA6BtE;;;;;AA7BsE,iBA6FtD,sBAAA,CAAuB,QAAgB"}
|
package/dist/helpers.d.mts
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf, Schema } from "./types.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/helpers.d.ts
|
|
4
|
-
type GetPropertyResult = JsonSchema & {
|
|
5
|
-
name: string;
|
|
6
|
-
required: boolean;
|
|
7
|
-
default?: unknown;
|
|
8
|
-
};
|
|
9
|
-
/**
|
|
10
|
-
* Retrieves the JSON Schema from a Schema wrapper or returns the input if it's already a JSON Schema.
|
|
11
|
-
*
|
|
12
|
-
* @remarks
|
|
13
|
-
* This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
|
|
14
|
-
*
|
|
15
|
-
* @param input - The input which can be either a Schema wrapper or a JSON Schema object.
|
|
16
|
-
* @returns The JSON Schema object.
|
|
17
|
-
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
18
|
-
*/
|
|
19
|
-
declare function getJsonSchema(input: Schema | JsonSchema): JsonSchema;
|
|
20
|
-
/**
|
|
21
|
-
* Retrieves the JSON Schema in Object form from a Schema wrapper or returns the input if it's already a JSON Schema.
|
|
22
|
-
*
|
|
23
|
-
* @remarks
|
|
24
|
-
* This function checks if the input is a Schema wrapper (an object with a `schema` property) and returns the `schema` if it is. If the input is already a JSON Schema object, it returns it directly. This allows for flexibility in handling both raw JSON Schema objects and wrapped schemas without needing to check the type at every usage point.
|
|
25
|
-
*
|
|
26
|
-
* @param input - The input which can be either a Schema wrapper or a JSON Schema object.
|
|
27
|
-
* @returns The JSON Schema object.
|
|
28
|
-
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
29
|
-
*/
|
|
30
|
-
declare function getJsonSchemaObject(input: Schema | JsonSchema): JsonSchemaObject;
|
|
31
|
-
/**
|
|
32
|
-
* Extracts object properties from a JSON Schema object form.
|
|
33
|
-
*
|
|
34
|
-
* @remarks
|
|
35
|
-
* This function returns an empty object if the schema is not an object form or if it has no properties.
|
|
36
|
-
*
|
|
37
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
38
|
-
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
39
|
-
*/
|
|
40
|
-
declare function getProperties(obj: Schema | JsonSchemaObject): Record<string, GetPropertyResult>;
|
|
41
|
-
/**
|
|
42
|
-
* Returns object properties as an array.
|
|
43
|
-
*
|
|
44
|
-
* @remarks
|
|
45
|
-
* This is a convenience function that extracts properties using `getProperties` and returns them as an array.
|
|
46
|
-
*
|
|
47
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
48
|
-
* @returns An array of JSON Schema fragments representing the properties, each including metadata.
|
|
49
|
-
*/
|
|
50
|
-
declare function getPropertiesList(obj: Schema | JsonSchemaObject): GetPropertyResult[];
|
|
51
|
-
/**
|
|
52
|
-
* Extracts object properties from a JSON Schema object form.
|
|
53
|
-
*
|
|
54
|
-
* @remarks
|
|
55
|
-
* This function returns an empty object if the schema is not an object form or if it has no properties.
|
|
56
|
-
*
|
|
57
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
58
|
-
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
59
|
-
*/
|
|
60
|
-
declare function getProperty<TSchema extends JsonSchemaObject>(obj: Schema<TSchema> | TSchema, name: keyof TSchema["properties"] & string): GetPropertyResult;
|
|
61
|
-
/**
|
|
62
|
-
* Adds a property to a JSON Schema object form.
|
|
63
|
-
*
|
|
64
|
-
* @remarks
|
|
65
|
-
* This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
|
|
66
|
-
*
|
|
67
|
-
* @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
|
|
68
|
-
* @param name - The name of the property to add.
|
|
69
|
-
* @param property - The JSON Schema fragment representing the property's schema, including metadata.
|
|
70
|
-
* @throws Will throw an error if the provided schema is not an object form.
|
|
71
|
-
*/
|
|
72
|
-
declare function addProperty(obj: Schema | JsonSchemaObject, name: string, property: JsonSchema): void;
|
|
73
|
-
/**
|
|
74
|
-
* Merges multiple JSON Schemas into one.
|
|
75
|
-
*
|
|
76
|
-
* @remarks
|
|
77
|
-
* This function takes multiple JSON Schemas or Schema wrappers and merges them
|
|
78
|
-
* into a single JSON Schema object. Later schemas in the argument list take
|
|
79
|
-
* precedence over earlier ones for scalar conflicts.
|
|
80
|
-
*
|
|
81
|
-
* Structured keywords are merged recursively:
|
|
82
|
-
* - Named child schemas (`properties`, `$defs`, etc.) are merged
|
|
83
|
-
* per-property via recursive calls to `merge`.
|
|
84
|
-
* - Composition arrays (`allOf`, `anyOf`, `oneOf`) are concatenated.
|
|
85
|
-
* - Single-schema keywords (`if`, `then`, `else`, `not`, `items`, etc.)
|
|
86
|
-
* are merged recursively when both sides define them.
|
|
87
|
-
* - `required` arrays are union'ed and deduplicated.
|
|
88
|
-
*
|
|
89
|
-
* @param schemas - An array of JSON Schemas or Schema wrappers to merge.
|
|
90
|
-
* @returns A new JSON Schema that is the result of merging all input schemas.
|
|
91
|
-
*/
|
|
92
|
-
declare function merge(...schemas: (JsonSchema | Schema)[]): JsonSchema;
|
|
93
|
-
/**
|
|
94
|
-
* Merges metadata into a JSON Schema fragment.
|
|
95
|
-
*
|
|
96
|
-
* @remarks
|
|
97
|
-
* This function takes a JSON Schema fragment and a metadata object, and merges the metadata into the schema. Only the keys defined in {@link JSON_SCHEMA_METADATA_KEYS} are considered for merging. The resulting schema will include the original schema properties along with the provided metadata.
|
|
98
|
-
*
|
|
99
|
-
* @param schema - The JSON Schema fragment to merge metadata into.
|
|
100
|
-
* @param metadata - The metadata to merge into the schema.
|
|
101
|
-
* @returns A new JSON Schema fragment that includes the merged metadata.
|
|
102
|
-
*/
|
|
103
|
-
declare function mergeMetadata<TSpec>(schema: JsonSchemaOf<TSpec>, metadata: JsonSchemaMetadataKeywords): JsonSchemaOf<TSpec>;
|
|
104
|
-
/**
|
|
105
|
-
* Returns whether a JSON Schema fragment accepts `null`.
|
|
106
|
-
*
|
|
107
|
-
* @remarks
|
|
108
|
-
* This is true if the schema has `nullable: true` or if its `type` includes `"null"`.
|
|
109
|
-
*
|
|
110
|
-
* @param schema - The JSON Schema fragment to check.
|
|
111
|
-
* @returns `true` if the schema accepts `null`, otherwise `false`.
|
|
112
|
-
*/
|
|
113
|
-
declare function isSchemaNullable(schema?: JsonSchema): boolean;
|
|
114
|
-
/**
|
|
115
|
-
* Returns whether an object property is optional (not listed in `required`).
|
|
116
|
-
*
|
|
117
|
-
* @remarks
|
|
118
|
-
* In JSON Schema, object properties are optional by default unless they are listed in the `required` array of the parent schema. This function checks whether a given property name is not included in the `required` array of its parent schema, indicating that it is optional.
|
|
119
|
-
*
|
|
120
|
-
* @param parent - The parent JSON Schema object containing the property.
|
|
121
|
-
* @param propertyName - The name of the property to check for optionality.
|
|
122
|
-
* @returns `true` if the property is optional, otherwise `false`.
|
|
123
|
-
*/
|
|
124
|
-
declare function isPropertyOptional(parent: JsonSchemaObject, propertyName: string): boolean;
|
|
125
|
-
/**
|
|
126
|
-
* Checks if a given file name has a valid schema input file extension.
|
|
127
|
-
*
|
|
128
|
-
* @param fileName - The file name to check for a valid schema input extension.
|
|
129
|
-
* @returns `true` if the file name has a valid schema input extension, otherwise `false`.
|
|
130
|
-
*/
|
|
131
|
-
declare function isValidSchemaInputFile(fileName: string): boolean;
|
|
132
|
-
//#endregion
|
|
133
|
-
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata };
|
|
134
|
-
//# sourceMappingURL=helpers.d.mts.map
|
package/dist/helpers.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.mts","names":[],"sources":["../src/helpers.ts"],"mappings":""}
|
package/dist/helpers.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{C as e,E as t,S as n,T as r,_ as i,b as a,g as o,v as s,w as c,x as l,y as u}from"./metadata-DIEpQjbq.mjs";export{o as addProperty,i as getJsonSchema,s as getJsonSchemaObject,u as getProperties,a as getPropertiesList,l as getProperty,n as isPropertyOptional,e as isSchemaNullable,c as isValidSchemaInputFile,r as merge,t as mergeMetadata};
|
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./constants.cjs"),l=require("./type-checks.cjs");let u=require("@stryke/type-checks"),d=require("@stryke/convert/to-array"),f=require("@stryke/date/format"),p=require("@stryke/date/validate"),m=require("@stryke/helpers/get-unique"),h=require("@stryke/string-format/kebab-case"),g=require("@stryke/string-format/title-case"),_=require("@stryke/type-checks/is-date"),v=require("@stryke/type-checks/is-function"),y=require("@stryke/type-checks/is-number"),b=require("@stryke/type-checks/is-set-object"),x=require("@stryke/type-checks/is-set-string"),ee=require("@stryke/unique-id/nanoid"),te=require("@stryke/convert/to-bool"),S=require("@stryke/string-format/camel-case"),C=require("@stryke/string-format/list"),w=require("@stryke/type-checks/is-boolean"),T=require("@stryke/type-checks/is-null"),E=require("@stryke/type-checks/is-undefined"),D=require("@stryke/path/find"),ne=require("@stryke/resolve/constants"),O=require("defu");O=s(O,1);function k(e){let t=l.isSchema(e)?e.schema:e;if(!l.isJsonSchema(t))throw TypeError(`The provided input is not a valid JSON Schema`);return t}function A(e){let t=k(e);if(!l.isJsonSchemaObject(t))throw TypeError(`The provided input is not a valid JSON Schema object`);return t}function j(e){let t=A(e);return(0,u.isSetObject)(t.properties)?Object.entries(t.properties).reduce((e,[n,r])=>(r.name=n,r.required=!z(t,n),r.default=t.default?.[n]??r.default,e[n]=r,e),{}):{}}function M(e){return Object.values(j(e))}function N(e,t){let n=A(e);if(!(0,u.isSetObject)(n.properties))throw TypeError(`The provided schema does not have any properties`);let r=n.properties[t];if(!r)throw TypeError(`The provided schema does not have a property named "${t}"`);return{...r,name:t,required:!z(n,t),default:n.default?.[t]??r?.default}}function P(e,t,n){let r=A(e);r.properties??={},r.required??=[],n.name=t,r.properties[t]=n,r.required.includes(t)||r.required.push(t),r.required.length===0&&delete r.required}function F(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(e===`required`)n[e]=(0,m.getUnique)([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);else if(c.SCHEMA_RECORD_KEYWORDS.has(e)&&(0,u.isSetObject)(t)&&(0,u.isSetObject)(r)){let i={...t};for(let[e,t]of Object.entries(r)){let n=i[e];i[e]=l.isJsonSchema(n)&&l.isJsonSchema(t)?F(n,t):t}n[e]=i}else c.SCHEMA_ARRAY_CONCAT_KEYWORDS.has(e)&&Array.isArray(t)&&Array.isArray(r)?n[e]=[...t,...r]:c.SCHEMA_SINGLE_KEYWORDS.has(e)&&l.isJsonSchema(t)&&l.isJsonSchema(r)?n[e]=F(t,r):n[e]=r}return n}function I(...e){let t=e.map(e=>k(e));return t.length===0?{}:t.reduce((e,t)=>{let n=e.type,r=t.type;return n&&r&&n!==r?t:F(e,t)})}function L(e,t){return(0,O.default)(e,Object.fromEntries(c.JSON_SCHEMA_METADATA_KEYS.filter(e=>t[e]!==void 0).map(e=>[e,t[e]])))}function R(e){return(0,u.isSetObject)(e)?e.nullable===!0?!0:J(e).includes(`null`):!1}function z(e,t){if(!e.properties?.[t])throw Error(`The property "${t}" does not exist in the parent schema.`);return!(e.required??[]).includes(t)}function B(e){return ne.VALID_OBJECT_SOURCE_EXTENSIONS.includes((0,D.findFileExtensionSafe)(e))}function V(e,t){return(0,E.isUndefined)(e)?`undefined`:(0,T.isNull)(e)?`null`:t===`boolean`||(0,w.isBoolean)(e)?String((0,te.toBool)(e)):t===`number`||(0,y.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 H(e){if(!e)return`unknown`;if(typeof e==`boolean`)return e?`unknown`:`never`;if(l.isJsonSchemaObject(e)&&(0,x.isSetString)(e.name))return e.name;let t=e;if((0,x.isSetString)(t.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(t.$ref)?.[1]??t.$ref;if(l.isJsonSchemaLiteral(e)&&!(0,E.isUndefined)(e.const))return JSON.stringify((0,x.isSetString)(e.const)?e.const.replaceAll(/^['"`]|['"`]$/g,``):e.const);let n=Y(e);if(n)return n===`integer`||n===`number`?`number`:n;if(t.type===`array`&&Array.isArray(t.enum))return t.enum.map(e=>JSON.stringify(e)).join(` | `);if(t.const!==void 0)return JSON.stringify(t.const);if(t.type===`array`||t.items)return`${H(Array.isArray(t.items)?t.items[0]:t.items)}[]`;if(t.type===`object`||t.properties||t.additionalProperties){if(l.isJsonSchema(t.additionalProperties))return`{ [key: string]: ${H(t.additionalProperties)} }`;if(l.isJsonSchemaObject(t)){let e=t.required??[];return`{ ${M(t).map(t=>{let n=!e.includes(t.name)||R(t)?`${e.includes(t.name)?``:`?`}${R(t)?` | null`:``}`:``;return`${t.name}${n}: ${H(t)}`}).join(`;
|
|
2
|
-
`)} }`}}return t.oneOf||t.anyOf?(t.oneOf??t.anyOf??[]).map(e=>H(e)).join(` | `):t.allOf?`object`:`unknown`}function U(e){return(0,T.isNull)(e)?`null`:(0,w.isBoolean)(e)?`boolean`:(0,u.isInteger)(e)?`integer`:(0,y.isNumber)(e)?`number`:(0,u.isString)(e)?`string`:(0,u.isObject)(e)?`object`:Array.isArray(e)?`array`:void 0}function W(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 K(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function q(e,t){return`${e} + ${JSON.stringify(t)}`}function re(e,t={}){let n=e,r=typeof n==`boolean`?{}:{...n.definitions,...n.$defs},i={};function a(e){let t=i[e]??0;return i[e]=t+1,`${e}${t>0?`${t}`:``}`}function o(e,n,i,o,c=`errors`){if(typeof e==`boolean`)return e?[`${o} = ${n};`]:[`${c}.push({ path: ${i}, failure: "No value is allowed at this location" });`,`${o} = ${n};`];if((0,x.isSetString)(e.$ref)){let t=W(e.$ref);return t&&t in r?[`${o} = ${G(t)}(${n}, ${i}, ${c});`]:[`${o} = ${n};`]}let l=a(e.name?`${(0,S.camelCase)(e.name)}Value`:`value`),u=a(e.name?`${(0,S.camelCase)(e.name)}Path`:`path`),d=[`const ${l} = ${n};`,`const ${u} = ${i};`];return!t.ignoreDefaults&&e.default!==void 0?(d.push(`if (${l} === undefined${e.type===`string`?` || ${l} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${l})`:``}) {`,` ${o} = ${JSON.stringify(e.default)};`,`} else {`),R(e)?(d.push(` if (${l} === null) {`,` ${o} = null;`,` } else {`),d.push(...s(e,l,u,o,c)),d.push(` }`)):d.push(...s(e,l,u,o,c)),d.push(`}`),d):(d.push(`if (${l} === undefined) {`,` ${c}.push({ path: ${u}, failure: "A value is required" });`,` ${o} = ${l};`,`} else {`),R(e)?(d.push(` if (${l} === null) {`,` ${o} = null;`,` } else {`),d.push(...s(e,l,u,o,c)),d.push(` }`)):d.push(...s(e,l,u,o,c)),d.push(`}`),d)}function s(e,t,n,r,i){let s=[];if(e.const!==void 0){let a=JSON.stringify(e.const);return s.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${a}) { ${i}.push({ path: ${n}, failure: "Expected the constant value " + ${a} }); }`,`${r} = ${a};`),s}if(Array.isArray(e.enum)){let a=JSON.stringify(e.enum);return s.push(`if (!${a}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${i}.push({ path: ${n}, failure: \`Expected one of: ${(0,C.list)(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),s}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let c=e.oneOf??e.anyOf??[],l=a(e.name?`${(0,S.camelCase)(e.name)}Matched`:`matched`);s.push(`let ${l} = false;`);for(let i of c){let c=a(e.name?`${(0,S.camelCase)(e.name)}BranchErrors`:`branchErrors`),u=a(e.name?`${(0,S.camelCase)(e.name)}BranchResult`:`branchResult`);s.push(`if (!${l}) {`),s.push(` const ${c}: { path: string; failure: string }[] = [];`,` let ${u};`),s.push(...o(i,t,n,u,c)),s.push(` if (${c}.length === 0) {`,` ${r} = ${u};`,` ${l} = true;`,` }`,`}`)}return s.push(`if (!${l}) {`,` ${i}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),s}if(Array.isArray(e.allOf)){let{allOf:a,...c}=e,l=I(c,...a);return s.push(...o(l,t,n,r,i)),s}let l=K(e);switch(Y(e)??l.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:s.push(...c(e,t,n,r,i));break;case`array`:s.push(...d(e,t,n,r,i));break;case`string`:s.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:s.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:s.push(`${r} = ${t};`);break}return s}function c(e,t,n,r,i){let s=H(e),c=[`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an object value" });`,` ${r} = ${t};`,`} else {`],d=a(s||e.name?`${(0,S.camelCase)(s||e.name)}Schema`:`schema`);if(c.push(`const ${d} = {} as Record<string, any>`),l.isJsonSchemaObject(e)){let r=new Set;for(let s of M(e)){r.add(s.name);let e;(0,u.isSetArray)(s.alias)?(e=`(${s.alias.map(e=>`${t}[${JSON.stringify(e)}]`).join(` ${l.isJsonSchemaString(s)?`||`:`??`} `)} ${l.isJsonSchemaString(s)?`||`:`??`} ${t}[${JSON.stringify(s.name)}])`,s.alias.forEach(e=>r.add(e))):e=`${t}[${JSON.stringify(s.name)}]`;let f=q(n,`.${s.name}`),p=a(s.name?`${(0,S.camelCase)(s.name)}Property`:`property`),m=s.default===void 0?s.required?`${i}.push({ path: ${f}, failure: "Required property is missing" });`:``:`${d}[${JSON.stringify(s.name)}] = ${JSON.stringify(s.default)};`;c.push(` if (${e} !== undefined) {`,` let ${p};`),c.push(...o(s,e,f,p,i)),c.push(`${d}[${JSON.stringify(s.name)}] = ${p};`),m?c.push(`} else { ${m} }`):c.push(`}`)}let f=e.additionalProperties;if(l.isJsonSchema(f)){let l=a(s||e.name?`${(0,S.camelCase)(s||e.name)}AdditionalProperties`:`additionalProperties`);c.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` let ${l};`),c.push(...o(f,`${t}[key]`,`${n} + "." + key`,l,i)),c.push(`${d}[key] = ${l};`,`}`)}else f!==!1&&c.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` ${d}[key] = ${t}[key];`,`}`)}return c.push(`${r} = ${d};`,`}`),c}function d(e,t,n,r,i){let s=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],c=a(e.name?`${(0,S.camelCase)(e.name)}Array`:`array`);s.push(`const ${c}: unknown[] = [];`);let l=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(l){let a=Array.isArray(e.items)?void 0:e.items;return s.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),l.forEach((e,t)=>{s.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),s.push(...o(e,`item`,q(n,`[${t}]`),`itemResult`,i)),s.push(`}`)}),a?(s.push(`else {`),s.push(...o(a,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),s.push(`}`)):s.push(`else { itemResult = item; }`),s.push(` ${c}.push(itemResult);`,` }`,` ${r} = ${c};`,`}`),s}let u=e.items??!0;return s.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),s.push(...o(u,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),s.push(` ${c}.push(itemResult);`,` }`,` ${r} = ${c};`,`}`),s}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(r).map(([e,t])=>`function ${G(e)}(inputValue, inputPath, errors) {
|
|
28
|
-
let result;
|
|
29
|
-
${o(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
|
-
${o(e,`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
|
-
}`}function ie(e,t){if(!t||!(0,b.isSetObject)(e))return e;let n={...e},r=n;for(let e of c.JSON_SCHEMA_METADATA_KEYS){let n=t[e];n!=null&&(r[e]=n)}return n}function J(e){if(!(0,b.isSetObject)(e))return[];let t=e;return Array.isArray(t.type)?t.type.filter(e=>(0,x.isSetString)(e)):(0,x.isSetString)(t.type)&&t.type!==`object`&&t.type!==`array`?[t.type]:[]}function Y(e){if((0,b.isSetObject)(e))return J(e).find(e=>e!==`null`)}function X(e){return(0,_.isDate)(e)?(0,f.formatYYYYMMDD)(e):(0,y.isNumber)(e)?(0,p.isValidTimestamp)(e)&&e>1e9?(0,f.formatYYYYMMDD)(new Date(e)):e.toString():(0,x.isSetString)(e)?e:`1.0`}function Z(e,t,n){let r=n??t?.version??e?.version;return(0,v.isFunction)(r)?async e=>X(await Promise.resolve(r(e))):X(r)}function Q(e,t,n){return n??t.name??((0,x.isSetString)(e?.name)?e.name:(0,x.isSetString)(e?.displayName)?e.displayName:e.$id?(0,h.kebabCase)(e.$id):H(e))}function ae(e,t){let n=Q(e,t),r=Z(e,t);return n?(0,v.isFunction)(n)?(0,v.isFunction)(r)?async e=>`${(0,h.kebabCase)(await Promise.resolve(n(e)))}@${await Promise.resolve(r(e))}`:async e=>`${(0,h.kebabCase)(await Promise.resolve(n(e)))}@${r}`:(0,v.isFunction)(r)?async e=>`${(0,h.kebabCase)(n)}@${await Promise.resolve(r(e))}`:`${(0,h.kebabCase)(n)}@${r}`:(0,ee.nanoid)()}function $(e,t,n){let r=n??t.displayName??e?.displayName;if(r!==void 0)return r;let i=t.name;return(0,v.isFunction)(i)?async e=>(0,g.titleCase)(await Promise.resolve(i(e))):(0,g.titleCase)(i??H(e))}function oe(e,t,n,r){n.displayName??=$(t,n);let i=(0,v.isFunction)(n.displayName)?async t=>e.replaceAll(/\{\s*displayName\s*\}/g,await Promise.resolve(n.displayName(t))):e.replaceAll(/\{\s*displayName\s*\}/g,n.displayName),a=r??n.description??t?.description;return a=(0,v.isFunction)(a)?async e=>{let t=await Promise.resolve(a(e));return(0,x.isSetString)(t)?t:(0,v.isFunction)(i)?i(e):i}:(0,x.isSetString)(a)?a:i,a}function se(e,t,n){let r=e=>e.map((e,t)=>(0,x.isSetString)(e)?{description:`Example #${t+1}`,value:e}:(0,b.isSetObject)(e)&&`value`in e&&(0,x.isSetString)(e.value)?{description:e.description||`Example #${t+1}`,value:e.value}:void 0).filter(Boolean),i=n??t.examples??e?.examples??[];return(0,v.isFunction)(i)?async e=>r((0,d.toArray)(await Promise.resolve(i(e)))):r((0,d.toArray)(i))}function ce(e,t,n){return(0,v.isFunction)(n)||(0,v.isFunction)(t.links)?async r=>(0,m.getUnique)((0,d.toArray)((0,v.isFunction)(n)?await Promise.resolve(n(r)):n).concat((0,v.isFunction)(t.links)?await Promise.resolve(t.links(r)):t.links??[]).concat(e?.docs??[])):(0,m.getUnique)((0,d.toArray)(n).concat(t.links??[]).concat(e?.docs??[]))}Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return j}});
|
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import{JSON_SCHEMA_METADATA_KEYS as e,SCHEMA_ARRAY_CONCAT_KEYWORDS as t,SCHEMA_RECORD_KEYWORDS as n,SCHEMA_SINGLE_KEYWORDS as r}from"./constants.mjs";import{isJsonSchema as i,isJsonSchemaLiteral as a,isJsonSchemaObject as o,isJsonSchemaString as s,isSchema as c}from"./type-checks.mjs";import{isInteger as l,isObject as u,isSetArray as d,isSetObject as f,isString as p}from"@stryke/type-checks";import{toArray as m}from"@stryke/convert/to-array";import{formatYYYYMMDD as h}from"@stryke/date/format";import{isValidTimestamp as ee}from"@stryke/date/validate";import{getUnique as g}from"@stryke/helpers/get-unique";import{kebabCase as _}from"@stryke/string-format/kebab-case";import{titleCase as v}from"@stryke/string-format/title-case";import{isDate as te}from"@stryke/type-checks/is-date";import{isFunction as y}from"@stryke/type-checks/is-function";import{isNumber as b}from"@stryke/type-checks/is-number";import{isSetObject as x}from"@stryke/type-checks/is-set-object";import{isSetString as S}from"@stryke/type-checks/is-set-string";import{nanoid as ne}from"@stryke/unique-id/nanoid";import{toBool as re}from"@stryke/convert/to-bool";import{camelCase as C}from"@stryke/string-format/camel-case";import{list as w}from"@stryke/string-format/list";import{isBoolean as T}from"@stryke/type-checks/is-boolean";import{isNull as E}from"@stryke/type-checks/is-null";import{isUndefined as D}from"@stryke/type-checks/is-undefined";import{findFileExtensionSafe as ie}from"@stryke/path/find";import{VALID_OBJECT_SOURCE_EXTENSIONS as O}from"@stryke/resolve/constants";import k from"defu";function A(e){let t=c(e)?e.schema:e;if(!i(t))throw TypeError(`The provided input is not a valid JSON Schema`);return t}function j(e){let t=A(e);if(!o(t))throw TypeError(`The provided input is not a valid JSON Schema object`);return t}function M(e){let t=j(e);return f(t.properties)?Object.entries(t.properties).reduce((e,[n,r])=>(r.name=n,r.required=!z(t,n),r.default=t.default?.[n]??r.default,e[n]=r,e),{}):{}}function N(e){return Object.values(M(e))}function P(e,t){let n=j(e);if(!f(n.properties))throw TypeError(`The provided schema does not have any properties`);let r=n.properties[t];if(!r)throw TypeError(`The provided schema does not have a property named "${t}"`);return{...r,name:t,required:!z(n,t),default:n.default?.[t]??r?.default}}function F(e,t,n){let r=j(e);r.properties??={},r.required??=[],n.name=t,r.properties[t]=n,r.required.includes(t)||r.required.push(t),r.required.length===0&&delete r.required}function I(e,a){let o={...e};for(let[e,s]of Object.entries(a)){let a=o[e];if(e===`required`)o[e]=g([...Array.isArray(a)?a:[],...Array.isArray(s)?s:[]]);else if(n.has(e)&&f(a)&&f(s)){let t={...a};for(let[e,n]of Object.entries(s)){let r=t[e];t[e]=i(r)&&i(n)?I(r,n):n}o[e]=t}else t.has(e)&&Array.isArray(a)&&Array.isArray(s)?o[e]=[...a,...s]:r.has(e)&&i(a)&&i(s)?o[e]=I(a,s):o[e]=s}return o}function L(...e){let t=e.map(e=>A(e));return t.length===0?{}:t.reduce((e,t)=>{let n=e.type,r=t.type;return n&&r&&n!==r?t:I(e,t)})}function ae(t,n){return k(t,Object.fromEntries(e.filter(e=>n[e]!==void 0).map(e=>[e,n[e]])))}function R(e){return f(e)?e.nullable===!0?!0:J(e).includes(`null`):!1}function z(e,t){if(!e.properties?.[t])throw Error(`The property "${t}" does not exist in the parent schema.`);return!(e.required??[]).includes(t)}function B(e){return O.includes(ie(e))}function V(e,t){return D(e)?`undefined`:E(e)?`null`:t===`boolean`||T(e)?String(re(e)):t===`number`||b(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 H(e){if(!e)return`unknown`;if(typeof e==`boolean`)return e?`unknown`:`never`;if(o(e)&&S(e.name))return e.name;let t=e;if(S(t.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(t.$ref)?.[1]??t.$ref;if(a(e)&&!D(e.const))return JSON.stringify(S(e.const)?e.const.replaceAll(/^['"`]|['"`]$/g,``):e.const);let n=Y(e);if(n)return n===`integer`||n===`number`?`number`:n;if(t.type===`array`&&Array.isArray(t.enum))return t.enum.map(e=>JSON.stringify(e)).join(` | `);if(t.const!==void 0)return JSON.stringify(t.const);if(t.type===`array`||t.items)return`${H(Array.isArray(t.items)?t.items[0]:t.items)}[]`;if(t.type===`object`||t.properties||t.additionalProperties){if(i(t.additionalProperties))return`{ [key: string]: ${H(t.additionalProperties)} }`;if(o(t)){let e=t.required??[];return`{ ${N(t).map(t=>{let n=!e.includes(t.name)||R(t)?`${e.includes(t.name)?``:`?`}${R(t)?` | null`:``}`:``;return`${t.name}${n}: ${H(t)}`}).join(`;
|
|
2
|
-
`)} }`}}return t.oneOf||t.anyOf?(t.oneOf??t.anyOf??[]).map(e=>H(e)).join(` | `):t.allOf?`object`:`unknown`}function U(e){return E(e)?`null`:T(e)?`boolean`:l(e)?`integer`:b(e)?`number`:p(e)?`string`:u(e)?`object`:Array.isArray(e)?`array`:void 0}function W(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 K(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function q(e,t){return`${e} + ${JSON.stringify(t)}`}function oe(e,t={}){let n=e,r=typeof n==`boolean`?{}:{...n.definitions,...n.$defs},a={};function c(e){let t=a[e]??0;return a[e]=t+1,`${e}${t>0?`${t}`:``}`}function l(e,n,i,a,o=`errors`){if(typeof e==`boolean`)return e?[`${a} = ${n};`]:[`${o}.push({ path: ${i}, failure: "No value is allowed at this location" });`,`${a} = ${n};`];if(S(e.$ref)){let t=W(e.$ref);return t&&t in r?[`${a} = ${G(t)}(${n}, ${i}, ${o});`]:[`${a} = ${n};`]}let s=c(e.name?`${C(e.name)}Value`:`value`),l=c(e.name?`${C(e.name)}Path`:`path`),d=[`const ${s} = ${n};`,`const ${l} = ${i};`];return!t.ignoreDefaults&&e.default!==void 0?(d.push(`if (${s} === undefined${e.type===`string`?` || ${s} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${s})`:``}) {`,` ${a} = ${JSON.stringify(e.default)};`,`} else {`),R(e)?(d.push(` if (${s} === null) {`,` ${a} = null;`,` } else {`),d.push(...u(e,s,l,a,o)),d.push(` }`)):d.push(...u(e,s,l,a,o)),d.push(`}`),d):(d.push(`if (${s} === undefined) {`,` ${o}.push({ path: ${l}, failure: "A value is required" });`,` ${a} = ${s};`,`} else {`),R(e)?(d.push(` if (${s} === null) {`,` ${a} = null;`,` } else {`),d.push(...u(e,s,l,a,o)),d.push(` }`)):d.push(...u(e,s,l,a,o)),d.push(`}`),d)}function u(e,t,n,r,i){let a=[];if(e.const!==void 0){let o=JSON.stringify(e.const);return a.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${o}) { ${i}.push({ path: ${n}, failure: "Expected the constant value " + ${o} }); }`,`${r} = ${o};`),a}if(Array.isArray(e.enum)){let o=JSON.stringify(e.enum);return a.push(`if (!${o}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${i}.push({ path: ${n}, failure: \`Expected one of: ${w(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),a}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let o=e.oneOf??e.anyOf??[],s=c(e.name?`${C(e.name)}Matched`:`matched`);a.push(`let ${s} = false;`);for(let i of o){let o=c(e.name?`${C(e.name)}BranchErrors`:`branchErrors`),u=c(e.name?`${C(e.name)}BranchResult`:`branchResult`);a.push(`if (!${s}) {`),a.push(` const ${o}: { path: string; failure: string }[] = [];`,` let ${u};`),a.push(...l(i,t,n,u,o)),a.push(` if (${o}.length === 0) {`,` ${r} = ${u};`,` ${s} = true;`,` }`,`}`)}return a.push(`if (!${s}) {`,` ${i}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),a}if(Array.isArray(e.allOf)){let{allOf:o,...s}=e,c=L(s,...o);return a.push(...l(c,t,n,r,i)),a}let o=K(e);switch(Y(e)??o.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:a.push(...f(e,t,n,r,i));break;case`array`:a.push(...p(e,t,n,r,i));break;case`string`:a.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:a.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:a.push(`${r} = ${t};`);break}return a}function f(e,t,n,r,a){let u=H(e),f=[`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) {`,` ${a}.push({ path: ${n}, failure: "Expected an object value" });`,` ${r} = ${t};`,`} else {`],p=c(u||e.name?`${C(u||e.name)}Schema`:`schema`);if(f.push(`const ${p} = {} as Record<string, any>`),o(e)){let r=new Set;for(let i of N(e)){r.add(i.name);let e;d(i.alias)?(e=`(${i.alias.map(e=>`${t}[${JSON.stringify(e)}]`).join(` ${s(i)?`||`:`??`} `)} ${s(i)?`||`:`??`} ${t}[${JSON.stringify(i.name)}])`,i.alias.forEach(e=>r.add(e))):e=`${t}[${JSON.stringify(i.name)}]`;let o=q(n,`.${i.name}`),u=c(i.name?`${C(i.name)}Property`:`property`),m=i.default===void 0?i.required?`${a}.push({ path: ${o}, failure: "Required property is missing" });`:``:`${p}[${JSON.stringify(i.name)}] = ${JSON.stringify(i.default)};`;f.push(` if (${e} !== undefined) {`,` let ${u};`),f.push(...l(i,e,o,u,a)),f.push(`${p}[${JSON.stringify(i.name)}] = ${u};`),m?f.push(`} else { ${m} }`):f.push(`}`)}let o=e.additionalProperties;if(i(o)){let i=c(u||e.name?`${C(u||e.name)}AdditionalProperties`:`additionalProperties`);f.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` let ${i};`),f.push(...l(o,`${t}[key]`,`${n} + "." + key`,i,a)),f.push(`${p}[key] = ${i};`,`}`)}else o!==!1&&f.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` ${p}[key] = ${t}[key];`,`}`)}return f.push(`${r} = ${p};`,`}`),f}function p(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=c(e.name?`${C(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(...l(e,`item`,q(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),c?(a.push(`else {`),a.push(...l(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let u=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(...l(u,`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(r).map(([e,t])=>`function ${G(e)}(inputValue, inputPath, errors) {
|
|
28
|
-
let result;
|
|
29
|
-
${l(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
|
-
${l(e,`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
|
-
}`}function se(t,n){if(!n||!x(t))return t;let r={...t},i=r;for(let t of e){let e=n[t];e!=null&&(i[t]=e)}return r}function J(e){if(!x(e))return[];let t=e;return Array.isArray(t.type)?t.type.filter(e=>S(e)):S(t.type)&&t.type!==`object`&&t.type!==`array`?[t.type]:[]}function Y(e){if(x(e))return J(e).find(e=>e!==`null`)}function X(e){return te(e)?h(e):b(e)?ee(e)&&e>1e9?h(new Date(e)):e.toString():S(e)?e:`1.0`}function Z(e,t,n){let r=n??t?.version??e?.version;return y(r)?async e=>X(await Promise.resolve(r(e))):X(r)}function Q(e,t,n){return n??t.name??(S(e?.name)?e.name:S(e?.displayName)?e.displayName:e.$id?_(e.$id):H(e))}function ce(e,t){let n=Q(e,t),r=Z(e,t);return n?y(n)?y(r)?async e=>`${_(await Promise.resolve(n(e)))}@${await Promise.resolve(r(e))}`:async e=>`${_(await Promise.resolve(n(e)))}@${r}`:y(r)?async e=>`${_(n)}@${await Promise.resolve(r(e))}`:`${_(n)}@${r}`:ne()}function $(e,t,n){let r=n??t.displayName??e?.displayName;if(r!==void 0)return r;let i=t.name;return y(i)?async e=>v(await Promise.resolve(i(e))):v(i??H(e))}function le(e,t,n,r){n.displayName??=$(t,n);let i=y(n.displayName)?async t=>e.replaceAll(/\{\s*displayName\s*\}/g,await Promise.resolve(n.displayName(t))):e.replaceAll(/\{\s*displayName\s*\}/g,n.displayName),a=r??n.description??t?.description;return a=y(a)?async e=>{let t=await Promise.resolve(a(e));return S(t)?t:y(i)?i(e):i}:S(a)?a:i,a}function ue(e,t,n){let r=e=>e.map((e,t)=>S(e)?{description:`Example #${t+1}`,value:e}:x(e)&&`value`in e&&S(e.value)?{description:e.description||`Example #${t+1}`,value:e.value}:void 0).filter(Boolean),i=n??t.examples??e?.examples??[];return y(i)?async e=>r(m(await Promise.resolve(i(e)))):r(m(i))}function de(e,t,n){return y(n)||y(t.links)?async r=>g(m(y(n)?await Promise.resolve(n(r)):n).concat(y(t.links)?await Promise.resolve(t.links(r)):t.links??[]).concat(e?.docs??[])):g(m(n).concat(t.links??[]).concat(e?.docs??[]))}export{R as C,ae as E,z as S,L as T,A as _,le as a,N as b,ce as c,Z as d,oe as f,F as g,V as h,J as i,de as l,H as m,X as n,$ as o,U as p,Y as r,ue as s,se as t,Q as u,j as v,B as w,P as x,M as y};
|
|
78
|
-
//# sourceMappingURL=metadata-DIEpQjbq.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metadata-DIEpQjbq.mjs","names":[],"sources":[],"mappings":""}
|
package/dist/metadata.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs");exports.applyJsonSchemaMetadata=e.t,exports.formatMetaVersion=e.n,exports.getPrimarySchemaType=e.r,exports.readSchemaTypes=e.i,exports.resolveMetaDescription=e.a,exports.resolveMetaDisplayName=e.o,exports.resolveMetaExample=e.s,exports.resolveMetaId=e.c,exports.resolveMetaLinks=e.l,exports.resolveMetaName=e.u,exports.resolveMetaVersion=e.d;
|
package/dist/metadata.d.cts
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaPrimitiveType, Meta, MetaLink, MetaValue, SchemaMeta, SchemaMetaExample } from "./types.cjs";
|
|
2
|
-
|
|
3
|
-
//#region src/metadata.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Applies Powerlines schema metadata onto a JSON Schema fragment.
|
|
6
|
-
*
|
|
7
|
-
* @param schema - The JSON Schema fragment to apply metadata to.
|
|
8
|
-
* @param metadata - The Powerlines schema metadata to apply.
|
|
9
|
-
* @returns A new JSON Schema fragment with the metadata applied.
|
|
10
|
-
*/
|
|
11
|
-
declare function applyJsonSchemaMetadata(schema: JsonSchema, metadata: JsonSchemaMetadataKeywords | undefined): JsonSchema;
|
|
12
|
-
/**
|
|
13
|
-
* Normalizes the JSON Schema `type` keyword to a string array.
|
|
14
|
-
*
|
|
15
|
-
* @remarks
|
|
16
|
-
* This function ensures that the `type` keyword of a JSON Schema fragment is always represented as an array of strings, even if it was originally defined as a single string. This normalization simplifies type checking and processing of JSON Schemas by providing a consistent format for the `type` information.
|
|
17
|
-
*
|
|
18
|
-
* @param schema - The JSON Schema fragment to read types from.
|
|
19
|
-
* @returns An array of JSON Schema primitive type names defined in the `type` keyword, or an empty array if no valid types are found.
|
|
20
|
-
*/
|
|
21
|
-
declare function readSchemaTypes(schema?: JsonSchema): JsonSchemaPrimitiveType[];
|
|
22
|
-
/**
|
|
23
|
-
* Returns the primary non-null JSON Schema type name for a fragment.
|
|
24
|
-
*
|
|
25
|
-
* @param schema - The JSON Schema fragment to check.
|
|
26
|
-
* @returns The primary non-null JSON Schema type name, or `undefined` if none is found.
|
|
27
|
-
*/
|
|
28
|
-
declare function getPrimarySchemaType(schema?: JsonSchema): JsonSchemaPrimitiveType | undefined;
|
|
29
|
-
declare function formatMetaVersion(value: string | number | Date): string;
|
|
30
|
-
/**
|
|
31
|
-
* Extracts the version information from a given input, which can be a string, number, or Date object. The function returns a string representation of the version in the format "YYYYMMDD" for Date inputs, or as a string for valid timestamp numbers. If the input is a string, it is returned as-is. If the input is invalid or not provided, a default version of "1.0" is returned.
|
|
32
|
-
*
|
|
33
|
-
* @param input - The input from which to extract the version. It can be a string, number, undefined, or Date object.
|
|
34
|
-
* @returns A string representing the extracted version information.
|
|
35
|
-
*/
|
|
36
|
-
declare function resolveMetaVersion<TSpec>(schema: JsonSchema, meta: Partial<Meta<TSpec>>, input?: MetaValue<TSpec, string | number | Date>): MetaValue<TSpec, string>;
|
|
37
|
-
/**
|
|
38
|
-
* Resolves a metadata name using explicit input, metadata, or schema fallbacks.
|
|
39
|
-
*
|
|
40
|
-
* @param schema - The JSON Schema fragment to read fallback values from.
|
|
41
|
-
* @param meta - Metadata values that may already include a name.
|
|
42
|
-
* @param input - An explicit name value to prioritize when provided.
|
|
43
|
-
* @returns The resolved metadata name.
|
|
44
|
-
*/
|
|
45
|
-
declare function resolveMetaName<TSpec>(schema: JsonSchema, meta: Partial<Meta<TSpec>>, input?: MetaValue<TSpec, string>): MetaValue<TSpec, string>;
|
|
46
|
-
/**
|
|
47
|
-
* Resolves a stable metadata identifier in the format `<name>@<version>`.
|
|
48
|
-
*
|
|
49
|
-
* @param schema - The JSON Schema fragment used to infer fallback values.
|
|
50
|
-
* @param meta - Metadata values used to resolve name and version.
|
|
51
|
-
* @returns The resolved metadata identifier, or a generated id when no name is available.
|
|
52
|
-
*/
|
|
53
|
-
declare function resolveMetaId<TSpec>(schema: JsonSchema, meta: Partial<Meta<TSpec>>): MetaValue<TSpec, string>;
|
|
54
|
-
/**
|
|
55
|
-
* Resolves a human-readable display name for metadata.
|
|
56
|
-
*
|
|
57
|
-
* @param schema - The JSON Schema fragment to read fallback display values from.
|
|
58
|
-
* @param meta - Metadata values that may already include a display name.
|
|
59
|
-
* @param input - An explicit display name value to prioritize when provided.
|
|
60
|
-
* @returns The resolved metadata display name.
|
|
61
|
-
*/
|
|
62
|
-
declare function resolveMetaDisplayName<TSpec>(schema: JsonSchema, meta: Partial<Meta<TSpec>>, input?: MetaValue<TSpec, string>): MetaValue<TSpec, string>;
|
|
63
|
-
/**
|
|
64
|
-
* Resolves a metadata description from explicit input, metadata, or schema values.
|
|
65
|
-
*
|
|
66
|
-
* @param template - A template string used to generate a default description when no explicit description is provided.
|
|
67
|
-
* @param schema - The JSON Schema fragment to read fallback description values from.
|
|
68
|
-
* @param meta - Metadata values that may already include a description.
|
|
69
|
-
* @param input - An explicit description value to prioritize when provided.
|
|
70
|
-
* @returns The resolved description, if available.
|
|
71
|
-
*/
|
|
72
|
-
declare function resolveMetaDescription<TSpec>(template: string, schema: JsonSchema, meta: Partial<Meta<TSpec>>, input?: MetaValue<TSpec, string>): MetaValue<TSpec, string>;
|
|
73
|
-
/**
|
|
74
|
-
* Resolves and normalizes metadata examples into a consistent object format.
|
|
75
|
-
*
|
|
76
|
-
* @typeParam TSpec - The schema specification type associated with example values.
|
|
77
|
-
* @param schema - The JSON Schema fragment to read fallback examples from.
|
|
78
|
-
* @param meta - Metadata values that may already include examples.
|
|
79
|
-
* @param input - Explicit examples to prioritize when provided.
|
|
80
|
-
* @returns A normalized list of examples with generated descriptions when needed.
|
|
81
|
-
*/
|
|
82
|
-
declare function resolveMetaExample<TSpec>(schema: JsonSchema, meta: Partial<SchemaMeta<TSpec>>, input?: SchemaMetaExample<TSpec> | MetaValue<TSpec, SchemaMetaExample<TSpec>[]>): MetaValue<TSpec, SchemaMetaExample<TSpec>[]>;
|
|
83
|
-
/**
|
|
84
|
-
* Resolves and de-duplicates metadata links from input, metadata, and schema docs.
|
|
85
|
-
*
|
|
86
|
-
* @param schema - The JSON Schema fragment to read fallback documentation links from.
|
|
87
|
-
* @param meta - Metadata values that may already include links.
|
|
88
|
-
* @param input - Explicit links to prioritize when provided.
|
|
89
|
-
* @returns A unique list of metadata links.
|
|
90
|
-
*/
|
|
91
|
-
declare function resolveMetaLinks<TSpec>(schema: JsonSchema, meta: Partial<Meta<TSpec>>, input?: MetaValue<TSpec, MetaLink[]>): MetaValue<TSpec, MetaLink[]>;
|
|
92
|
-
//#endregion
|
|
93
|
-
export { applyJsonSchemaMetadata, formatMetaVersion, getPrimarySchemaType, readSchemaTypes, resolveMetaDescription, resolveMetaDisplayName, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaVersion };
|
|
94
|
-
//# sourceMappingURL=metadata.d.cts.map
|
package/dist/metadata.d.cts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.d.cts","names":[],"sources":["../src/metadata.ts"],"mappings":";;;;;AAuDA;;;;;iBAAgB,uBAAA,CACd,MAAA,EAAQ,UAAA,EACR,QAAA,EAAU,0BAAA,eACT,UAAA;;;;;;;;;AAAU;iBA0BG,eAAA,CACd,MAAA,GAAS,UAAA,GACR,uBAAuB;;;;;;;iBA6BV,oBAAA,CACd,MAAA,GAAS,UAAA,GACR,uBAAuB;AAAA,iBAQV,iBAAA,CAAkB,KAA6B,oBAAJ,IAAI;AAV/D;;;;;;AAAA,iBA4BgB,kBAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,IACnB,KAAA,GAAQ,SAAA,CAAU,KAAA,oBAAyB,IAAA,IAC1C,SAAA,CAAU,KAAA;;AA9Ba;AAQ1B;;;;AAA+D;AAkB/D;iBAsBgB,eAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,IACnB,KAAA,GAAQ,SAAA,CAAU,KAAA,YACjB,SAAA,CAAU,KAAA;;;;;;;;iBAqBG,aAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,KAClB,SAAA,CAAU,KAAA;;;;;;;;;iBA0BG,sBAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,IACnB,KAAA,GAAQ,SAAA,CAAU,KAAA,YACjB,SAAA,CAAU,KAAA;;;;;;;;;;iBAyBG,sBAAA,QACd,QAAA,UACA,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,IACnB,KAAA,GAAQ,SAAA,CAAU,KAAA,YACjB,SAAA,CAAU,KAAA;AAxFb;;;;;;;;;AAAA,iBAsIgB,kBAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,UAAA,CAAW,KAAA,IACzB,KAAA,GACI,iBAAA,CAAkB,KAAA,IAClB,SAAA,CAAU,KAAA,EAAO,iBAAA,CAAkB,KAAA,OACtC,SAAA,CAAU,KAAA,EAAO,iBAAA,CAAkB,KAAA;;;;;;;;;iBAoCtB,gBAAA,QACd,MAAA,EAAQ,UAAA,EACR,IAAA,EAAM,OAAA,CAAQ,IAAA,CAAK,KAAA,IACnB,KAAA,GAAQ,SAAA,CAAU,KAAA,EAAO,QAAA,MACxB,SAAA,CAAU,KAAA,EAAO,QAAA"}
|