@powerlines/schema 0.11.22 → 0.11.24
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/bundle.mjs.map +1 -1
- package/dist/codegen.cjs +44 -1
- package/dist/codegen.d.cts +19 -1
- package/dist/codegen.d.cts.map +1 -1
- package/dist/codegen.d.mts +19 -1
- package/dist/codegen.d.mts.map +1 -1
- package/dist/codegen.mjs +42 -1
- package/dist/codegen.mjs.map +1 -1
- package/dist/constants.cjs +19 -0
- package/dist/constants.d.cts +17 -0
- package/dist/constants.d.cts.map +1 -0
- package/dist/constants.d.mts +17 -0
- package/dist/constants.d.mts.map +1 -0
- package/dist/constants.mjs +18 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/extract.cjs +23 -4
- package/dist/extract.d.cts.map +1 -1
- package/dist/extract.d.mts.map +1 -1
- package/dist/extract.mjs +23 -4
- package/dist/extract.mjs.map +1 -1
- package/dist/helpers.cjs +54 -0
- package/dist/helpers.d.cts +26 -0
- package/dist/helpers.d.cts.map +1 -0
- package/dist/helpers.d.mts +26 -0
- package/dist/helpers.d.mts.map +1 -0
- package/dist/helpers.mjs +52 -0
- package/dist/helpers.mjs.map +1 -0
- package/dist/index.cjs +17 -2
- package/dist/index.d.cts +7 -4
- package/dist/index.d.mts +7 -4
- package/dist/index.mjs +6 -3
- package/dist/jtd.mjs.map +1 -1
- package/dist/persistence.cjs +76 -0
- package/dist/persistence.d.cts +47 -0
- package/dist/persistence.d.cts.map +1 -0
- package/dist/persistence.d.mts +47 -0
- package/dist/persistence.d.mts.map +1 -0
- package/dist/persistence.mjs +71 -0
- package/dist/persistence.mjs.map +1 -0
- package/dist/reflection.cjs +13 -6
- package/dist/reflection.d.cts.map +1 -1
- package/dist/reflection.d.mts.map +1 -1
- package/dist/reflection.mjs +12 -6
- package/dist/reflection.mjs.map +1 -1
- package/dist/resolve.mjs.map +1 -1
- package/dist/type-checks.cjs +21 -2
- package/dist/type-checks.d.cts +16 -2
- package/dist/type-checks.d.cts.map +1 -1
- package/dist/type-checks.d.mts +16 -2
- package/dist/type-checks.d.mts.map +1 -1
- package/dist/type-checks.mjs +21 -4
- package/dist/type-checks.mjs.map +1 -1
- package/dist/types.d.cts +42 -12
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +42 -12
- package/dist/types.d.mts.map +1 -1
- package/package.json +19 -7
package/dist/helpers.cjs
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_type_checks = require('./type-checks.cjs');
|
|
4
|
+
let defu = require("defu");
|
|
5
|
+
let _stryke_type_checks = require("@stryke/type-checks");
|
|
6
|
+
|
|
7
|
+
//#region src/helpers.ts
|
|
8
|
+
/**
|
|
9
|
+
* A helper function to extract the properties from a JTD object schema. This function takes an {@link ObjectSchema} as input and returns a record of its properties, where each key is the property name and the value is the corresponding JTD schema type along with an `optional` flag indicating whether the property is optional (i.e., defined in `optionalProperties`) or required (i.e., defined in `properties`). The function checks both `properties` and `optionalProperties` of the JTD schema to construct the resulting record.
|
|
10
|
+
*
|
|
11
|
+
* @param obj - The {@link ObjectSchema} from which to extract the properties.
|
|
12
|
+
* @returns A record of the properties defined in the JTD object schema, where each key is the property name and the value is an object containing the JTD schema type and an `optional` flag.
|
|
13
|
+
*/
|
|
14
|
+
function getProperties(obj) {
|
|
15
|
+
const properties = {};
|
|
16
|
+
const schema = require_type_checks.isObjectSchema(obj) ? obj.schema : obj;
|
|
17
|
+
if ("optionalProperties" in schema && (0, _stryke_type_checks.isSetObject)(schema.optionalProperties)) for (const [key, value] of Object.entries(schema.optionalProperties)) properties[key] = {
|
|
18
|
+
...value,
|
|
19
|
+
name: key,
|
|
20
|
+
optional: true
|
|
21
|
+
};
|
|
22
|
+
if ("properties" in schema && (0, _stryke_type_checks.isSetObject)(schema.properties)) for (const [key, value] of Object.entries(schema.properties)) properties[key] = {
|
|
23
|
+
...value,
|
|
24
|
+
name: key,
|
|
25
|
+
optional: false
|
|
26
|
+
};
|
|
27
|
+
return properties;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Merges multiple JTD object schemas into a single schema. This function takes an array of JTD object schemas (either {@link JTDSchemaObjectType} or {@link ObjectSchema}) and combines their properties into a single JTD object schema. The resulting schema will contain all properties from the input schemas, with optional properties marked accordingly. If there are overlapping properties between the input schemas, the function will merge them using a deep merge strategy (via `defu`) if they are both JTD object schemas; otherwise, the property from the first schema in the input array will take precedence.
|
|
31
|
+
*
|
|
32
|
+
* @remarks
|
|
33
|
+
* This function attempts to mimic {@link defu}'s behavior for merging objects, but with special handling for JTD schemas. When merging properties, if a property exists in multiple input schemas and is defined as a JTD object schema in all of them, the function will perform a deep merge of those schemas. If the property is not a JTD object schema in any of the input schemas, the function will simply take the first definition it encounters.
|
|
34
|
+
*
|
|
35
|
+
* @param schemas - An array of JTD object schemas to merge.
|
|
36
|
+
* @returns A single JTD object schema that combines the properties of all input schemas.
|
|
37
|
+
*/
|
|
38
|
+
function mergeSchemas(...schemas) {
|
|
39
|
+
const mergedSchema = {
|
|
40
|
+
properties: {},
|
|
41
|
+
optionalProperties: {},
|
|
42
|
+
additionalProperties: false
|
|
43
|
+
};
|
|
44
|
+
for (const schema of schemas.reverse()) {
|
|
45
|
+
const properties = getProperties(schema);
|
|
46
|
+
for (const [key, value] of Object.entries(properties)) if (value.optional) mergedSchema.optionalProperties[key] = mergedSchema.optionalProperties[key] && require_type_checks.isJTDSchemaObject(mergedSchema.optionalProperties[key]) && require_type_checks.isJTDSchemaObject(value) ? (0, defu.defu)(mergedSchema.optionalProperties[key], value) : value;
|
|
47
|
+
else mergedSchema.properties[key] = mergedSchema.properties[key] && require_type_checks.isJTDSchemaObject(mergedSchema.properties[key]) && require_type_checks.isJTDSchemaObject(value) ? (0, defu.defu)(mergedSchema.properties[key], value) : value;
|
|
48
|
+
}
|
|
49
|
+
return mergedSchema;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
exports.getProperties = getProperties;
|
|
54
|
+
exports.mergeSchemas = mergeSchemas;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { JTDSchemaObjectType, JTDSchemaType, ObjectSchema, SchemaMetadata } from "./types.cjs";
|
|
2
|
+
|
|
3
|
+
//#region src/helpers.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A helper function to extract the properties from a JTD object schema. This function takes an {@link ObjectSchema} as input and returns a record of its properties, where each key is the property name and the value is the corresponding JTD schema type along with an `optional` flag indicating whether the property is optional (i.e., defined in `optionalProperties`) or required (i.e., defined in `properties`). The function checks both `properties` and `optionalProperties` of the JTD schema to construct the resulting record.
|
|
6
|
+
*
|
|
7
|
+
* @param obj - The {@link ObjectSchema} from which to extract the properties.
|
|
8
|
+
* @returns A record of the properties defined in the JTD object schema, where each key is the property name and the value is an object containing the JTD schema type and an `optional` flag.
|
|
9
|
+
*/
|
|
10
|
+
declare function getProperties<TMetadata extends SchemaMetadata>(obj: ObjectSchema<TMetadata> | JTDSchemaObjectType<TMetadata>): Record<string, JTDSchemaType<TMetadata> & {
|
|
11
|
+
name: string;
|
|
12
|
+
optional: boolean;
|
|
13
|
+
}>;
|
|
14
|
+
/**
|
|
15
|
+
* Merges multiple JTD object schemas into a single schema. This function takes an array of JTD object schemas (either {@link JTDSchemaObjectType} or {@link ObjectSchema}) and combines their properties into a single JTD object schema. The resulting schema will contain all properties from the input schemas, with optional properties marked accordingly. If there are overlapping properties between the input schemas, the function will merge them using a deep merge strategy (via `defu`) if they are both JTD object schemas; otherwise, the property from the first schema in the input array will take precedence.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* This function attempts to mimic {@link defu}'s behavior for merging objects, but with special handling for JTD schemas. When merging properties, if a property exists in multiple input schemas and is defined as a JTD object schema in all of them, the function will perform a deep merge of those schemas. If the property is not a JTD object schema in any of the input schemas, the function will simply take the first definition it encounters.
|
|
19
|
+
*
|
|
20
|
+
* @param schemas - An array of JTD object schemas to merge.
|
|
21
|
+
* @returns A single JTD object schema that combines the properties of all input schemas.
|
|
22
|
+
*/
|
|
23
|
+
declare function mergeSchemas<TMetadata extends SchemaMetadata>(...schemas: (JTDSchemaObjectType<TMetadata> | ObjectSchema<TMetadata>)[]): JTDSchemaObjectType<TMetadata>;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { getProperties, mergeSchemas };
|
|
26
|
+
//# sourceMappingURL=helpers.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;;;AAkCA;;;;iBAAgB,aAAA,mBAAgC,cAAA,CAAA,CAC9C,GAAA,EAAK,YAAA,CAAa,SAAA,IAAa,mBAAA,CAAoB,SAAA,IAClD,MAAA,SAED,aAAA,CAAc,SAAA;EAAe,IAAA;EAAc,QAAA;AAAA;;;;;;;;;;iBAmC7B,YAAA,mBAA+B,cAAA,CAAA,CAAA,GAC1C,OAAA,GAAU,mBAAA,CAAoB,SAAA,IAAa,YAAA,CAAa,SAAA,OAC1D,mBAAA,CAAoB,SAAA"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { JTDSchemaObjectType, JTDSchemaType, ObjectSchema, SchemaMetadata } from "./types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/helpers.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* A helper function to extract the properties from a JTD object schema. This function takes an {@link ObjectSchema} as input and returns a record of its properties, where each key is the property name and the value is the corresponding JTD schema type along with an `optional` flag indicating whether the property is optional (i.e., defined in `optionalProperties`) or required (i.e., defined in `properties`). The function checks both `properties` and `optionalProperties` of the JTD schema to construct the resulting record.
|
|
6
|
+
*
|
|
7
|
+
* @param obj - The {@link ObjectSchema} from which to extract the properties.
|
|
8
|
+
* @returns A record of the properties defined in the JTD object schema, where each key is the property name and the value is an object containing the JTD schema type and an `optional` flag.
|
|
9
|
+
*/
|
|
10
|
+
declare function getProperties<TMetadata extends SchemaMetadata>(obj: ObjectSchema<TMetadata> | JTDSchemaObjectType<TMetadata>): Record<string, JTDSchemaType<TMetadata> & {
|
|
11
|
+
name: string;
|
|
12
|
+
optional: boolean;
|
|
13
|
+
}>;
|
|
14
|
+
/**
|
|
15
|
+
* Merges multiple JTD object schemas into a single schema. This function takes an array of JTD object schemas (either {@link JTDSchemaObjectType} or {@link ObjectSchema}) and combines their properties into a single JTD object schema. The resulting schema will contain all properties from the input schemas, with optional properties marked accordingly. If there are overlapping properties between the input schemas, the function will merge them using a deep merge strategy (via `defu`) if they are both JTD object schemas; otherwise, the property from the first schema in the input array will take precedence.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* This function attempts to mimic {@link defu}'s behavior for merging objects, but with special handling for JTD schemas. When merging properties, if a property exists in multiple input schemas and is defined as a JTD object schema in all of them, the function will perform a deep merge of those schemas. If the property is not a JTD object schema in any of the input schemas, the function will simply take the first definition it encounters.
|
|
19
|
+
*
|
|
20
|
+
* @param schemas - An array of JTD object schemas to merge.
|
|
21
|
+
* @returns A single JTD object schema that combines the properties of all input schemas.
|
|
22
|
+
*/
|
|
23
|
+
declare function mergeSchemas<TMetadata extends SchemaMetadata>(...schemas: (JTDSchemaObjectType<TMetadata> | ObjectSchema<TMetadata>)[]): JTDSchemaObjectType<TMetadata>;
|
|
24
|
+
//#endregion
|
|
25
|
+
export { getProperties, mergeSchemas };
|
|
26
|
+
//# sourceMappingURL=helpers.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.mts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;;;AAkCA;;;;iBAAgB,aAAA,mBAAgC,cAAA,CAAA,CAC9C,GAAA,EAAK,YAAA,CAAa,SAAA,IAAa,mBAAA,CAAoB,SAAA,IAClD,MAAA,SAED,aAAA,CAAc,SAAA;EAAe,IAAA;EAAc,QAAA;AAAA;;;;;;;;;;iBAmC7B,YAAA,mBAA+B,cAAA,CAAA,CAAA,GAC1C,OAAA,GAAU,mBAAA,CAAoB,SAAA,IAAa,YAAA,CAAa,SAAA,OAC1D,mBAAA,CAAoB,SAAA"}
|
package/dist/helpers.mjs
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { isJTDSchemaObject, isObjectSchema } from "./type-checks.mjs";
|
|
2
|
+
import { defu as defu$1 } from "defu";
|
|
3
|
+
import { isSetObject } from "@stryke/type-checks";
|
|
4
|
+
|
|
5
|
+
//#region src/helpers.ts
|
|
6
|
+
/**
|
|
7
|
+
* A helper function to extract the properties from a JTD object schema. This function takes an {@link ObjectSchema} as input and returns a record of its properties, where each key is the property name and the value is the corresponding JTD schema type along with an `optional` flag indicating whether the property is optional (i.e., defined in `optionalProperties`) or required (i.e., defined in `properties`). The function checks both `properties` and `optionalProperties` of the JTD schema to construct the resulting record.
|
|
8
|
+
*
|
|
9
|
+
* @param obj - The {@link ObjectSchema} from which to extract the properties.
|
|
10
|
+
* @returns A record of the properties defined in the JTD object schema, where each key is the property name and the value is an object containing the JTD schema type and an `optional` flag.
|
|
11
|
+
*/
|
|
12
|
+
function getProperties(obj) {
|
|
13
|
+
const properties = {};
|
|
14
|
+
const schema = isObjectSchema(obj) ? obj.schema : obj;
|
|
15
|
+
if ("optionalProperties" in schema && isSetObject(schema.optionalProperties)) for (const [key, value] of Object.entries(schema.optionalProperties)) properties[key] = {
|
|
16
|
+
...value,
|
|
17
|
+
name: key,
|
|
18
|
+
optional: true
|
|
19
|
+
};
|
|
20
|
+
if ("properties" in schema && isSetObject(schema.properties)) for (const [key, value] of Object.entries(schema.properties)) properties[key] = {
|
|
21
|
+
...value,
|
|
22
|
+
name: key,
|
|
23
|
+
optional: false
|
|
24
|
+
};
|
|
25
|
+
return properties;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Merges multiple JTD object schemas into a single schema. This function takes an array of JTD object schemas (either {@link JTDSchemaObjectType} or {@link ObjectSchema}) and combines their properties into a single JTD object schema. The resulting schema will contain all properties from the input schemas, with optional properties marked accordingly. If there are overlapping properties between the input schemas, the function will merge them using a deep merge strategy (via `defu`) if they are both JTD object schemas; otherwise, the property from the first schema in the input array will take precedence.
|
|
29
|
+
*
|
|
30
|
+
* @remarks
|
|
31
|
+
* This function attempts to mimic {@link defu}'s behavior for merging objects, but with special handling for JTD schemas. When merging properties, if a property exists in multiple input schemas and is defined as a JTD object schema in all of them, the function will perform a deep merge of those schemas. If the property is not a JTD object schema in any of the input schemas, the function will simply take the first definition it encounters.
|
|
32
|
+
*
|
|
33
|
+
* @param schemas - An array of JTD object schemas to merge.
|
|
34
|
+
* @returns A single JTD object schema that combines the properties of all input schemas.
|
|
35
|
+
*/
|
|
36
|
+
function mergeSchemas(...schemas) {
|
|
37
|
+
const mergedSchema = {
|
|
38
|
+
properties: {},
|
|
39
|
+
optionalProperties: {},
|
|
40
|
+
additionalProperties: false
|
|
41
|
+
};
|
|
42
|
+
for (const schema of schemas.reverse()) {
|
|
43
|
+
const properties = getProperties(schema);
|
|
44
|
+
for (const [key, value] of Object.entries(properties)) if (value.optional) mergedSchema.optionalProperties[key] = mergedSchema.optionalProperties[key] && isJTDSchemaObject(mergedSchema.optionalProperties[key]) && isJTDSchemaObject(value) ? defu$1(mergedSchema.optionalProperties[key], value) : value;
|
|
45
|
+
else mergedSchema.properties[key] = mergedSchema.properties[key] && isJTDSchemaObject(mergedSchema.properties[key]) && isJTDSchemaObject(value) ? defu$1(mergedSchema.properties[key], value) : value;
|
|
46
|
+
}
|
|
47
|
+
return mergedSchema;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
//#endregion
|
|
51
|
+
export { getProperties, mergeSchemas };
|
|
52
|
+
//# sourceMappingURL=helpers.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.mjs","names":["defu"],"sources":["../src/helpers.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { isSetObject } from \"@stryke/type-checks\";\nimport { defu } from \"defu\";\nimport { isJTDSchemaObject, isObjectSchema } from \"./type-checks\";\nimport {\n JTDSchemaObjectType,\n JTDSchemaType,\n ObjectSchema,\n SchemaMetadata\n} from \"./types\";\n\n/**\n * A helper function to extract the properties from a JTD object schema. This function takes an {@link ObjectSchema} as input and returns a record of its properties, where each key is the property name and the value is the corresponding JTD schema type along with an `optional` flag indicating whether the property is optional (i.e., defined in `optionalProperties`) or required (i.e., defined in `properties`). The function checks both `properties` and `optionalProperties` of the JTD schema to construct the resulting record.\n *\n * @param obj - The {@link ObjectSchema} from which to extract the properties.\n * @returns A record of the properties defined in the JTD object schema, where each key is the property name and the value is an object containing the JTD schema type and an `optional` flag.\n */\nexport function getProperties<TMetadata extends SchemaMetadata>(\n obj: ObjectSchema<TMetadata> | JTDSchemaObjectType<TMetadata>\n): Record<\n string,\n JTDSchemaType<TMetadata> & { name: string; optional: boolean }\n> {\n const properties: Record<\n string,\n JTDSchemaType<TMetadata> & { name: string; optional: boolean }\n > = {};\n\n const schema = isObjectSchema(obj) ? obj.schema : obj;\n if (\n \"optionalProperties\" in schema &&\n isSetObject(schema.optionalProperties)\n ) {\n for (const [key, value] of Object.entries(schema.optionalProperties)) {\n properties[key] = { ...value, name: key, optional: true };\n }\n }\n\n if (\"properties\" in schema && isSetObject(schema.properties)) {\n for (const [key, value] of Object.entries(schema.properties)) {\n properties[key] = { ...value, name: key, optional: false };\n }\n }\n\n return properties;\n}\n\n/**\n * Merges multiple JTD object schemas into a single schema. This function takes an array of JTD object schemas (either {@link JTDSchemaObjectType} or {@link ObjectSchema}) and combines their properties into a single JTD object schema. The resulting schema will contain all properties from the input schemas, with optional properties marked accordingly. If there are overlapping properties between the input schemas, the function will merge them using a deep merge strategy (via `defu`) if they are both JTD object schemas; otherwise, the property from the first schema in the input array will take precedence.\n *\n * @remarks\n * This function attempts to mimic {@link defu}'s behavior for merging objects, but with special handling for JTD schemas. When merging properties, if a property exists in multiple input schemas and is defined as a JTD object schema in all of them, the function will perform a deep merge of those schemas. If the property is not a JTD object schema in any of the input schemas, the function will simply take the first definition it encounters.\n *\n * @param schemas - An array of JTD object schemas to merge.\n * @returns A single JTD object schema that combines the properties of all input schemas.\n */\nexport function mergeSchemas<TMetadata extends SchemaMetadata>(\n ...schemas: (JTDSchemaObjectType<TMetadata> | ObjectSchema<TMetadata>)[]\n): JTDSchemaObjectType<TMetadata> {\n const mergedSchema = {\n properties: {},\n optionalProperties: {},\n additionalProperties: false\n } as JTDSchemaObjectType<TMetadata>;\n for (const schema of schemas.reverse()) {\n const properties = getProperties(schema);\n for (const [key, value] of Object.entries(properties)) {\n if (value.optional) {\n mergedSchema.optionalProperties![key] = (\n mergedSchema.optionalProperties![key] &&\n isJTDSchemaObject(mergedSchema.optionalProperties![key]) &&\n isJTDSchemaObject(value)\n ? defu(mergedSchema.optionalProperties![key], value)\n : value\n ) as JTDSchemaType<TMetadata>;\n } else {\n mergedSchema.properties![key] = (\n mergedSchema.properties![key] &&\n isJTDSchemaObject(mergedSchema.properties![key]) &&\n isJTDSchemaObject(value)\n ? defu(mergedSchema.properties![key], value)\n : value\n ) as JTDSchemaType<TMetadata>;\n }\n }\n }\n\n return mergedSchema;\n}\n"],"mappings":";;;;;;;;;;;AAkCA,SAAgB,cACd,KAIA;CACA,MAAM,aAGF,CAAC;CAEL,MAAM,SAAS,eAAe,GAAG,IAAI,IAAI,SAAS;CAClD,IACE,wBAAwB,UACxB,YAAY,OAAO,kBAAkB,GAErC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,kBAAkB,GACjE,WAAW,OAAO;EAAE,GAAG;EAAO,MAAM;EAAK,UAAU;CAAK;CAI5D,IAAI,gBAAgB,UAAU,YAAY,OAAO,UAAU,GACzD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,UAAU,GACzD,WAAW,OAAO;EAAE,GAAG;EAAO,MAAM;EAAK,UAAU;CAAM;CAI7D,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,aACd,GAAG,SAC6B;CAChC,MAAM,eAAe;EACnB,YAAY,CAAC;EACb,oBAAoB,CAAC;EACrB,sBAAsB;CACxB;CACA,KAAK,MAAM,UAAU,QAAQ,QAAQ,GAAG;EACtC,MAAM,aAAa,cAAc,MAAM;EACvC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,UAAU,GAClD,IAAI,MAAM,UACR,aAAa,mBAAoB,OAC/B,aAAa,mBAAoB,QACjC,kBAAkB,aAAa,mBAAoB,IAAI,KACvD,kBAAkB,KAAK,IACnBA,OAAK,aAAa,mBAAoB,MAAM,KAAK,IACjD;OAGN,aAAa,WAAY,OACvB,aAAa,WAAY,QACzB,kBAAkB,aAAa,WAAY,IAAI,KAC/C,kBAAkB,KAAK,IACnBA,OAAK,aAAa,WAAY,MAAM,KAAK,IACzC;CAIZ;CAEA,OAAO;AACT"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_bundle = require('./bundle.cjs');
|
|
3
|
+
const require_type_checks = require('./type-checks.cjs');
|
|
4
|
+
const require_helpers = require('./helpers.cjs');
|
|
3
5
|
const require_codegen = require('./codegen.cjs');
|
|
6
|
+
const require_constants = require('./constants.cjs');
|
|
4
7
|
const require_jtd = require('./jtd.cjs');
|
|
8
|
+
const require_persistence = require('./persistence.cjs');
|
|
5
9
|
const require_reflection = require('./reflection.cjs');
|
|
6
10
|
const require_resolve = require('./resolve.cjs');
|
|
7
|
-
const require_type_checks = require('./type-checks.cjs');
|
|
8
11
|
const require_extract = require('./extract.cjs');
|
|
9
12
|
|
|
13
|
+
exports.JTDTypes = require_constants.JTDTypes;
|
|
10
14
|
exports.bundle = require_bundle.bundle;
|
|
11
15
|
exports.extract = require_extract.extract;
|
|
12
16
|
exports.extractHash = require_extract.extractHash;
|
|
@@ -18,13 +22,24 @@ exports.extractSchemaSchema = require_extract.extractSchemaSchema;
|
|
|
18
22
|
exports.extractSource = require_extract.extractSource;
|
|
19
23
|
exports.extractVariant = require_extract.extractVariant;
|
|
20
24
|
exports.generateCode = require_codegen.generateCode;
|
|
25
|
+
exports.getCacheDirectory = require_persistence.getCacheDirectory;
|
|
26
|
+
exports.getCacheFilePath = require_persistence.getCacheFilePath;
|
|
27
|
+
exports.getProperties = require_helpers.getProperties;
|
|
21
28
|
exports.isExtractedSchema = require_type_checks.isExtractedSchema;
|
|
22
29
|
exports.isJTDSchema = require_type_checks.isJTDSchema;
|
|
30
|
+
exports.isJTDSchemaObject = require_type_checks.isJTDSchemaObject;
|
|
31
|
+
exports.isObjectSchema = require_type_checks.isObjectSchema;
|
|
23
32
|
exports.isSchema = require_type_checks.isSchema;
|
|
24
33
|
exports.isUntypedInput = require_type_checks.isUntypedInput;
|
|
25
34
|
exports.isUntypedSchema = require_type_checks.isUntypedSchema;
|
|
26
35
|
exports.jsonSchemaToJtd = require_jtd.jsonSchemaToJtd;
|
|
36
|
+
exports.mergeSchemas = require_helpers.mergeSchemas;
|
|
37
|
+
exports.readSchema = require_persistence.readSchema;
|
|
38
|
+
exports.readSchemaSafe = require_persistence.readSchemaSafe;
|
|
27
39
|
exports.reflectionToJsonSchema = require_reflection.reflectionToJsonSchema;
|
|
28
40
|
exports.resolve = require_resolve.resolve;
|
|
29
41
|
exports.resolveModule = require_resolve.resolveModule;
|
|
30
|
-
exports.resolveReflection = require_resolve.resolveReflection;
|
|
42
|
+
exports.resolveReflection = require_resolve.resolveReflection;
|
|
43
|
+
exports.stringifyType = require_codegen.stringifyType;
|
|
44
|
+
exports.stringifyValue = require_codegen.stringifyValue;
|
|
45
|
+
exports.writeSchema = require_persistence.writeSchema;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { BundleOptions, bundle } from "./bundle.cjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.cjs";
|
|
3
|
+
import { generateCode, stringifyType, stringifyValue } from "./codegen.cjs";
|
|
4
|
+
import { JTDTypes } from "./constants.cjs";
|
|
4
5
|
import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.cjs";
|
|
6
|
+
import { getProperties, mergeSchemas } from "./helpers.cjs";
|
|
5
7
|
import { jsonSchemaToJtd } from "./jtd.cjs";
|
|
8
|
+
import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.cjs";
|
|
6
9
|
import { reflectionToJsonSchema } from "./reflection.cjs";
|
|
7
10
|
import { resolve, resolveModule, resolveReflection } from "./resolve.cjs";
|
|
8
|
-
import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
|
|
9
|
-
export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
|
|
11
|
+
import { isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
|
|
12
|
+
export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { BundleOptions, bundle } from "./bundle.mjs";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.mjs";
|
|
3
|
+
import { generateCode, stringifyType, stringifyValue } from "./codegen.mjs";
|
|
4
|
+
import { JTDTypes } from "./constants.mjs";
|
|
4
5
|
import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
|
|
6
|
+
import { getProperties, mergeSchemas } from "./helpers.mjs";
|
|
5
7
|
import { jsonSchemaToJtd } from "./jtd.mjs";
|
|
8
|
+
import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
|
|
6
9
|
import { reflectionToJsonSchema } from "./reflection.mjs";
|
|
7
10
|
import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
|
|
8
|
-
import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
9
|
-
export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
|
|
11
|
+
import { isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
12
|
+
export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
|
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { bundle } from "./bundle.mjs";
|
|
2
|
-
import {
|
|
2
|
+
import { isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
3
|
+
import { getProperties, mergeSchemas } from "./helpers.mjs";
|
|
4
|
+
import { generateCode, stringifyType, stringifyValue } from "./codegen.mjs";
|
|
5
|
+
import { JTDTypes } from "./constants.mjs";
|
|
3
6
|
import { jsonSchemaToJtd } from "./jtd.mjs";
|
|
7
|
+
import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
|
|
4
8
|
import { reflectionToJsonSchema } from "./reflection.mjs";
|
|
5
9
|
import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
|
|
6
|
-
import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
7
10
|
import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
|
|
8
11
|
|
|
9
|
-
export { bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
|
|
12
|
+
export { JTDTypes, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
|
package/dist/jtd.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jtd.mjs","names":["isSetObject"],"sources":["../src/jtd.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n isBoolean,\n isSetArray,\n isSetString,\n isUndefined\n} from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n JsonSchemaLike,\n JTDNumberType,\n JTDSchemaType,\n SchemaMetadata\n} from \"./types\";\n\n/**\n * Maps a JSON Schema `format` annotation for integers to the closest JTD numeric type.\n *\n * @param format - The JSON Schema format hint to map.\n * @returns The matching JTD numeric type, or `undefined` if no exact match exists.\n */\nfunction jsonSchemaIntegerFormatToJtd(\n format: string | undefined\n): JTDNumberType | undefined {\n switch (format) {\n case \"int8\":\n return \"int8\";\n case \"uint8\":\n return \"uint8\";\n case \"int16\":\n return \"int16\";\n case \"uint16\":\n return \"uint16\";\n case \"int32\":\n return \"int32\";\n case \"uint32\":\n return \"uint32\";\n case undefined:\n default:\n return undefined;\n }\n}\n\n/**\n * Maps a JSON Schema `format` annotation for floating point numbers to the closest JTD numeric type.\n *\n * @param format - The JSON Schema format hint to map.\n * @returns The matching JTD numeric type, or `undefined` if no exact match exists.\n */\nfunction jsonSchemaNumberFormatToJtd(\n format: string | undefined\n): JTDNumberType | undefined {\n switch (format) {\n case \"float\":\n case \"float32\":\n return \"float32\";\n case \"double\":\n case \"float64\":\n return \"float64\";\n case undefined:\n default:\n return undefined;\n }\n}\n\n/**\n * Picks the smallest unsigned JTD integer type that can hold the provided bounds.\n *\n * @param minimum - The inclusive lower bound, when known.\n * @param maximum - The inclusive upper bound, when known.\n * @returns The narrowest unsigned JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as an unsigned integer.\n */\nfunction pickUnsignedIntegerType(\n minimum: number | undefined,\n maximum: number | undefined\n): JTDNumberType | undefined {\n if (minimum === undefined || minimum < 0) {\n return undefined;\n }\n if (maximum === undefined) {\n return undefined;\n }\n if (maximum <= 0xff) {\n return \"uint8\";\n }\n if (maximum <= 0xffff) {\n return \"uint16\";\n }\n if (maximum <= 0xffffffff) {\n return \"uint32\";\n }\n return undefined;\n}\n\n/**\n * Picks the smallest signed JTD integer type that can hold the provided bounds.\n *\n * @param minimum - The inclusive lower bound, when known.\n * @param maximum - The inclusive upper bound, when known.\n * @returns The narrowest signed JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as a signed integer.\n */\nfunction pickSignedIntegerType(\n minimum: number | undefined,\n maximum: number | undefined\n): JTDNumberType | undefined {\n if (\n minimum !== undefined &&\n maximum !== undefined &&\n minimum >= -0x80 &&\n maximum <= 0x7f\n ) {\n return \"int8\";\n }\n if (\n minimum !== undefined &&\n maximum !== undefined &&\n minimum >= -0x8000 &&\n maximum <= 0x7fff\n ) {\n return \"int16\";\n }\n return \"int32\";\n}\n\n/**\n * Tests whether the provided value is a non-null object that can be inspected as a JSON Schema fragment.\n *\n * @param value - The value to test.\n * @returns `true` if the value is a plain object suitable for JSON-Schema conversion.\n */\nfunction isJsonSchemaLike(value: unknown): value is JsonSchemaLike {\n return isSetObject(value);\n}\n\n/**\n * Reads the JSON Schema `type` field as an array, normalising the single-string form.\n *\n * @param schema - The JSON Schema fragment to inspect.\n * @returns The list of JSON Schema type names declared on the fragment.\n */\nfunction readTypes(schema: JsonSchemaLike): string[] {\n if (Array.isArray(schema.type)) {\n return schema.type;\n }\n if (typeof schema.type === \"string\") {\n return [schema.type];\n }\n return [];\n}\n\n/**\n * Builds a JTD `metadata` object from the JSON Schema annotation keywords found on a fragment.\n *\n * @param schema - The source JSON Schema fragment.\n * @returns A metadata bag suitable for attaching to a JTD form, or `undefined` if no annotations are present.\n */\nfunction collectMetadata<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike): TMetadata | undefined {\n const metadata: TMetadata = {} as TMetadata;\n if (isSetString(schema.description)) {\n metadata.description = schema.description;\n }\n\n if (isSetArray(schema.examples)) {\n metadata.examples = schema.examples;\n }\n\n if (\n isSetArray(schema.alias) &&\n (schema.alias as unknown[]).every(isSetString)\n ) {\n metadata.alias = schema.alias as string[];\n }\n\n if (isSetString(schema.table)) {\n metadata.default = schema.table;\n }\n\n if (isSetString(schema.title)) {\n metadata.title = schema.title;\n }\n\n if (!isUndefined(schema.default)) {\n metadata.default = schema.default;\n }\n\n if (isBoolean(schema.isHidden)) {\n metadata.isHidden = schema.isHidden;\n } else if (isBoolean(schema.hidden)) {\n metadata.isHidden = schema.hidden;\n }\n\n if (isBoolean(schema.isIgnored)) {\n metadata.isIgnored = schema.isIgnored;\n } else if (isBoolean(schema.ignored)) {\n metadata.isIgnored = schema.ignored;\n }\n\n if (isBoolean(schema.isReadonly)) {\n metadata.isReadonly = schema.isReadonly;\n } else if (isBoolean(schema.readonly)) {\n metadata.isReadonly = schema.readonly;\n }\n\n if (isBoolean(schema.isPrimaryKey)) {\n metadata.isPrimaryKey = schema.isPrimaryKey;\n } else if (isBoolean(schema.primaryKey)) {\n metadata.isPrimaryKey = schema.primaryKey;\n }\n\n if (isBoolean(schema.isInternal)) {\n metadata.isInternal = schema.isInternal;\n } else if (isBoolean(schema.internal)) {\n metadata.isInternal = schema.internal;\n }\n\n if (isBoolean(schema.isRuntime)) {\n metadata.isRuntime = schema.isRuntime;\n } else if (isBoolean(schema.runtime)) {\n metadata.isRuntime = schema.runtime;\n }\n\n if (isSetArray(schema.union)) {\n metadata.union = schema.union as JsonSchemaLike[];\n }\n\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n}\n\n/**\n * Attaches metadata and nullability flags to a JTD form, mutating and returning the form.\n *\n * @param form - The base JTD form to decorate.\n * @param schema - The source JSON Schema fragment from which annotations are read.\n * @param nullable - Whether the schema is nullable in JTD semantics.\n * @returns The decorated JTD form.\n */\nfunction decorate<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n form: JTDSchemaType<TMetadata>,\n schema: JsonSchemaLike,\n nullable: boolean\n): JTDSchemaType<TMetadata> {\n if (nullable) {\n (form as { nullable?: boolean }).nullable = true;\n }\n const metadata = collectMetadata<TMetadata>(schema);\n if (metadata) {\n (form as { metadata?: TMetadata }).metadata = metadata;\n }\n return form;\n}\n\n/**\n * Determines whether the supplied list of JSON Schema types collapses to `null` only.\n *\n * @param types - The normalized list of JSON Schema type names.\n * @returns `true` if the only declared type is `null`.\n */\nfunction isNullOnly(types: string[]): boolean {\n return types.length > 0 && types.every(t => t === \"null\");\n}\n\n/**\n * Splits a `null` declaration away from a list of JSON Schema types.\n *\n * @param types - The normalized list of JSON Schema type names.\n * @returns A tuple of `[nonNullTypes, nullable]` describing the remaining types and whether `null` was present.\n */\nfunction stripNull(types: string[]): { types: string[]; nullable: boolean } {\n const nullable = types.includes(\"null\");\n\n return { types: types.filter(t => t !== \"null\"), nullable };\n}\n\n/**\n * Converts a JSON Schema `enum` keyword to a JTD enum form, stringifying values when required.\n *\n * @param values - The raw enum values from the JSON Schema fragment.\n * @returns A JTD enum form, or `undefined` if the enum cannot be represented (e.g. empty list).\n */\nfunction enumToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(values: readonly unknown[]): JTDSchemaType<TMetadata> | undefined {\n const strings = values\n .filter(v => v !== null && v !== undefined)\n .map(v => String(v));\n if (strings.length === 0) {\n return undefined;\n }\n return { enum: Array.from(new Set(strings)) };\n}\n\n/**\n * Selects the most appropriate JTD numeric `type` value for a JSON Schema integer fragment.\n *\n * @param schema - The integer JSON Schema fragment.\n * @returns The chosen JTD integer type.\n */\nfunction pickIntegerJtdType(schema: JsonSchemaLike): JTDNumberType {\n const mapped = jsonSchemaIntegerFormatToJtd(schema.format);\n if (mapped) {\n return mapped;\n }\n const unsigned = pickUnsignedIntegerType(schema.minimum, schema.maximum);\n if (unsigned) {\n return unsigned;\n }\n return pickSignedIntegerType(schema.minimum, schema.maximum) ?? \"int32\";\n}\n\n/**\n * Selects the most appropriate JTD numeric `type` value for a JSON Schema number fragment.\n *\n * @param schema - The number JSON Schema fragment.\n * @returns The chosen JTD floating point type.\n */\nfunction pickNumberJtdType(schema: JsonSchemaLike): JTDNumberType {\n return jsonSchemaNumberFormatToJtd(schema.format) ?? \"float64\";\n}\n\n/**\n * Selects the JTD string `type` value for a JSON Schema string fragment, mapping `format: \"date-time\"` to `timestamp`.\n *\n * @param schema - The string JSON Schema fragment.\n * @returns The chosen JTD string type.\n */\nfunction pickStringJtdType(schema: JsonSchemaLike): \"string\" | \"timestamp\" {\n if (schema.format === \"date-time\") {\n return \"timestamp\";\n }\n return \"string\";\n}\n\n/**\n * Converts a JSON Schema object fragment into a JTD properties form.\n *\n * @param schema - The object JSON Schema fragment.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns The JTD properties form representing the object.\n */\nfunction objectToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike, nullable: boolean): JTDSchemaType<TMetadata> {\n const required = new Set(schema.required ?? []);\n const properties: Record<string, JTDSchemaType<TMetadata>> = {};\n const optionalProperties: Record<string, JTDSchemaType<TMetadata>> = {};\n\n const metadata = {\n default: schema.default ?? {}\n } as TMetadata & { default: Record<string, unknown> };\n\n if (schema.properties) {\n for (const [key, value] of Object.entries(schema.properties)) {\n if (!isUndefined(value.default)) {\n metadata.default[key] = value.default;\n }\n\n const converted = jsonSchemaToJtd<TMetadata>(value);\n if (!converted) {\n continue;\n }\n\n if (required.has(key)) {\n properties[key] = converted;\n } else {\n optionalProperties[key] = converted;\n }\n }\n }\n\n const hasProperties = Object.keys(properties).length > 0;\n const hasOptional = Object.keys(optionalProperties).length > 0;\n\n // JTD requires `values` form for open maps with a single value schema.\n // patternProperties / additionalProperties: object collapses to `values`\n // when there are no declared properties.\n if (\n !hasProperties &&\n !hasOptional &&\n isJsonSchemaLike(schema.additionalProperties)\n ) {\n const values = jsonSchemaToJtd<TMetadata>(schema.additionalProperties);\n if (values) {\n return decorate<TMetadata>({ metadata, values }, schema, nullable);\n }\n }\n if (!hasProperties && !hasOptional && schema.patternProperties) {\n const first = Object.values(schema.patternProperties)[0];\n if (first) {\n const values = jsonSchemaToJtd<TMetadata>(first);\n if (values) {\n return decorate<TMetadata>({ metadata, values }, schema, nullable);\n }\n }\n }\n\n const form: {\n metadata: TMetadata;\n properties?: Record<string, JTDSchemaType<TMetadata>>;\n optionalProperties?: Record<string, JTDSchemaType<TMetadata>>;\n additionalProperties?: boolean;\n } = { metadata };\n\n if (hasProperties) {\n form.properties = properties;\n } else if (!hasOptional) {\n // JTD object form must have at least one of properties / optionalProperties.\n form.properties = {};\n }\n if (hasOptional) {\n form.optionalProperties = optionalProperties;\n }\n if (\n schema.additionalProperties === true ||\n isJsonSchemaLike(schema.additionalProperties) ||\n schema.patternProperties !== undefined\n ) {\n form.additionalProperties = true;\n }\n\n return decorate<TMetadata>(form, schema, nullable);\n}\n\n/**\n * Converts a JSON Schema array fragment into a JTD elements form.\n *\n * @param schema - The array JSON Schema fragment.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns The JTD elements form representing the array.\n */\nfunction arrayToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike, nullable: boolean): JTDSchemaType<TMetadata> {\n let elementSchema: JsonSchemaLike | undefined;\n if (Array.isArray(schema.items)) {\n // Tuple form — JTD has no native tuple support. Best effort: collapse to\n // the union (anyOf) of the tuple member schemas; if there is only one\n // distinct shape, fall back to using it directly.\n elementSchema = schema.items[0];\n } else if (schema.items) {\n elementSchema = schema.items;\n }\n\n const elements = elementSchema\n ? jsonSchemaToJtd<TMetadata>(elementSchema)\n : {};\n\n return decorate<TMetadata>({ elements: elements ?? {} }, schema, nullable);\n}\n\n/**\n * Attempts to detect and emit a JTD discriminator form from a JSON Schema `oneOf` or `anyOf` fragment.\n *\n * @param schemas - The list of candidate JSON Schema fragments.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns A discriminator form when every branch shares a single tag property, otherwise `undefined`.\n */\nfunction tryDiscriminator<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n schemas: readonly JsonSchemaLike[],\n nullable: boolean\n): JTDSchemaType<TMetadata> | undefined {\n if (schemas.length < 2) {\n return undefined;\n }\n\n let candidateKey: string | undefined;\n const mapping: Record<string, JTDSchemaType<TMetadata>> = {};\n\n for (const branch of schemas) {\n if (!isJsonSchemaLike(branch) || !branch.properties) {\n return undefined;\n }\n\n const constantTags = Object.entries(branch.properties).filter(\n ([, value]) =>\n isJsonSchemaLike(value) &&\n (typeof value.const === \"string\" ||\n (Array.isArray(value.enum) &&\n value.enum.length === 1 &&\n typeof value.enum[0] === \"string\"))\n );\n if (constantTags.length === 0) {\n return undefined;\n }\n\n const [tagKey, tagSchema] = constantTags[0]!;\n if (!candidateKey) {\n candidateKey = tagKey;\n } else if (candidateKey !== tagKey) {\n return undefined;\n }\n\n const tag =\n typeof tagSchema.const === \"string\"\n ? tagSchema.const\n : (tagSchema.enum?.[0] as string);\n\n // Remove the discriminator property from the branch before converting,\n // as JTD's mapping schemas describe the remainder of the object.\n const { [tagKey]: _omit, ...restProperties } = branch.properties;\n const restRequired = (branch.required ?? []).filter(k => k !== tagKey);\n const branchSchema: JsonSchemaLike = {\n ...branch,\n properties: restProperties,\n required: restRequired\n };\n\n const branchForm = jsonSchemaToJtd<TMetadata>(branchSchema);\n if (!branchForm || !isSetObject(branchForm) || \"ref\" in branchForm) {\n return undefined;\n }\n\n mapping[tag] = branchForm;\n }\n\n if (!candidateKey) {\n return undefined;\n }\n\n const form: JTDSchemaType<TMetadata> = {\n discriminator: candidateKey,\n mapping\n };\n if (nullable) {\n (form as { nullable?: boolean }).nullable = true;\n }\n\n return form;\n}\n\n/**\n * Converts a JSON Schema fragment (draft-07 style, as produced by `zod-to-json-schema`, Standard Schema, etc.) into a valid JSON Type Definition (RFC 8927) schema.\n *\n * Unsupported JSON Schema keywords (`pattern`, `const`, `minItems`, `maxItems`, `uniqueItems`, etc.) are dropped — JTD intentionally omits these. Annotation keywords (`description`, `title`, `default`, `examples`) are preserved under the JTD `metadata` field.\n *\n * @param schema - The JSON Schema fragment to convert.\n * @returns A valid JTD form, or `undefined` if the input cannot be represented.\n */\nexport function jsonSchemaToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n schema: JsonSchemaLike | undefined | null\n): JTDSchemaType<TMetadata> | undefined {\n if (!isJsonSchemaLike(schema)) {\n return undefined;\n }\n\n // $ref → JTD ref form. The pointer must reference `#/definitions/<name>`.\n if (isSetString(schema.$ref)) {\n const match = /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(schema.$ref);\n if (match) {\n return { ref: match[1]! };\n }\n }\n\n // allOf — fold member schemas together via shallow merge before converting.\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n const merged = schema.allOf.reduce<JsonSchemaLike>(\n (acc, current) => mergeJsonSchema(acc, current),\n {}\n );\n const { allOf: _allOf, ...rest } = schema;\n\n return jsonSchemaToJtd<TMetadata>(mergeJsonSchema(merged, rest));\n }\n\n const rawTypes = readTypes(schema);\n const { types: nonNullTypes, nullable: typeIsNullable } = stripNull(rawTypes);\n const nullable = Boolean(schema.nullable) || typeIsNullable;\n\n // Pure null type → JTD has no first-class null form, emit empty + nullable.\n if (isNullOnly(rawTypes)) {\n return decorate<TMetadata>({}, schema, true);\n }\n\n // Enum form.\n if (Array.isArray(schema.enum)) {\n const enumForm = enumToJtd<TMetadata>(schema.enum);\n if (enumForm) {\n return decorate<TMetadata>(enumForm, schema, nullable);\n }\n }\n\n // const → enum of one (only valid when value is a string in JTD).\n if (isSetString(schema.const)) {\n return decorate<TMetadata>({ enum: [schema.const] }, schema, nullable);\n }\n\n // anyOf / oneOf — try to detect a discriminated union, otherwise collapse.\n const union = schema.oneOf ?? schema.anyOf;\n if (Array.isArray(union) && union.length > 0) {\n const branches = union.filter(isJsonSchemaLike);\n const onlyNullBranches = branches.filter(b =>\n readTypes(b).includes(\"null\")\n );\n const nonNullBranches = branches.filter(\n b => !isNullOnly(readTypes(b)) && readTypes(b).join() !== \"null\"\n );\n const unionNullable = nullable || onlyNullBranches.length > 0;\n\n if (nonNullBranches.length === 1) {\n const collapsed = jsonSchemaToJtd<TMetadata>(nonNullBranches[0]);\n if (collapsed) {\n return decorate<TMetadata>(collapsed, schema, unionNullable);\n }\n }\n\n const discriminated = tryDiscriminator<TMetadata>(\n nonNullBranches,\n unionNullable\n );\n if (discriminated) {\n const metadata = collectMetadata<TMetadata>(schema);\n if (metadata) {\n (discriminated as { metadata?: TMetadata }).metadata = metadata;\n }\n return discriminated;\n }\n\n // No safe JTD equivalent: emit empty schema (matches any value) with\n // metadata to preserve provenance.\n const fallback = decorate<TMetadata>({}, schema, unionNullable);\n const metadata =\n (fallback as { metadata?: TMetadata }).metadata ?? ({} as TMetadata);\n metadata.union = union;\n (fallback as { metadata?: TMetadata }).metadata = metadata;\n return fallback;\n }\n\n // Object form — `type: \"object\"` or implicit via `properties`.\n if (\n nonNullTypes.includes(\"object\") ||\n schema.properties ||\n schema.patternProperties ||\n isJsonSchemaLike(schema.additionalProperties)\n ) {\n const result = objectToJtd<TMetadata>(schema, nullable);\n const definitions = schema.definitions ?? schema.$defs;\n if (definitions && Object.keys(definitions).length > 0) {\n const converted: Record<string, JTDSchemaType<TMetadata>> = {};\n for (const [key, value] of Object.entries(definitions)) {\n const def = jsonSchemaToJtd<TMetadata>(value);\n if (def) {\n converted[key] = def;\n }\n }\n if (Object.keys(converted).length > 0) {\n (\n result as { definitions?: Record<string, JTDSchemaType<TMetadata>> }\n ).definitions = converted;\n }\n }\n return result;\n }\n\n if (nonNullTypes.includes(\"array\")) {\n return arrayToJtd<TMetadata>(schema, nullable);\n }\n\n // Scalar types.\n if (nonNullTypes.length === 1) {\n const t = nonNullTypes[0]!;\n if (t === \"string\") {\n return decorate<TMetadata>(\n { type: pickStringJtdType(schema) },\n schema,\n nullable\n );\n }\n if (t === \"boolean\") {\n return decorate<TMetadata>({ type: \"boolean\" }, schema, nullable);\n }\n if (t === \"integer\") {\n return decorate<TMetadata>(\n { type: pickIntegerJtdType(schema) },\n schema,\n nullable\n );\n }\n if (t === \"number\") {\n return decorate<TMetadata>(\n { type: pickNumberJtdType(schema) },\n schema,\n nullable\n );\n }\n }\n\n // Mixed scalar types (e.g. [\"string\", \"number\"]) — emit empty schema since\n // JTD has no native union of primitives.\n if (nonNullTypes.length > 1) {\n return decorate<TMetadata>({}, schema, nullable);\n }\n\n // No type info — empty (any) schema, possibly nullable.\n return decorate<TMetadata>({}, schema, nullable);\n}\n\n/**\n * Shallow-merges two JSON Schema fragments, combining `required` arrays and `properties` maps.\n *\n * @param left - The base schema fragment.\n * @param right - The schema fragment to merge into the base.\n * @returns A merged schema fragment. Neither input is mutated.\n */\nfunction mergeJsonSchema(\n left: JsonSchemaLike,\n right: JsonSchemaLike\n): JsonSchemaLike {\n const merged: JsonSchemaLike = { ...left, ...right };\n if (left.properties || right.properties) {\n merged.properties = {\n ...(left.properties ?? {}),\n ...(right.properties ?? {})\n };\n }\n if (left.required || right.required) {\n merged.required = Array.from(\n new Set([...(left.required ?? []), ...(right.required ?? [])])\n );\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,6BACP,QAC2B;AAC3B,SAAQ,QAAR;EACE,KAAK,OACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK,QACH,QAAO;EACT,KAAK,SACH,QAAO;EACT,KAAK;EACL,QACE;;;;;;;;;AAUN,SAAS,4BACP,QAC2B;AAC3B,SAAQ,QAAR;EACE,KAAK;EACL,KAAK,UACH,QAAO;EACT,KAAK;EACL,KAAK,UACH,QAAO;EACT,KAAK;EACL,QACE;;;;;;;;;;AAWN,SAAS,wBACP,SACA,SAC2B;AAC3B,KAAI,YAAY,UAAa,UAAU,EACrC;AAEF,KAAI,YAAY,OACd;AAEF,KAAI,WAAW,IACb,QAAO;AAET,KAAI,WAAW,MACb,QAAO;AAET,KAAI,WAAW,WACb,QAAO;;;;;;;;;AAYX,SAAS,sBACP,SACA,SAC2B;AAC3B,KACE,YAAY,UACZ,YA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M,WAAW,EAAE,QAAQ,SAAS;AAEnE,MAAI,MAAM,UACR,QAAO,SACL,EAAE,MAAM,mBAAmB,OAAO,EAAE,EACpC,QACA,SACD;AAEH,MAAI,MAAM,SACR,QAAO,SACL,EAAE,MAAM,kBAAkB,OAAO,EAAE,EACnC,QACA,SACD;;AAML,KAAI,aAAa,SAAS,EACxB,QAAO,SAAoB,EAAE,EAAE,QAAQ,SAAS;AAIlD,QAAO,SAAoB,EAAE,EAAE,QAAQ,SAAS;;;;;;;;;AAUlD,SAAS,gBACP,MACA,OACgB;CAChB,MAAM,SAAyB;EAAE,GAAG;EAAM,GAAG;EAAO;AACpD,KAAI,KAAK,cAAc,MAAM,WAC3B,QAAO,aAAa;EAClB,GAAI,KAAK,cAAc,EAAE;EACzB,GAAI,MAAM,cAAc,EAAE;EAC3B;AAEH,KAAI,KAAK,YAAY,MAAM,SACzB,QAAO,WAAW,MAAM,KACtB,IAAI,IAAI,CAAC,GAAI,KAAK,YAAY,EAAE,EAAG,GAAI,MAAM,YAAY,EAAE,CAAE,CAAC,CAC/D;AAEH,QAAO"}
|
|
1
|
+
{"version":3,"file":"jtd.mjs","names":["isSetObject"],"sources":["../src/jtd.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport {\n isBoolean,\n isSetArray,\n isSetString,\n isUndefined\n} from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n JsonSchemaLike,\n JTDNumberType,\n JTDSchemaType,\n SchemaMetadata\n} from \"./types\";\n\n/**\n * Maps a JSON Schema `format` annotation for integers to the closest JTD numeric type.\n *\n * @param format - The JSON Schema format hint to map.\n * @returns The matching JTD numeric type, or `undefined` if no exact match exists.\n */\nfunction jsonSchemaIntegerFormatToJtd(\n format: string | undefined\n): JTDNumberType | undefined {\n switch (format) {\n case \"int8\":\n return \"int8\";\n case \"uint8\":\n return \"uint8\";\n case \"int16\":\n return \"int16\";\n case \"uint16\":\n return \"uint16\";\n case \"int32\":\n return \"int32\";\n case \"uint32\":\n return \"uint32\";\n case undefined:\n default:\n return undefined;\n }\n}\n\n/**\n * Maps a JSON Schema `format` annotation for floating point numbers to the closest JTD numeric type.\n *\n * @param format - The JSON Schema format hint to map.\n * @returns The matching JTD numeric type, or `undefined` if no exact match exists.\n */\nfunction jsonSchemaNumberFormatToJtd(\n format: string | undefined\n): JTDNumberType | undefined {\n switch (format) {\n case \"float\":\n case \"float32\":\n return \"float32\";\n case \"double\":\n case \"float64\":\n return \"float64\";\n case undefined:\n default:\n return undefined;\n }\n}\n\n/**\n * Picks the smallest unsigned JTD integer type that can hold the provided bounds.\n *\n * @param minimum - The inclusive lower bound, when known.\n * @param maximum - The inclusive upper bound, when known.\n * @returns The narrowest unsigned JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as an unsigned integer.\n */\nfunction pickUnsignedIntegerType(\n minimum: number | undefined,\n maximum: number | undefined\n): JTDNumberType | undefined {\n if (minimum === undefined || minimum < 0) {\n return undefined;\n }\n if (maximum === undefined) {\n return undefined;\n }\n if (maximum <= 0xff) {\n return \"uint8\";\n }\n if (maximum <= 0xffff) {\n return \"uint16\";\n }\n if (maximum <= 0xffffffff) {\n return \"uint32\";\n }\n return undefined;\n}\n\n/**\n * Picks the smallest signed JTD integer type that can hold the provided bounds.\n *\n * @param minimum - The inclusive lower bound, when known.\n * @param maximum - The inclusive upper bound, when known.\n * @returns The narrowest signed JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as a signed integer.\n */\nfunction pickSignedIntegerType(\n minimum: number | undefined,\n maximum: number | undefined\n): JTDNumberType | undefined {\n if (\n minimum !== undefined &&\n maximum !== undefined &&\n minimum >= -0x80 &&\n maximum <= 0x7f\n ) {\n return \"int8\";\n }\n if (\n minimum !== undefined &&\n maximum !== undefined &&\n minimum >= -0x8000 &&\n maximum <= 0x7fff\n ) {\n return \"int16\";\n }\n return \"int32\";\n}\n\n/**\n * Tests whether the provided value is a non-null object that can be inspected as a JSON Schema fragment.\n *\n * @param value - The value to test.\n * @returns `true` if the value is a plain object suitable for JSON-Schema conversion.\n */\nfunction isJsonSchemaLike(value: unknown): value is JsonSchemaLike {\n return isSetObject(value);\n}\n\n/**\n * Reads the JSON Schema `type` field as an array, normalising the single-string form.\n *\n * @param schema - The JSON Schema fragment to inspect.\n * @returns The list of JSON Schema type names declared on the fragment.\n */\nfunction readTypes(schema: JsonSchemaLike): string[] {\n if (Array.isArray(schema.type)) {\n return schema.type;\n }\n if (typeof schema.type === \"string\") {\n return [schema.type];\n }\n return [];\n}\n\n/**\n * Builds a JTD `metadata` object from the JSON Schema annotation keywords found on a fragment.\n *\n * @param schema - The source JSON Schema fragment.\n * @returns A metadata bag suitable for attaching to a JTD form, or `undefined` if no annotations are present.\n */\nfunction collectMetadata<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike): TMetadata | undefined {\n const metadata: TMetadata = {} as TMetadata;\n if (isSetString(schema.description)) {\n metadata.description = schema.description;\n }\n\n if (isSetArray(schema.examples)) {\n metadata.examples = schema.examples;\n }\n\n if (\n isSetArray(schema.alias) &&\n (schema.alias as unknown[]).every(isSetString)\n ) {\n metadata.alias = schema.alias as string[];\n }\n\n if (isSetString(schema.table)) {\n metadata.default = schema.table;\n }\n\n if (isSetString(schema.title)) {\n metadata.title = schema.title;\n }\n\n if (!isUndefined(schema.default)) {\n metadata.default = schema.default;\n }\n\n if (isBoolean(schema.isHidden)) {\n metadata.isHidden = schema.isHidden;\n } else if (isBoolean(schema.hidden)) {\n metadata.isHidden = schema.hidden;\n }\n\n if (isBoolean(schema.isIgnored)) {\n metadata.isIgnored = schema.isIgnored;\n } else if (isBoolean(schema.ignored)) {\n metadata.isIgnored = schema.ignored;\n }\n\n if (isBoolean(schema.isReadonly)) {\n metadata.isReadonly = schema.isReadonly;\n } else if (isBoolean(schema.readonly)) {\n metadata.isReadonly = schema.readonly;\n }\n\n if (isBoolean(schema.isPrimaryKey)) {\n metadata.isPrimaryKey = schema.isPrimaryKey;\n } else if (isBoolean(schema.primaryKey)) {\n metadata.isPrimaryKey = schema.primaryKey;\n }\n\n if (isBoolean(schema.isInternal)) {\n metadata.isInternal = schema.isInternal;\n } else if (isBoolean(schema.internal)) {\n metadata.isInternal = schema.internal;\n }\n\n if (isBoolean(schema.isRuntime)) {\n metadata.isRuntime = schema.isRuntime;\n } else if (isBoolean(schema.runtime)) {\n metadata.isRuntime = schema.runtime;\n }\n\n if (isSetArray(schema.union)) {\n metadata.union = schema.union as JsonSchemaLike[];\n }\n\n return Object.keys(metadata).length > 0 ? metadata : undefined;\n}\n\n/**\n * Attaches metadata and nullability flags to a JTD form, mutating and returning the form.\n *\n * @param form - The base JTD form to decorate.\n * @param schema - The source JSON Schema fragment from which annotations are read.\n * @param nullable - Whether the schema is nullable in JTD semantics.\n * @returns The decorated JTD form.\n */\nfunction decorate<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n form: JTDSchemaType<TMetadata>,\n schema: JsonSchemaLike,\n nullable: boolean\n): JTDSchemaType<TMetadata> {\n if (nullable) {\n (form as { nullable?: boolean }).nullable = true;\n }\n const metadata = collectMetadata<TMetadata>(schema);\n if (metadata) {\n (form as { metadata?: TMetadata }).metadata = metadata;\n }\n return form;\n}\n\n/**\n * Determines whether the supplied list of JSON Schema types collapses to `null` only.\n *\n * @param types - The normalized list of JSON Schema type names.\n * @returns `true` if the only declared type is `null`.\n */\nfunction isNullOnly(types: string[]): boolean {\n return types.length > 0 && types.every(t => t === \"null\");\n}\n\n/**\n * Splits a `null` declaration away from a list of JSON Schema types.\n *\n * @param types - The normalized list of JSON Schema type names.\n * @returns A tuple of `[nonNullTypes, nullable]` describing the remaining types and whether `null` was present.\n */\nfunction stripNull(types: string[]): { types: string[]; nullable: boolean } {\n const nullable = types.includes(\"null\");\n\n return { types: types.filter(t => t !== \"null\"), nullable };\n}\n\n/**\n * Converts a JSON Schema `enum` keyword to a JTD enum form, stringifying values when required.\n *\n * @param values - The raw enum values from the JSON Schema fragment.\n * @returns A JTD enum form, or `undefined` if the enum cannot be represented (e.g. empty list).\n */\nfunction enumToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(values: readonly unknown[]): JTDSchemaType<TMetadata> | undefined {\n const strings = values\n .filter(v => v !== null && v !== undefined)\n .map(v => String(v));\n if (strings.length === 0) {\n return undefined;\n }\n return { enum: Array.from(new Set(strings)) };\n}\n\n/**\n * Selects the most appropriate JTD numeric `type` value for a JSON Schema integer fragment.\n *\n * @param schema - The integer JSON Schema fragment.\n * @returns The chosen JTD integer type.\n */\nfunction pickIntegerJtdType(schema: JsonSchemaLike): JTDNumberType {\n const mapped = jsonSchemaIntegerFormatToJtd(schema.format);\n if (mapped) {\n return mapped;\n }\n const unsigned = pickUnsignedIntegerType(schema.minimum, schema.maximum);\n if (unsigned) {\n return unsigned;\n }\n return pickSignedIntegerType(schema.minimum, schema.maximum) ?? \"int32\";\n}\n\n/**\n * Selects the most appropriate JTD numeric `type` value for a JSON Schema number fragment.\n *\n * @param schema - The number JSON Schema fragment.\n * @returns The chosen JTD floating point type.\n */\nfunction pickNumberJtdType(schema: JsonSchemaLike): JTDNumberType {\n return jsonSchemaNumberFormatToJtd(schema.format) ?? \"float64\";\n}\n\n/**\n * Selects the JTD string `type` value for a JSON Schema string fragment, mapping `format: \"date-time\"` to `timestamp`.\n *\n * @param schema - The string JSON Schema fragment.\n * @returns The chosen JTD string type.\n */\nfunction pickStringJtdType(schema: JsonSchemaLike): \"string\" | \"timestamp\" {\n if (schema.format === \"date-time\") {\n return \"timestamp\";\n }\n return \"string\";\n}\n\n/**\n * Converts a JSON Schema object fragment into a JTD properties form.\n *\n * @param schema - The object JSON Schema fragment.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns The JTD properties form representing the object.\n */\nfunction objectToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike, nullable: boolean): JTDSchemaType<TMetadata> {\n const required = new Set(schema.required ?? []);\n const properties: Record<string, JTDSchemaType<TMetadata>> = {};\n const optionalProperties: Record<string, JTDSchemaType<TMetadata>> = {};\n\n const metadata = {\n default: schema.default ?? {}\n } as TMetadata & { default: Record<string, unknown> };\n\n if (schema.properties) {\n for (const [key, value] of Object.entries(schema.properties)) {\n if (!isUndefined(value.default)) {\n metadata.default[key] = value.default;\n }\n\n const converted = jsonSchemaToJtd<TMetadata>(value);\n if (!converted) {\n continue;\n }\n\n if (required.has(key)) {\n properties[key] = converted;\n } else {\n optionalProperties[key] = converted;\n }\n }\n }\n\n const hasProperties = Object.keys(properties).length > 0;\n const hasOptional = Object.keys(optionalProperties).length > 0;\n\n // JTD requires `values` form for open maps with a single value schema.\n // patternProperties / additionalProperties: object collapses to `values`\n // when there are no declared properties.\n if (\n !hasProperties &&\n !hasOptional &&\n isJsonSchemaLike(schema.additionalProperties)\n ) {\n const values = jsonSchemaToJtd<TMetadata>(schema.additionalProperties);\n if (values) {\n return decorate<TMetadata>({ metadata, values }, schema, nullable);\n }\n }\n if (!hasProperties && !hasOptional && schema.patternProperties) {\n const first = Object.values(schema.patternProperties)[0];\n if (first) {\n const values = jsonSchemaToJtd<TMetadata>(first);\n if (values) {\n return decorate<TMetadata>({ metadata, values }, schema, nullable);\n }\n }\n }\n\n const form: {\n metadata: TMetadata;\n properties?: Record<string, JTDSchemaType<TMetadata>>;\n optionalProperties?: Record<string, JTDSchemaType<TMetadata>>;\n additionalProperties?: boolean;\n } = { metadata };\n\n if (hasProperties) {\n form.properties = properties;\n } else if (!hasOptional) {\n // JTD object form must have at least one of properties / optionalProperties.\n form.properties = {};\n }\n if (hasOptional) {\n form.optionalProperties = optionalProperties;\n }\n if (\n schema.additionalProperties === true ||\n isJsonSchemaLike(schema.additionalProperties) ||\n schema.patternProperties !== undefined\n ) {\n form.additionalProperties = true;\n }\n\n return decorate<TMetadata>(form, schema, nullable);\n}\n\n/**\n * Converts a JSON Schema array fragment into a JTD elements form.\n *\n * @param schema - The array JSON Schema fragment.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns The JTD elements form representing the array.\n */\nfunction arrayToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: JsonSchemaLike, nullable: boolean): JTDSchemaType<TMetadata> {\n let elementSchema: JsonSchemaLike | undefined;\n if (Array.isArray(schema.items)) {\n // Tuple form — JTD has no native tuple support. Best effort: collapse to\n // the union (anyOf) of the tuple member schemas; if there is only one\n // distinct shape, fall back to using it directly.\n elementSchema = schema.items[0];\n } else if (schema.items) {\n elementSchema = schema.items;\n }\n\n const elements = elementSchema\n ? jsonSchemaToJtd<TMetadata>(elementSchema)\n : {};\n\n return decorate<TMetadata>({ elements: elements ?? {} }, schema, nullable);\n}\n\n/**\n * Attempts to detect and emit a JTD discriminator form from a JSON Schema `oneOf` or `anyOf` fragment.\n *\n * @param schemas - The list of candidate JSON Schema fragments.\n * @param nullable - Whether the resulting JTD form should be nullable.\n * @returns A discriminator form when every branch shares a single tag property, otherwise `undefined`.\n */\nfunction tryDiscriminator<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n schemas: readonly JsonSchemaLike[],\n nullable: boolean\n): JTDSchemaType<TMetadata> | undefined {\n if (schemas.length < 2) {\n return undefined;\n }\n\n let candidateKey: string | undefined;\n const mapping: Record<string, JTDSchemaType<TMetadata>> = {};\n\n for (const branch of schemas) {\n if (!isJsonSchemaLike(branch) || !branch.properties) {\n return undefined;\n }\n\n const constantTags = Object.entries(branch.properties).filter(\n ([, value]) =>\n isJsonSchemaLike(value) &&\n (typeof value.const === \"string\" ||\n (Array.isArray(value.enum) &&\n value.enum.length === 1 &&\n typeof value.enum[0] === \"string\"))\n );\n if (constantTags.length === 0) {\n return undefined;\n }\n\n const [tagKey, tagSchema] = constantTags[0]!;\n if (!candidateKey) {\n candidateKey = tagKey;\n } else if (candidateKey !== tagKey) {\n return undefined;\n }\n\n const tag =\n typeof tagSchema.const === \"string\"\n ? tagSchema.const\n : (tagSchema.enum?.[0] as string);\n\n // Remove the discriminator property from the branch before converting,\n // as JTD's mapping schemas describe the remainder of the object.\n const { [tagKey]: _omit, ...restProperties } = branch.properties;\n const restRequired = (branch.required ?? []).filter(k => k !== tagKey);\n const branchSchema: JsonSchemaLike = {\n ...branch,\n properties: restProperties,\n required: restRequired\n };\n\n const branchForm = jsonSchemaToJtd<TMetadata>(branchSchema);\n if (!branchForm || !isSetObject(branchForm) || \"ref\" in branchForm) {\n return undefined;\n }\n\n mapping[tag] = branchForm;\n }\n\n if (!candidateKey) {\n return undefined;\n }\n\n const form: JTDSchemaType<TMetadata> = {\n discriminator: candidateKey,\n mapping\n };\n if (nullable) {\n (form as { nullable?: boolean }).nullable = true;\n }\n\n return form;\n}\n\n/**\n * Converts a JSON Schema fragment (draft-07 style, as produced by `zod-to-json-schema`, Standard Schema, etc.) into a valid JSON Type Definition (RFC 8927) schema.\n *\n * Unsupported JSON Schema keywords (`pattern`, `const`, `minItems`, `maxItems`, `uniqueItems`, etc.) are dropped — JTD intentionally omits these. Annotation keywords (`description`, `title`, `default`, `examples`) are preserved under the JTD `metadata` field.\n *\n * @param schema - The JSON Schema fragment to convert.\n * @returns A valid JTD form, or `undefined` if the input cannot be represented.\n */\nexport function jsonSchemaToJtd<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n schema: JsonSchemaLike | undefined | null\n): JTDSchemaType<TMetadata> | undefined {\n if (!isJsonSchemaLike(schema)) {\n return undefined;\n }\n\n // $ref → JTD ref form. The pointer must reference `#/definitions/<name>`.\n if (isSetString(schema.$ref)) {\n const match = /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(schema.$ref);\n if (match) {\n return { ref: match[1]! };\n }\n }\n\n // allOf — fold member schemas together via shallow merge before converting.\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n const merged = schema.allOf.reduce<JsonSchemaLike>(\n (acc, current) => mergeJsonSchema(acc, current),\n {}\n );\n const { allOf: _allOf, ...rest } = schema;\n\n return jsonSchemaToJtd<TMetadata>(mergeJsonSchema(merged, rest));\n }\n\n const rawTypes = readTypes(schema);\n const { types: nonNullTypes, nullable: typeIsNullable } = stripNull(rawTypes);\n const nullable = Boolean(schema.nullable) || typeIsNullable;\n\n // Pure null type → JTD has no first-class null form, emit empty + nullable.\n if (isNullOnly(rawTypes)) {\n return decorate<TMetadata>({}, schema, true);\n }\n\n // Enum form.\n if (Array.isArray(schema.enum)) {\n const enumForm = enumToJtd<TMetadata>(schema.enum);\n if (enumForm) {\n return decorate<TMetadata>(enumForm, schema, nullable);\n }\n }\n\n // const → enum of one (only valid when value is a string in JTD).\n if (isSetString(schema.const)) {\n return decorate<TMetadata>({ enum: [schema.const] }, schema, nullable);\n }\n\n // anyOf / oneOf — try to detect a discriminated union, otherwise collapse.\n const union = schema.oneOf ?? schema.anyOf;\n if (Array.isArray(union) && union.length > 0) {\n const branches = union.filter(isJsonSchemaLike);\n const onlyNullBranches = branches.filter(b =>\n readTypes(b).includes(\"null\")\n );\n const nonNullBranches = branches.filter(\n b => !isNullOnly(readTypes(b)) && readTypes(b).join() !== \"null\"\n );\n const unionNullable = nullable || onlyNullBranches.length > 0;\n\n if (nonNullBranches.length === 1) {\n const collapsed = jsonSchemaToJtd<TMetadata>(nonNullBranches[0]);\n if (collapsed) {\n return decorate<TMetadata>(collapsed, schema, unionNullable);\n }\n }\n\n const discriminated = tryDiscriminator<TMetadata>(\n nonNullBranches,\n unionNullable\n );\n if (discriminated) {\n const metadata = collectMetadata<TMetadata>(schema);\n if (metadata) {\n (discriminated as { metadata?: TMetadata }).metadata = metadata;\n }\n return discriminated;\n }\n\n // No safe JTD equivalent: emit empty schema (matches any value) with\n // metadata to preserve provenance.\n const fallback = decorate<TMetadata>({}, schema, unionNullable);\n const metadata =\n (fallback as { metadata?: TMetadata }).metadata ?? ({} as TMetadata);\n metadata.union = union;\n (fallback as { metadata?: TMetadata }).metadata = metadata;\n return fallback;\n }\n\n // Object form — `type: \"object\"` or implicit via `properties`.\n if (\n nonNullTypes.includes(\"object\") ||\n schema.properties ||\n schema.patternProperties ||\n isJsonSchemaLike(schema.additionalProperties)\n ) {\n const result = objectToJtd<TMetadata>(schema, nullable);\n const definitions = schema.definitions ?? schema.$defs;\n if (definitions && Object.keys(definitions).length > 0) {\n const converted: Record<string, JTDSchemaType<TMetadata>> = {};\n for (const [key, value] of Object.entries(definitions)) {\n const def = jsonSchemaToJtd<TMetadata>(value);\n if (def) {\n converted[key] = def;\n }\n }\n if (Object.keys(converted).length > 0) {\n (\n result as { definitions?: Record<string, JTDSchemaType<TMetadata>> }\n ).definitions = converted;\n }\n }\n return result;\n }\n\n if (nonNullTypes.includes(\"array\")) {\n return arrayToJtd<TMetadata>(schema, nullable);\n }\n\n // Scalar types.\n if (nonNullTypes.length === 1) {\n const t = nonNullTypes[0]!;\n if (t === \"string\") {\n return decorate<TMetadata>(\n { type: pickStringJtdType(schema) },\n schema,\n nullable\n );\n }\n if (t === \"boolean\") {\n return decorate<TMetadata>({ type: \"boolean\" }, schema, nullable);\n }\n if (t === \"integer\") {\n return decorate<TMetadata>(\n { type: pickIntegerJtdType(schema) },\n schema,\n nullable\n );\n }\n if (t === \"number\") {\n return decorate<TMetadata>(\n { type: pickNumberJtdType(schema) },\n schema,\n nullable\n );\n }\n }\n\n // Mixed scalar types (e.g. [\"string\", \"number\"]) — emit empty schema since\n // JTD has no native union of primitives.\n if (nonNullTypes.length > 1) {\n return decorate<TMetadata>({}, schema, nullable);\n }\n\n // No type info — empty (any) schema, possibly nullable.\n return decorate<TMetadata>({}, schema, nullable);\n}\n\n/**\n * Shallow-merges two JSON Schema fragments, combining `required` arrays and `properties` maps.\n *\n * @param left - The base schema fragment.\n * @param right - The schema fragment to merge into the base.\n * @returns A merged schema fragment. Neither input is mutated.\n */\nfunction mergeJsonSchema(\n left: JsonSchemaLike,\n right: JsonSchemaLike\n): JsonSchemaLike {\n const merged: JsonSchemaLike = { ...left, ...right };\n if (left.properties || right.properties) {\n merged.properties = {\n ...(left.properties ?? {}),\n ...(right.properties ?? {})\n };\n }\n if (left.required || right.required) {\n merged.required = Array.from(\n new Set([...(left.required ?? []), ...(right.required ?? [])])\n );\n }\n return merged;\n}\n"],"mappings":";;;;;;;;;;AAsCA,SAAS,6BACP,QAC2B;CAC3B,QAAQ,QAAR;EACE,KAAK,QACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK,SACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,SACE;CACJ;AACF;;;;;;;AAQA,SAAS,4BACP,QAC2B;CAC3B,QAAQ,QAAR;EACE,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK;EACL,KAAK,WACH,OAAO;EACT,KAAK;EACL,SACE;CACJ;AACF;;;;;;;;AASA,SAAS,wBACP,SACA,SAC2B;CAC3B,IAAI,YAAY,UAAa,UAAU,GACrC;CAEF,IAAI,YAAY,QACd;CAEF,IAAI,WAAW,KACb,OAAO;CAET,IAAI,WAAW,OACb,OAAO;CAET,IAAI,WAAW,YACb,OAAO;AAGX;;;;;;;;AASA,SAAS,sBACP,SACA,SAC2B;CAC3B,IACE,YAAY,UACZ,YAAY,UACZ,WAAW,QACX,WAAW,KAEX,OAAO;CAET,IACE,YAAY,UACZ,YAAY,UACZ,WAAW,UACX,WAAW,OAEX,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,iBAAiB,OAA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,OAAO,SAAoB,EAAE,MAAM,UAAU,GAAG,QAAQ,QAAQ;EAElE,IAAI,MAAM,WACR,OAAO,SACL,EAAE,MAAM,mBAAmB,MAAM,EAAE,GACnC,QACA,QACF;EAEF,IAAI,MAAM,UACR,OAAO,SACL,EAAE,MAAM,kBAAkB,MAAM,EAAE,GAClC,QACA,QACF;CAEJ;CAIA,IAAI,aAAa,SAAS,GACxB,OAAO,SAAoB,CAAC,GAAG,QAAQ,QAAQ;CAIjD,OAAO,SAAoB,CAAC,GAAG,QAAQ,QAAQ;AACjD;;;;;;;;AASA,SAAS,gBACP,MACA,OACgB;CAChB,MAAM,SAAyB;EAAE,GAAG;EAAM,GAAG;CAAM;CACnD,IAAI,KAAK,cAAc,MAAM,YAC3B,OAAO,aAAa;EAClB,GAAI,KAAK,cAAc,CAAC;EACxB,GAAI,MAAM,cAAc,CAAC;CAC3B;CAEF,IAAI,KAAK,YAAY,MAAM,UACzB,OAAO,WAAW,MAAM,KACtB,IAAI,IAAI,CAAC,GAAI,KAAK,YAAY,CAAC,GAAI,GAAI,MAAM,YAAY,CAAC,CAAE,CAAC,CAC/D;CAEF,OAAO;AACT"}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_type_checks = require('./type-checks.cjs');
|
|
4
|
+
const require_extract = require('./extract.cjs');
|
|
5
|
+
let _stryke_path_join = require("@stryke/path/join");
|
|
6
|
+
|
|
7
|
+
//#region src/persistence.ts
|
|
8
|
+
/**
|
|
9
|
+
* A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
|
|
10
|
+
*
|
|
11
|
+
* @param context - The context object providing access to the cache path.
|
|
12
|
+
* @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
|
|
13
|
+
*/
|
|
14
|
+
function getCacheDirectory(context) {
|
|
15
|
+
return (0, _stryke_path_join.joinPaths)(context.cachePath, "schemas");
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
|
|
19
|
+
*
|
|
20
|
+
* @param context - The context object providing access to the cache path.
|
|
21
|
+
* @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
|
|
22
|
+
* @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
|
|
23
|
+
*/
|
|
24
|
+
function getCacheFilePath(context, input) {
|
|
25
|
+
const hash = require_extract.extractHash(require_extract.extractVariant(input), input);
|
|
26
|
+
return (0, _stryke_path_join.joinPaths)(getCacheDirectory(context), `${hash}.json`);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
|
|
30
|
+
*
|
|
31
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
32
|
+
* @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
|
|
33
|
+
* @throws Will throw an error if the provided input is not a valid schema.
|
|
34
|
+
*/
|
|
35
|
+
async function writeSchema(context, schema) {
|
|
36
|
+
if (!require_type_checks.isSchema(schema)) throw new Error(`The provided input is not a valid schema. A valid schema must have a "variant" property indicating the type of the input and a "schema" property containing the parsed JTD schema object.`);
|
|
37
|
+
await context.fs.write(getCacheFilePath(context, schema), JSON.stringify(schema.schema));
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
|
|
41
|
+
*
|
|
42
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
43
|
+
* @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
|
|
44
|
+
* @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
|
|
45
|
+
*/
|
|
46
|
+
async function readSchemaSafe(context, input) {
|
|
47
|
+
const cacheFilePath = getCacheFilePath(context, input);
|
|
48
|
+
if (!await context.fs.exists(cacheFilePath)) return;
|
|
49
|
+
const data = await context.fs.read(cacheFilePath);
|
|
50
|
+
if (!data) return;
|
|
51
|
+
return JSON.parse(data);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
|
|
55
|
+
*
|
|
56
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
57
|
+
* @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
|
|
58
|
+
* @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
|
|
59
|
+
* @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
|
|
60
|
+
*/
|
|
61
|
+
async function readSchema(context, input) {
|
|
62
|
+
const schema = await readSchemaSafe(context, input);
|
|
63
|
+
if (!schema) {
|
|
64
|
+
const variant = require_extract.extractVariant(input);
|
|
65
|
+
const hash = require_extract.extractHash(variant, input);
|
|
66
|
+
throw new Error(`The ${variant} schema with hash "${hash}" does not exist in the cache. This may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. Please ensure that the schema is properly written to the cache before attempting to read it.`);
|
|
67
|
+
}
|
|
68
|
+
return schema;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//#endregion
|
|
72
|
+
exports.getCacheDirectory = getCacheDirectory;
|
|
73
|
+
exports.getCacheFilePath = getCacheFilePath;
|
|
74
|
+
exports.readSchema = readSchema;
|
|
75
|
+
exports.readSchemaSafe = readSchemaSafe;
|
|
76
|
+
exports.writeSchema = writeSchema;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { Schema, SchemaInput, SchemaMetadata } from "./types.cjs";
|
|
2
|
+
import { Context } from "@powerlines/core";
|
|
3
|
+
|
|
4
|
+
//#region src/persistence.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
|
|
7
|
+
*
|
|
8
|
+
* @param context - The context object providing access to the cache path.
|
|
9
|
+
* @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
|
|
10
|
+
*/
|
|
11
|
+
declare function getCacheDirectory(context: Context): string;
|
|
12
|
+
/**
|
|
13
|
+
* A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
|
|
14
|
+
*
|
|
15
|
+
* @param context - The context object providing access to the cache path.
|
|
16
|
+
* @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
|
|
17
|
+
* @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
|
|
18
|
+
*/
|
|
19
|
+
declare function getCacheFilePath(context: Context, input: SchemaInput): string;
|
|
20
|
+
/**
|
|
21
|
+
* Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
|
|
22
|
+
*
|
|
23
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
24
|
+
* @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
|
|
25
|
+
* @throws Will throw an error if the provided input is not a valid schema.
|
|
26
|
+
*/
|
|
27
|
+
declare function writeSchema<TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>, TContext extends Context = Context>(context: TContext, schema: Schema<TMetadata>): Promise<void>;
|
|
28
|
+
/**
|
|
29
|
+
* A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
|
|
30
|
+
*
|
|
31
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
32
|
+
* @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
|
|
33
|
+
* @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
|
|
34
|
+
*/
|
|
35
|
+
declare function readSchemaSafe<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata> | undefined>;
|
|
36
|
+
/**
|
|
37
|
+
* Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
|
|
38
|
+
*
|
|
39
|
+
* @param context - The context object providing access to the file system and cache path.
|
|
40
|
+
* @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
|
|
41
|
+
* @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
|
|
42
|
+
* @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
|
|
43
|
+
*/
|
|
44
|
+
declare function readSchema<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata>>;
|
|
45
|
+
//#endregion
|
|
46
|
+
export { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema };
|
|
47
|
+
//# sourceMappingURL=persistence.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"persistence.d.cts","names":[],"sources":["../src/persistence.ts"],"mappings":";;;;;;AA8BA;;;;iBAAgB,iBAAA,CAAkB,OAAgB,EAAP,OAAO;AAWlD;;;;;;;AAAA,iBAAgB,gBAAA,CAAiB,OAAA,EAAS,OAAA,EAAS,KAAA,EAAO,WAAW;;AAAA;AAcrE;;;;;iBAAsB,WAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAC3B,OAAA,EAAS,QAAA,EAAU,MAAA,EAAQ,MAAA,CAAO,SAAA,IAAU,OAAA;;;;;;;;iBAoBxB,cAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CAEnC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,GACN,OAAA,CAAQ,MAAA,CAAO,SAAA;;;;;;;;;iBAsBI,UAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CACnC,OAAA,EAAS,QAAA,EAAU,KAAA,EAAO,WAAA,GAAc,OAAA,CAAQ,MAAA,CAAO,SAAA"}
|