@powerlines/schema 0.11.77 → 0.11.78

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/index.mjs CHANGED
@@ -1027,7 +1027,7 @@ function stringifyType(schema) {
1027
1027
  }
1028
1028
  if (objectSchema.type === "array" && Array.isArray(objectSchema.enum)) return objectSchema.enum.map((value) => JSON.stringify(value)).join(" | ");
1029
1029
  if (objectSchema.const !== void 0) return JSON.stringify(objectSchema.const);
1030
- if (objectSchema.type === "array" || objectSchema.items) return `${stringifyType(objectSchema.items)}[]`;
1030
+ if (objectSchema.type === "array" || objectSchema.items) return `${stringifyType(Array.isArray(objectSchema.items) ? objectSchema.items[0] : objectSchema.items)}[]`;
1031
1031
  if (objectSchema.type === "object" || objectSchema.properties || objectSchema.additionalProperties) {
1032
1032
  if (isJsonSchema(objectSchema.additionalProperties)) return `{ [key: string]: ${stringifyType(objectSchema.additionalProperties)} }`;
1033
1033
  if (isJsonSchemaObject(objectSchema)) {
@@ -1052,10 +1052,262 @@ function getJsonSchemaType(value) {
1052
1052
  return isNull$1(value) ? "null" : isBoolean$1(value) ? "boolean" : isInteger(value) ? "integer" : isNumber$1(value) ? "number" : isString(value) ? "string" : isObject(value) ? "object" : Array.isArray(value) ? "array" : void 0;
1053
1053
  }
1054
1054
  /**
1055
+ * Resolves a local JSON Schema `$ref` (e.g. `#/$defs/Name`) to the referenced definition name.
1056
+ */
1057
+ function resolveLocalRefName(ref) {
1058
+ return /^#\/(?:definitions|\$defs)\/(.+)$/.exec(ref)?.[1];
1059
+ }
1060
+ /**
1061
+ * Converts an arbitrary definition name into a safe JavaScript identifier suffix.
1062
+ */
1063
+ function toParserIdentifier(name) {
1064
+ const cleaned = name.replace(/[^\w$]/gu, "_");
1065
+ return `parse_${/^\d/u.test(cleaned) ? `_${cleaned}` : cleaned}`;
1066
+ }
1067
+ /**
1068
+ * Returns the list of JSON Schema `type` keyword values declared on a fragment,
1069
+ * preserving `object` and `array` (which {@link readSchemaTypes} intentionally drops).
1070
+ */
1071
+ function readDeclaredTypes(schema) {
1072
+ const type = schema.type;
1073
+ if (Array.isArray(type)) return [...type];
1074
+ return type ? [type] : [];
1075
+ }
1076
+ /**
1077
+ * Generates a JavaScript expression that builds a path string for a child element.
1078
+ */
1079
+ function childPath(pathExpr, segment) {
1080
+ return `${pathExpr} + ${JSON.stringify(segment)}`;
1081
+ }
1082
+ /**
1083
+ * Generates standalone parser code for a JSON Schema.
1084
+ *
1085
+ * @remarks
1086
+ * The generated `parse` function reads an arbitrary input value and converts it
1087
+ * into the shape described by the schema. It walks the schema recursively to:
1088
+ *
1089
+ * - resolve local `$ref` pointers (`#/$defs/*` and `#/definitions/*`) into
1090
+ * dedicated parser functions so recursive schemas are supported,
1091
+ * - apply `default` values for object properties (and root/array values) that
1092
+ * are missing from the input,
1093
+ * - coerce primitive values to the declared type (for example `"42"` to `42`
1094
+ * for an `integer` schema, or `1` to `true` for a `boolean` schema),
1095
+ * - validate `const`, `enum`, `oneOf`/`anyOf` and `allOf` constraints, and
1096
+ * - collect detailed, path-aware errors and throw a `ParserError` when the
1097
+ * input cannot be converted into a valid value.
1098
+ *
1099
+ * @param schema - The JSON Schema to generate parser code for.
1100
+ * @returns The generated standalone parser code as a string.
1101
+ */
1102
+ function generateParserCode(schema) {
1103
+ const rootSchema = typeof schema === "boolean" ? schema : schema;
1104
+ const definitions = typeof rootSchema === "boolean" ? {} : {
1105
+ ...rootSchema.definitions,
1106
+ ...rootSchema.$defs
1107
+ };
1108
+ /**
1109
+ * Generates a JavaScript expression that parses `valueExpr` against `fragment`.
1110
+ * The expression has access to an in-scope mutable `errors` array.
1111
+ */
1112
+ function generateExpression(fragment, valueExpr, pathExpr) {
1113
+ if (typeof fragment === "boolean") return fragment ? valueExpr : `((value, path) => { errors.push({ path, message: "No value is allowed at this location" }); return value; })(${valueExpr}, ${pathExpr})`;
1114
+ const view = fragment;
1115
+ if (isSetString$1(view.$ref)) {
1116
+ const refName = resolveLocalRefName(view.$ref);
1117
+ if (refName && refName in definitions) return `${toParserIdentifier(refName)}(${valueExpr}, ${pathExpr}, errors)`;
1118
+ return valueExpr;
1119
+ }
1120
+ return `((value, path) => {\n${generateBody(view)}\n})(${valueExpr}, ${pathExpr})`;
1121
+ }
1122
+ /**
1123
+ * Generates the body statements (including a terminating `return`) for the
1124
+ * arrow function produced by {@link generateExpression}.
1125
+ */
1126
+ function generateBody(view) {
1127
+ const lines = [];
1128
+ const nullable = isSchemaNullable(view);
1129
+ if (view.default !== void 0) lines.push(`if (value === undefined) { return ${JSON.stringify(view.default)}; }`);
1130
+ else lines.push(`if (value === undefined) { errors.push({ path, message: "A value is required" }); return value; }`);
1131
+ if (nullable) lines.push(`if (value === null) { return null; }`);
1132
+ if (view.const !== void 0) {
1133
+ const constValue = JSON.stringify(view.const);
1134
+ lines.push(`if (JSON.stringify(value) !== ${JSON.stringify(constValue)}) { errors.push({ path, message: "Expected the constant value " + ${JSON.stringify(constValue)} }); }`, `return ${constValue};`);
1135
+ return lines.join("\n");
1136
+ }
1137
+ if (Array.isArray(view.enum)) {
1138
+ const enumValues = JSON.stringify(view.enum);
1139
+ lines.push(`if (!${enumValues}.some(allowed => JSON.stringify(allowed) === JSON.stringify(value))) { errors.push({ path, message: "Expected one of " + ${JSON.stringify(enumValues)} }); }`, `return value;`);
1140
+ return lines.join("\n");
1141
+ }
1142
+ if (Array.isArray(view.oneOf) || Array.isArray(view.anyOf)) {
1143
+ const branchFns = (view.oneOf ?? view.anyOf ?? []).map((branch) => `(value, path, errors) => (${generateExpression(branch, "value", "path")})`).join(",\n");
1144
+ lines.push(`const branches = [\n${branchFns}\n];`, `for (const branch of branches) {`, ` const branchErrors = [];`, ` const branchResult = branch(value, path, branchErrors);`, ` if (branchErrors.length === 0) { return branchResult; }`, `}`, `errors.push({ path, message: "Value does not match any of the allowed schemas" });`, `return value;`);
1145
+ return lines.join("\n");
1146
+ }
1147
+ if (Array.isArray(view.allOf)) {
1148
+ const { allOf, ...rest } = view;
1149
+ const merged = merge(rest, ...allOf);
1150
+ lines.push(`return ${generateExpression(merged, "value", "path")};`);
1151
+ return lines.join("\n");
1152
+ }
1153
+ const declaredTypes = readDeclaredTypes(view);
1154
+ switch (getPrimarySchemaType(view) ?? declaredTypes.find((type) => type !== "null") ?? (view.properties ? "object" : view.items ? "array" : void 0)) {
1155
+ case "object":
1156
+ lines.push(generateObjectBody(view));
1157
+ break;
1158
+ case "array":
1159
+ lines.push(generateArrayBody(view));
1160
+ break;
1161
+ case "string":
1162
+ lines.push(`if (typeof value === "string") { return value; }`, `if (typeof value === "number" || typeof value === "boolean") { return String(value); }`, `errors.push({ path, message: "Expected a string value" });`, `return value;`);
1163
+ break;
1164
+ case "integer":
1165
+ lines.push(`if (typeof value === "number" && Number.isInteger(value)) { return value; }`, `if (typeof value === "string" && value.trim() !== "" && Number.isInteger(Number(value))) { return Number(value); }`, `if (typeof value === "boolean") { return value ? 1 : 0; }`, `errors.push({ path, message: "Expected an integer value" });`, `return value;`);
1166
+ break;
1167
+ case "number":
1168
+ lines.push(`if (typeof value === "number") { return value; }`, `if (typeof value === "string" && value.trim() !== "" && !Number.isNaN(Number(value))) { return Number(value); }`, `if (typeof value === "boolean") { return value ? 1 : 0; }`, `errors.push({ path, message: "Expected a number value" });`, `return value;`);
1169
+ break;
1170
+ case "boolean":
1171
+ lines.push(`if (typeof value === "boolean") { return value; }`, `if (value === "true" || value === 1) { return true; }`, `if (value === "false" || value === 0) { return false; }`, `errors.push({ path, message: "Expected a boolean value" });`, `return value;`);
1172
+ break;
1173
+ case "null":
1174
+ lines.push(`if (value === null) { return null; }`, `errors.push({ path, message: "Expected a null value" });`, `return value;`);
1175
+ break;
1176
+ case void 0:
1177
+ default:
1178
+ lines.push(`return value;`);
1179
+ break;
1180
+ }
1181
+ return lines.join("\n");
1182
+ }
1183
+ /**
1184
+ * Generates the parsing statements for an `object` schema, applying property
1185
+ * defaults and recursing into each declared property.
1186
+ */
1187
+ function generateObjectBody(view) {
1188
+ const lines = [`if (typeof value !== "object" || value === null || Array.isArray(value)) { errors.push({ path, message: "Expected an object value" }); return value; }`, `const result = {};`];
1189
+ const properties = isJsonSchemaObject(view) ? getPropertiesList(view) : [];
1190
+ const propertyNames = /* @__PURE__ */ new Set();
1191
+ for (const property of properties) {
1192
+ const name = property.name;
1193
+ propertyNames.add(name);
1194
+ const accessor = `value[${JSON.stringify(name)}]`;
1195
+ const propertyPath = childPath("path", `.${name}`);
1196
+ const propertyExpression = generateExpression(property, accessor, propertyPath);
1197
+ const missingBranch = property.default !== void 0 ? `result[${JSON.stringify(name)}] = ${JSON.stringify(property.default)};` : property.required ? `errors.push({ path: ${propertyPath}, message: "Required property is missing" });` : ``;
1198
+ lines.push(`if (${accessor} !== undefined) {`, ` result[${JSON.stringify(name)}] = ${propertyExpression};`, `}${missingBranch ? ` else { ${missingBranch} }` : ``}`);
1199
+ }
1200
+ const additional = view.additionalProperties;
1201
+ if (isJsonSchema(additional)) {
1202
+ const additionalExpression = generateExpression(additional, `value[key]`, `path + "." + key`);
1203
+ lines.push(`for (const key of Object.keys(value)) {`, ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`, ` result[key] = ${additionalExpression};`, `}`);
1204
+ } else if (additional !== false) lines.push(`for (const key of Object.keys(value)) {`, ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`, ` result[key] = value[key];`, `}`);
1205
+ lines.push(`return result;`);
1206
+ return lines.join("\n");
1207
+ }
1208
+ /**
1209
+ * Generates the parsing statements for an `array` schema, recursing into each
1210
+ * item (supporting both list and tuple `items`/`prefixItems` forms).
1211
+ */
1212
+ function generateArrayBody(view) {
1213
+ const lines = [`if (!Array.isArray(value)) { errors.push({ path, message: "Expected an array value" }); return value; }`];
1214
+ const tupleItems = view.prefixItems ?? (Array.isArray(view.items) ? view.items : void 0);
1215
+ if (tupleItems) {
1216
+ const listItems = !Array.isArray(view.items) ? view.items : void 0;
1217
+ const itemExpressions = tupleItems.map((item, index) => `index === ${index} ? (${generateExpression(item, "item", childPath("path", `[${index}]`))})`);
1218
+ const fallbackExpression = listItems ? generateExpression(listItems, "item", `path + "[" + index + "]"`) : "item";
1219
+ lines.push(`return value.map((item, index) => ${itemExpressions.join(" : ")}${itemExpressions.length > 0 ? " : " : ""}${fallbackExpression});`);
1220
+ return lines.join("\n");
1221
+ }
1222
+ const itemExpression = generateExpression(view.items ?? true, "item", `path + "[" + index + "]"`);
1223
+ lines.push(`return value.map((item, index) => ${itemExpression});`);
1224
+ return lines.join("\n");
1225
+ }
1226
+ const parserFunctions = Object.entries(definitions).map(([name, definition]) => `function ${toParserIdentifier(name)}(value, path, errors) {\n return ${generateExpression(definition, "value", "path")};\n}`);
1227
+ const rootExpression = generateExpression(schema, "value", "\"$\"");
1228
+ return `/**
1229
+ * Error thrown when an input value cannot be parsed into the type described by the JSON Schema.
1230
+ */
1231
+ export class ParserError extends Error {
1232
+ constructor(errors) {
1233
+ super(
1234
+ "Failed to parse the provided value against the JSON Schema:\\n" +
1235
+ errors.map(error => " - " + error.path + ": " + error.message).join("\\n")
1236
+ );
1237
+
1238
+ this.name = "ParserError";
1239
+ this.errors = errors;
1240
+ }
1241
+ }
1242
+
1243
+ ${parserFunctions.join("\n\n")}
1244
+
1245
+ /**
1246
+ * Parses an input value into the type described by the JSON Schema.
1247
+ *
1248
+ * @remarks
1249
+ * The parser applies default values for missing properties, coerces primitive
1250
+ * values to the declared type, and throws a {@link ParserError} (containing
1251
+ * a detailed list of validation errors) when the value cannot be converted into
1252
+ * a valid result.
1253
+ *
1254
+ * @param value - The input value to parse.
1255
+ * @returns The parsed value conforming to the schema.
1256
+ */
1257
+ export function parse(value) {
1258
+ const errors = [];
1259
+ const result = ${rootExpression};
1260
+ if (errors.length > 0) {
1261
+ throw new ParserError(errors);
1262
+ }
1263
+
1264
+ return result;
1265
+ }`;
1266
+ }
1267
+ /**
1055
1268
  * Generates standalone JSON Schema validation code using Ajv.
1269
+ *
1270
+ * @remarks
1271
+ * The generated code includes a validation function that can be used to validate data against the provided JSON Schema at runtime. The validation function will throw an error if the data does not conform to the schema, providing detailed information about the validation errors.
1272
+ *
1273
+ * @param schema - The JSON Schema to generate validation code for.
1274
+ * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.
1275
+ * @returns The generated standalone validation code as a string.
1276
+ */
1277
+ function generateValidationCode(schema, refsOrFuncts) {
1278
+ return standaloneCode(getValidator(schema), refsOrFuncts);
1279
+ }
1280
+ /**
1281
+ * Generates standalone JavaScript code for validating and parsing data according to a JSON Schema.
1282
+ *
1283
+ * @remarks
1284
+ * The generated code includes:
1285
+ * - Validation code generated by Ajv for the provided JSON Schema, which can be used to validate data against the schema at runtime. The validation function will throw an error if the data does not conform to the schema, providing detailed information about the validation errors.
1286
+ * - Parsing code generated for the provided JSON Schema, which can be used to parse and validate data against the schema at runtime. The parsing function will apply default values specified in the schema if they are not present in the input data, throw an error if the input data does not conform to the schema (providing detailed information about the validation errors), and return the parsed data if it is valid according to the schema.
1287
+ *
1288
+ * @param schema - The JSON Schema to generate code for.
1289
+ * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.
1290
+ * @returns The generated standalone validation and parsing code as a string.
1056
1291
  */
1057
- async function generateCode(schemas, refsOrFuncts) {
1058
- return standaloneCode(getValidator(schemas), refsOrFuncts);
1292
+ function generateCode(schema, refsOrFuncts) {
1293
+ return `
1294
+ /**
1295
+ * Validation code generated by Ajv for the provided JSON Schema. This code can be used to validate data against the schema at runtime. The validation function will throw an error if the data does not conform to the schema, providing detailed information about the validation errors.
1296
+ *
1297
+ * @see https://ajv.js.org/standalone.html
1298
+ */
1299
+
1300
+ ${generateValidationCode(schema, refsOrFuncts)}
1301
+
1302
+ /**
1303
+ * Parsing code generated for the provided JSON Schema. This code can be used to parse and validate data against the schema at runtime. The parsing function will do the following:
1304
+ * - Apply default values specified in the schema if they are not present in the input data
1305
+ * - Throw an error if the input data does not conform to the schema, providing detailed information about the validation errors
1306
+ * - Return the parsed data if it is valid according to the schema
1307
+ */
1308
+
1309
+ ${generateParserCode(schema)}
1310
+ `;
1059
1311
  }
1060
1312
 
1061
1313
  //#endregion
@@ -2080,5 +2332,5 @@ async function extract(context, input, options = {}) {
2080
2332
  }
2081
2333
 
2082
2334
  //#endregion
2083
- export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, VALID_SOURCE_FILE_EXTENSIONS, addProperty, applyJsonSchemaMetadata, bundle, bundleReferences, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getJsonSchema, getJsonSchemaObject, getJsonSchemaType, getPrimarySchemaType, getProperties, getPropertiesList, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isPropertyOptional, isSchema, isSchemaNullable, isSchemaObject, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema, isValidSchemaInputFile, merge, readSchema, readSchemaSafe, readSchemaTypes, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
2335
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, VALID_SOURCE_FILE_EXTENSIONS, addProperty, applyJsonSchemaMetadata, bundle, bundleReferences, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractVariant, generateCode, generateParserCode, generateValidationCode, getCacheDirectory, getCacheFilePath, getJsonSchema, getJsonSchemaObject, getJsonSchemaType, getPrimarySchemaType, getProperties, getPropertiesList, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isPropertyOptional, isSchema, isSchemaNullable, isSchemaObject, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema, isValidSchemaInputFile, merge, readSchema, readSchemaSafe, readSchemaTypes, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
2084
2336
  //# sourceMappingURL=index.mjs.map