@powerlines/schema 0.11.86 → 0.11.88
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.mjs +1 -1
- package/dist/codegen.mjs.map +1 -1
- package/dist/resolve.cjs +1 -1
- package/dist/resolve.d.cts.map +1 -1
- package/dist/resolve.d.mts.map +1 -1
- package/dist/resolve.mjs +1 -1
- package/dist/resolve.mjs.map +1 -1
- package/package.json +5 -5
package/dist/codegen.cjs
CHANGED
package/dist/codegen.mjs
CHANGED
package/dist/codegen.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.mjs","names":["isUndefined","isNull","isBoolean","isNumber","isSetString"],"sources":["../src/codegen.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 { toBool } from \"@stryke/convert/to-bool\";\nimport { camelCase } from \"@stryke/string-format/camel-case\";\nimport { isInteger, isObject, isString } from \"@stryke/type-checks\";\nimport { isBoolean } from \"@stryke/type-checks/is-boolean\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isUndefined } from \"@stryke/type-checks/is-undefined\";\nimport standaloneCode from \"ajv/dist/standalone\";\nimport { getPropertiesList, isSchemaNullable, merge } from \"./helpers\";\nimport { getPrimarySchemaType } from \"./metadata\";\nimport { isJsonSchema, isJsonSchemaObject } from \"./type-checks\";\nimport { JsonSchema, JsonSchemaLike, JsonSchemaType } from \"./types\";\nimport { getValidator } from \"./validate\";\n\n/**\n * Stringifies a value for generated TypeScript code.\n */\nexport function stringifyValue(\n value?: unknown,\n type?: JsonSchemaType | string\n): string {\n return isUndefined(value)\n ? \"undefined\"\n : isNull(value)\n ? \"null\"\n : type === \"boolean\" || isBoolean(value)\n ? String(toBool(value))\n : type === \"number\" || isNumber(value)\n ? Number.parseFloat(String(value)).toLocaleString(undefined, {\n maximumFractionDigits: 20\n })\n : type === \"integer\"\n ? Number.parseInt(String(value)).toLocaleString()\n : type === \"string\" || type === \"object\" || type === \"array\"\n ? JSON.stringify(value)\n : String(value);\n}\n\n/**\n * Stringifies a JSON Schema fragment into a TypeScript-like type string.\n */\nexport function stringifyType(schema?: JsonSchema): string {\n if (!schema) {\n return \"unknown\";\n }\n\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n if (isJsonSchemaObject(schema) && isSetString(schema.name)) {\n return schema.name;\n }\n\n const objectSchema = schema as JsonSchemaLike;\n\n if (isSetString(objectSchema.$ref)) {\n const match = /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(objectSchema.$ref);\n\n return match?.[1] ?? objectSchema.$ref;\n }\n\n const primaryType = getPrimarySchemaType(schema);\n if (primaryType) {\n if (primaryType === \"integer\" || primaryType === \"number\") {\n return \"number\";\n }\n\n return primaryType;\n }\n\n if (objectSchema.type === \"array\" && Array.isArray(objectSchema.enum)) {\n const enumValues = objectSchema.enum as readonly unknown[];\n\n return enumValues\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \");\n }\n\n if (objectSchema.const !== undefined) {\n return JSON.stringify(objectSchema.const);\n }\n\n if (objectSchema.type === \"array\" || objectSchema.items) {\n const items = Array.isArray(objectSchema.items)\n ? objectSchema.items[0]\n : objectSchema.items;\n\n return `${stringifyType(items)}[]`;\n }\n\n if (\n objectSchema.type === \"object\" ||\n objectSchema.properties ||\n objectSchema.additionalProperties\n ) {\n if (isJsonSchema(objectSchema.additionalProperties)) {\n return `{ [key: string]: ${stringifyType(objectSchema.additionalProperties)} }`;\n }\n\n if (isJsonSchemaObject(objectSchema)) {\n const required = objectSchema.required ?? [];\n\n return `{ ${getPropertiesList(objectSchema)\n .map(property => {\n const suffix =\n !required.includes(property.name) || isSchemaNullable(property)\n ? `${!required.includes(property.name) ? \"?\" : \"\"}${isSchemaNullable(property) ? \" | null\" : \"\"}`\n : \"\";\n\n return `${property.name}${suffix}: ${stringifyType(property)}`;\n })\n .join(\";\\n\")} }`;\n }\n }\n\n if (objectSchema.oneOf || objectSchema.anyOf) {\n return (objectSchema.oneOf ?? objectSchema.anyOf ?? [])\n .map(branch => stringifyType(branch))\n .join(\" | \");\n }\n\n if (objectSchema.allOf) {\n return \"object\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Returns a string type representation of a value based on its type and an optional JSON Schema primitive type hint.\n *\n * @param value - The value whose type is to be represented as a string.\n * @returns A string representation of the value's type, which may be influenced by the provided JSON Schema primitive type hint. The function handles various JavaScript types and formats them accordingly, including special handling for `undefined`, `null`, booleans, numbers (with formatting), strings, objects, and arrays. If a specific type hint is provided, it will take precedence in determining the string representation of the value.\n */\nexport function getJsonSchemaType(value?: unknown): JsonSchemaType | undefined {\n return isNull(value)\n ? \"null\"\n : isBoolean(value)\n ? \"boolean\"\n : isInteger(value)\n ? \"integer\"\n : isNumber(value)\n ? \"number\"\n : isString(value)\n ? \"string\"\n : isObject(value)\n ? \"object\"\n : Array.isArray(value)\n ? \"array\"\n : undefined;\n}\n\n/**\n * Resolves a local JSON Schema `$ref` (e.g. `#/$defs/Name`) to the referenced definition name.\n */\nfunction resolveLocalRefName(ref: string): string | undefined {\n return /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(ref)?.[1];\n}\n\n/**\n * Converts an arbitrary definition name into a safe JavaScript identifier suffix.\n */\nfunction toParserIdentifier(name: string): string {\n const cleaned = name.replace(/[^\\w$]/gu, \"_\");\n\n return `parse_${/^\\d/u.test(cleaned) ? `_${cleaned}` : cleaned}`;\n}\n\n/**\n * Returns the list of JSON Schema `type` keyword values declared on a fragment,\n * preserving `object` and `array` (which {@link readSchemaTypes} intentionally drops).\n */\nfunction readDeclaredTypes(schema: JsonSchemaLike): JsonSchemaType[] {\n const type = schema.type;\n if (Array.isArray(type)) {\n return [...type];\n }\n\n return type ? [type] : [];\n}\n\n/**\n * Generates a JavaScript expression that builds a path string for a child element.\n */\nfunction childPath(pathExpr: string, segment: string): string {\n return `${pathExpr} + ${JSON.stringify(segment)}`;\n}\n\n/**\n * Generates standalone parser code for a JSON Schema.\n *\n * @remarks\n * The generated `parse` function reads an arbitrary input value and converts it\n * into the shape described by the schema. It walks the schema recursively to:\n *\n * - resolve local `$ref` pointers (`#/$defs/*` and `#/definitions/*`) into\n * dedicated parser functions so recursive schemas are supported,\n * - apply `default` values for object properties (and root/array values) that\n * are missing from the input,\n * - coerce primitive values to the declared type (for example `\"42\"` to `42`\n * for an `integer` schema, or `1` to `true` for a `boolean` schema),\n * - validate `const`, `enum`, `oneOf`/`anyOf` and `allOf` constraints, and\n * - collect detailed, path-aware errors and throw a `ParserError` when the\n * input cannot be converted into a valid value.\n *\n * @param schema - The JSON Schema to generate parser code for.\n * @returns The generated standalone parser code as a string.\n */\nexport function generateParserCode(schema: JsonSchema): string {\n const rootSchema =\n typeof schema === \"boolean\" ? schema : (schema as JsonSchemaLike);\n\n const definitions: Record<string, JsonSchema> =\n typeof rootSchema === \"boolean\"\n ? {}\n : {\n ...(\n rootSchema as {\n definitions?: Record<string, JsonSchema>;\n }\n ).definitions,\n ...rootSchema.$defs\n };\n\n const tempCounter = {} as Record<string, number>;\n function nextTemp(prefix: string): string {\n const id = tempCounter[prefix] ?? 0;\n tempCounter[prefix] = id + 1;\n\n return `${prefix}${id > 0 ? `${id}` : \"\"}`;\n }\n\n /**\n * Generates inline parsing statements for a schema fragment.\n */\n function generateStatements(\n fragment: JsonSchemaLike,\n valueExpr: string,\n pathExpr: string,\n targetVar: string,\n errorsVar = \"errors\"\n ): string[] {\n if (typeof fragment === \"boolean\") {\n return fragment\n ? [`${targetVar} = ${valueExpr};`]\n : [\n `${errorsVar}.push({ path: ${pathExpr}, message: \"No value is allowed at this location\" });`,\n `${targetVar} = ${valueExpr};`\n ];\n }\n\n if (isSetString(fragment.$ref)) {\n const refName = resolveLocalRefName(fragment.$ref);\n if (refName && refName in definitions) {\n return [\n `${targetVar} = ${toParserIdentifier(refName)}(${valueExpr}, ${pathExpr}, ${errorsVar});`\n ];\n }\n\n // Unknown / external reference — pass the value through unchanged.\n return [`${targetVar} = ${valueExpr};`];\n }\n\n const valueVar = nextTemp(\n fragment.name ? `${camelCase(fragment.name)}Value` : \"value\"\n );\n const pathVar = nextTemp(\n fragment.name ? `${camelCase(fragment.name)}Path` : \"path\"\n );\n const lines: string[] = [\n `const ${valueVar} = ${valueExpr};`,\n `const ${pathVar} = ${pathExpr};`\n ];\n\n if (fragment.default !== undefined) {\n lines.push(\n `if (${valueVar} === undefined) {`,\n ` ${targetVar} = ${JSON.stringify(fragment.default)};`,\n `} else {`\n );\n\n if (isSchemaNullable(fragment)) {\n lines.push(\n ` if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n ` } else {`\n );\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n lines.push(` }`);\n } else {\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n }\n\n lines.push(`}`);\n\n return lines;\n }\n\n lines.push(\n `if (${valueVar} === undefined) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"A value is required\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n );\n\n if (isSchemaNullable(fragment)) {\n lines.push(\n ` if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n ` } else {`\n );\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n lines.push(` }`);\n } else {\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n }\n\n lines.push(`}`);\n\n return lines;\n }\n\n /**\n * Generates inline parsing statements assuming `value` is already defined.\n */\n function generateCoreStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const lines: string[] = [];\n\n if (view.const !== undefined) {\n const constValue = JSON.stringify(view.const);\n lines.push(\n `if (JSON.stringify(${valueVar}) !== ${constValue}) { ${\n errorsVar\n }.push({ path: ${pathVar}, message: \"Expected the constant value \" + ${\n constValue\n } }); }`,\n `${targetVar} = ${constValue};`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.enum)) {\n const enumValues = JSON.stringify(view.enum);\n lines.push(\n `if (!${enumValues}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${\n valueVar\n }))) { ${errorsVar}.push({ path: ${\n pathVar\n }, message: \"Expected one of \" + ${enumValues} }); }`,\n `${targetVar} = ${valueVar};`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.oneOf) || Array.isArray(view.anyOf)) {\n const branches = view.oneOf ?? view.anyOf ?? [];\n const matchedVar = nextTemp(\n view.name ? `${camelCase(view.name)}Matched` : \"matched\"\n );\n\n lines.push(`let ${matchedVar} = false;`);\n\n for (const branch of branches) {\n const branchErrorsVar = nextTemp(\n view.name ? `${camelCase(view.name)}BranchErrors` : \"branchErrors\"\n );\n const branchResultVar = nextTemp(\n view.name ? `${camelCase(view.name)}BranchResult` : \"branchResult\"\n );\n\n lines.push(`if (!${matchedVar}) {`);\n lines.push(\n ` const ${branchErrorsVar}: { path: string; message: string }[] = [];`,\n ` let ${branchResultVar};`\n );\n lines.push(\n ...generateStatements(\n branch,\n valueVar,\n pathVar,\n branchResultVar,\n branchErrorsVar\n )\n );\n lines.push(\n ` if (${branchErrorsVar}.length === 0) {`,\n ` ${targetVar} = ${branchResultVar};`,\n ` ${matchedVar} = true;`,\n ` }`,\n `}`\n );\n }\n\n lines.push(\n `if (!${matchedVar}) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Value does not match any of the allowed schemas\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.allOf)) {\n const { allOf, ...rest } = view;\n const merged = merge(rest, ...allOf);\n lines.push(\n ...generateStatements(merged, valueVar, pathVar, targetVar, errorsVar)\n );\n\n return lines;\n }\n\n const declaredTypes = readDeclaredTypes(view);\n const primaryType =\n getPrimarySchemaType(view) ??\n declaredTypes.find(type => type !== \"null\") ??\n (view.properties ? \"object\" : view.items ? \"array\" : undefined);\n\n switch (primaryType) {\n case \"object\":\n lines.push(\n ...generateObjectStatements(\n view,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n break;\n case \"array\":\n lines.push(\n ...generateArrayStatements(\n view,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n break;\n case \"string\":\n lines.push(\n `if (typeof ${valueVar} === \"string\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"number\" || typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = String(${valueVar});`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a string value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"integer\":\n lines.push(\n `if (typeof ${valueVar} === \"number\" && Number.isInteger(${valueVar})) {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"string\" && ${valueVar}.trim() !== \"\" && Number.isInteger(Number(${valueVar}))) {`,\n ` ${targetVar} = Number(${valueVar});`,\n `} else if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar} ? 1 : 0;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an integer value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"number\":\n lines.push(\n `if (typeof ${valueVar} === \"number\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"string\" && ${valueVar}.trim() !== \"\" && !Number.isNaN(Number(${valueVar}))) {`,\n ` ${targetVar} = Number(${valueVar});`,\n `} else if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar} ? 1 : 0;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a number value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"boolean\":\n lines.push(\n `if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (${valueVar} === \"true\" || ${valueVar} === 1) {`,\n ` ${targetVar} = true;`,\n `} else if (${valueVar} === \"false\" || ${valueVar} === 0) {`,\n ` ${targetVar} = false;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a boolean value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"null\":\n lines.push(\n `if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a null value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case undefined:\n default:\n lines.push(`${targetVar} = ${valueVar};`);\n break;\n }\n\n return lines;\n }\n\n /**\n * Generates the parsing statements for an `object` schema, applying property\n * defaults and recursing into each declared property.\n */\n function generateObjectStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const type = stringifyType(view);\n\n const lines: string[] = [\n `if (typeof ${valueVar} !== \"object\" || ${valueVar} === null || Array.isArray(${valueVar})) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an object value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n ];\n\n const resultVar = nextTemp(\n type || view.name ? `${camelCase(type || view.name)}Schema` : \"schema\"\n );\n lines.push(`const ${resultVar} = {} as Record<string, any>`);\n\n const properties = isJsonSchemaObject(view) ? getPropertiesList(view) : [];\n const propertyNames = new Set<string>();\n\n for (const property of properties) {\n const name = property.name;\n propertyNames.add(name);\n\n const accessor = property.alias?.length\n ? `(${valueVar}[${JSON.stringify(name)}] ?? ${property.alias\n .map(alias => `${valueVar}[${JSON.stringify(alias)}]`)\n .join(\" ?? \")})`\n : `${valueVar}[${JSON.stringify(name)}]`;\n const propertyPath = childPath(pathVar, `.${name}`);\n const propertyVar = nextTemp(\n name ? `${camelCase(name)}Property` : \"property\"\n );\n\n const missingBranch =\n property.default !== undefined\n ? `${resultVar}[${JSON.stringify(name)}] = ${JSON.stringify(\n property.default\n )};`\n : property.required\n ? `errors.push({ path: ${propertyPath}, message: \"Required property is missing\" });`\n : \"\";\n\n lines.push(\n ` if (${accessor} !== undefined) {`,\n ` let ${propertyVar};`\n );\n lines.push(\n ...generateStatements(\n property as JsonSchemaLike,\n accessor,\n propertyPath,\n propertyVar,\n errorsVar\n )\n );\n lines.push(`${resultVar}[${JSON.stringify(name)}] = ${propertyVar};`);\n if (missingBranch) {\n lines.push(`} else { ${missingBranch} }`);\n } else {\n lines.push(\"}\");\n }\n }\n\n const additional = view.additionalProperties;\n if (isJsonSchema(additional)) {\n const additionalVar = nextTemp(\n type || view.name\n ? `${camelCase(type || view.name)}AdditionalProperties`\n : \"additionalProperties\"\n );\n\n lines.push(\n ` for (const key of Object.keys(${valueVar})) {`,\n ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`,\n ` let ${additionalVar};`\n );\n lines.push(\n ...generateStatements(\n additional,\n `${valueVar}[key]`,\n `${pathVar} + \".\" + key`,\n additionalVar,\n errorsVar\n )\n );\n lines.push(`${resultVar}[key] = ${additionalVar};`, `}`);\n } else if (additional !== false) {\n lines.push(\n ` for (const key of Object.keys(${valueVar})) {`,\n ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`,\n ` ${resultVar}[key] = ${valueVar}[key];`,\n `}`\n );\n }\n\n lines.push(`${targetVar} = ${resultVar};`, `}`);\n\n return lines;\n }\n\n /**\n * Generates the parsing statements for an `array` schema, recursing into each\n * item (supporting both list and tuple `items`/`prefixItems` forms).\n */\n function generateArrayStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const lines: string[] = [\n `if (!Array.isArray(${valueVar})) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an array value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n ];\n\n const resultVar = nextTemp(\n view.name ? `${camelCase(view.name)}Array` : \"array\"\n );\n lines.push(` const ${resultVar}: unknown[] = [];`);\n\n const tupleItems =\n view.prefixItems ?? (Array.isArray(view.items) ? view.items : undefined);\n\n if (tupleItems) {\n const listItems = !Array.isArray(view.items) ? view.items : undefined;\n lines.push(\n ` for (let index = 0; index < ${valueVar}.length; index += 1) {`,\n ` const item = ${valueVar}[index];`,\n ` let itemResult;`\n );\n\n tupleItems.forEach((item, index) => {\n lines.push(\n `${index === 0 ? \" if\" : \" else if\"} (index === ${index}) {`\n );\n lines.push(\n ...generateStatements(\n item,\n \"item\",\n childPath(pathVar, `[${index}]`),\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\"}\");\n });\n\n if (listItems) {\n lines.push(\"else {\");\n lines.push(\n ...generateStatements(\n listItems as JsonSchemaLike,\n \"item\",\n `${pathVar} + \"[\" + index + \"]\"`,\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\"}\");\n } else {\n lines.push(\"else { itemResult = item; }\");\n }\n\n lines.push(\n ` ${resultVar}.push(itemResult);`,\n ` }`,\n ` ${targetVar} = ${resultVar};`,\n `}`\n );\n\n return lines;\n }\n\n const itemSchema = (view.items ?? true) as JsonSchema;\n lines.push(\n ` for (let index = 0; index < ${valueVar}.length; index += 1) {`,\n ` const item = ${valueVar}[index];`,\n ` let itemResult;`\n );\n lines.push(\n ...generateStatements(\n itemSchema,\n \"item\",\n `${pathVar} + \"[\" + index + \"]\"`,\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\n ` ${resultVar}.push(itemResult);`,\n ` }`,\n ` ${targetVar} = ${resultVar};`,\n `}`\n );\n\n return lines;\n }\n\n const parserFunctions = Object.entries(definitions).map(\n ([name, definition]) =>\n `function ${toParserIdentifier(name)}(value, path, errors) {\\nlet result;\\n${generateStatements(\n definition,\n \"value\",\n \"path\",\n \"result\",\n \"errors\"\n ).join(\"\\n\")}\\n\\n return result${\n definition.name ? ` as ${stringifyType(definition)}` : \"\"\n };\\n}`\n );\n\n return `/**\n * Error thrown when an input value cannot be parsed into the type described by the JSON Schema.\n */\nexport class ParserError extends Error {\n public override name = \"ParserError\";\n\n public errors: { path: string; message: string }[];\n\n public constructor(errors: { path: string; message: string }[]) {\n super(\n \"Failed to parse the provided value against the JSON Schema:\\\\n\" +\n errors.map(error => \" - \" + error.path + \": \" + error.message).join(\"\\\\n\")\n );\n\n this.errors = errors;\n }\n}\n\n${parserFunctions.join(\"\\n\\n\")}\n\n/**\n * Parses an input value into the type described by the JSON Schema.\n *\n * @remarks\n * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws a {@link ParserError} (containing a detailed list of validation errors) when the value cannot be converted into a valid result.\n *\n * @param value - The input value to parse.\n * @returns The parsed value conforming to the schema.\n */\nexport function parse(value: Record<string, unknown>)${\n schema.name ? `: ${stringifyType(schema)}` : \"\"\n } {\n const errors: { path: string; message: string }[] = [];\n\n let result;\n${generateStatements(schema, \"value\", '\"$\"', \"result\", \"errors\").join(\"\\n\")}\n\n if (errors.length > 0) {\n throw new ParserError(errors);\n }\n\n return result;\n}`;\n}\n\n/**\n * Generates standalone JSON Schema validation code using Ajv.\n *\n * @remarks\n * 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.\n *\n * @param schema - The JSON Schema to generate validation code for.\n * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.\n * @returns The generated standalone validation code as a string.\n */\nexport function generateValidationCode(\n schema: JsonSchema,\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(getValidator(schema), refsOrFuncts);\n}\n\n/**\n * Generates standalone JavaScript code for validating and parsing data according to a JSON Schema.\n *\n * @remarks\n * The generated code includes:\n * - 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.\n * - 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.\n *\n * @param schema - The JSON Schema to generate code for.\n * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.\n * @returns The generated standalone validation and parsing code as a string.\n */\nexport function generateCode(\n schema: JsonSchema,\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return `${generateValidationCode(\n schema,\n refsOrFuncts\n )}\\n\\n${generateParserCode(schema)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoCA,SAAgB,eACd,OACA,MACQ;CACR,OAAOA,cAAY,KAAK,IACpB,cACAC,SAAO,KAAK,IACV,SACA,SAAS,aAAaC,YAAU,KAAK,IACnC,OAAO,OAAO,KAAK,CAAC,IACpB,SAAS,YAAYC,WAAS,KAAK,IACjC,OAAO,WAAW,OAAO,KAAK,CAAC,EAAE,eAAe,QAAW,EACzD,uBAAuB,GACzB,CAAC,IACD,SAAS,YACP,OAAO,SAAS,OAAO,KAAK,CAAC,EAAE,eAAe,IAC9C,SAAS,YAAY,SAAS,YAAY,SAAS,UACjD,KAAK,UAAU,KAAK,IACpB,OAAO,KAAK;AAC5B;;;;AAKA,SAAgB,cAAc,QAA6B;CACzD,IAAI,CAAC,QACH,OA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MAAM,KAAK,6BAA6B;GAG1C,MAAM,KACJ,OAAO,UAAU,qBACjB,OACA,KAAK,UAAU,KAAK,UAAU,IAC9B,GACF;GAEA,OAAO;EACT;EAEA,MAAM,aAAc,KAAK,SAAS;EAClC,MAAM,KACJ,iCAAiC,SAAS,yBAC1C,oBAAoB,SAAS,WAC7B,qBACF;EACA,MAAM,KACJ,GAAG,mBACD,YACA,QACA,GAAG,QAAQ,uBACX,cACA,SACF,CACF;EACA,MAAM,KACJ,OAAO,UAAU,qBACjB,OACA,KAAK,UAAU,KAAK,UAAU,IAC9B,GACF;EAEA,OAAO;CACT;CAeA,OAAO;;;;;;;;;;;;;;;;;;EAbiB,OAAO,QAAQ,WAAW,EAAE,KACjD,CAAC,MAAM,gBACN,YAAY,mBAAmB,IAAI,EAAE,wCAAwC,mBAC3E,YACA,SACA,QACA,UACA,QACF,EAAE,KAAK,IAAI,EAAE,qBACX,WAAW,OAAO,OAAO,cAAc,UAAU,MAAM,GACxD,KAqBS,EAAE,KAAK,MAAM,EAAE;;;;;;;;;;;uDAY3B,OAAO,OAAO,KAAK,cAAc,MAAM,MAAM,GAC9C;;;;EAID,mBAAmB,QAAQ,SAAS,SAAO,UAAU,QAAQ,EAAE,KAAK,IAAI,EAAE;;;;;;;;AAQ5E;;;;;;;;;;;AAYA,SAAgB,uBACd,QACA,cACA;CACA,OAAO,eAAe,aAAa,MAAM,GAAG,YAAY;AAC1D;;;;;;;;;;;;;AAcA,SAAgB,aACd,QACA,cACA;CACA,OAAO,GAAG,uBACR,QACA,YACF,EAAE,MAAM,mBAAmB,MAAM;AACnC"}
|
|
1
|
+
{"version":3,"file":"codegen.mjs","names":["isUndefined","isNull","isBoolean","isNumber","isSetString"],"sources":["../src/codegen.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 { toBool } from \"@stryke/convert/to-bool\";\nimport { camelCase } from \"@stryke/string-format/camel-case\";\nimport { isInteger, isObject, isString } from \"@stryke/type-checks\";\nimport { isBoolean } from \"@stryke/type-checks/is-boolean\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { isUndefined } from \"@stryke/type-checks/is-undefined\";\nimport standaloneCode from \"ajv/dist/standalone\";\nimport { getPropertiesList, isSchemaNullable, merge } from \"./helpers\";\nimport { getPrimarySchemaType } from \"./metadata\";\nimport { isJsonSchema, isJsonSchemaObject } from \"./type-checks\";\nimport { JsonSchema, JsonSchemaLike, JsonSchemaType } from \"./types\";\nimport { getValidator } from \"./validate\";\n\n/**\n * Stringifies a value for generated TypeScript code.\n */\nexport function stringifyValue(\n value?: unknown,\n type?: JsonSchemaType | string\n): string {\n return isUndefined(value)\n ? \"undefined\"\n : isNull(value)\n ? \"null\"\n : type === \"boolean\" || isBoolean(value)\n ? String(toBool(value))\n : type === \"number\" || isNumber(value)\n ? Number.parseFloat(String(value)).toLocaleString(undefined, {\n maximumFractionDigits: 20\n })\n : type === \"integer\"\n ? Number.parseInt(String(value)).toLocaleString()\n : type === \"string\" || type === \"object\" || type === \"array\"\n ? JSON.stringify(value)\n : String(value);\n}\n\n/**\n * Stringifies a JSON Schema fragment into a TypeScript-like type string.\n */\nexport function stringifyType(schema?: JsonSchema): string {\n if (!schema) {\n return \"unknown\";\n }\n\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n if (isJsonSchemaObject(schema) && isSetString(schema.name)) {\n return schema.name;\n }\n\n const objectSchema = schema as JsonSchemaLike;\n\n if (isSetString(objectSchema.$ref)) {\n const match = /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(objectSchema.$ref);\n\n return match?.[1] ?? objectSchema.$ref;\n }\n\n const primaryType = getPrimarySchemaType(schema);\n if (primaryType) {\n if (primaryType === \"integer\" || primaryType === \"number\") {\n return \"number\";\n }\n\n return primaryType;\n }\n\n if (objectSchema.type === \"array\" && Array.isArray(objectSchema.enum)) {\n const enumValues = objectSchema.enum as readonly unknown[];\n\n return enumValues\n .map((value: unknown) => JSON.stringify(value))\n .join(\" | \");\n }\n\n if (objectSchema.const !== undefined) {\n return JSON.stringify(objectSchema.const);\n }\n\n if (objectSchema.type === \"array\" || objectSchema.items) {\n const items = Array.isArray(objectSchema.items)\n ? objectSchema.items[0]\n : objectSchema.items;\n\n return `${stringifyType(items)}[]`;\n }\n\n if (\n objectSchema.type === \"object\" ||\n objectSchema.properties ||\n objectSchema.additionalProperties\n ) {\n if (isJsonSchema(objectSchema.additionalProperties)) {\n return `{ [key: string]: ${stringifyType(objectSchema.additionalProperties)} }`;\n }\n\n if (isJsonSchemaObject(objectSchema)) {\n const required = objectSchema.required ?? [];\n\n return `{ ${getPropertiesList(objectSchema)\n .map(property => {\n const suffix =\n !required.includes(property.name) || isSchemaNullable(property)\n ? `${!required.includes(property.name) ? \"?\" : \"\"}${isSchemaNullable(property) ? \" | null\" : \"\"}`\n : \"\";\n\n return `${property.name}${suffix}: ${stringifyType(property)}`;\n })\n .join(\";\\n\")} }`;\n }\n }\n\n if (objectSchema.oneOf || objectSchema.anyOf) {\n return (objectSchema.oneOf ?? objectSchema.anyOf ?? [])\n .map(branch => stringifyType(branch))\n .join(\" | \");\n }\n\n if (objectSchema.allOf) {\n return \"object\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Returns a string type representation of a value based on its type and an optional JSON Schema primitive type hint.\n *\n * @param value - The value whose type is to be represented as a string.\n * @returns A string representation of the value's type, which may be influenced by the provided JSON Schema primitive type hint. The function handles various JavaScript types and formats them accordingly, including special handling for `undefined`, `null`, booleans, numbers (with formatting), strings, objects, and arrays. If a specific type hint is provided, it will take precedence in determining the string representation of the value.\n */\nexport function getJsonSchemaType(value?: unknown): JsonSchemaType | undefined {\n return isNull(value)\n ? \"null\"\n : isBoolean(value)\n ? \"boolean\"\n : isInteger(value)\n ? \"integer\"\n : isNumber(value)\n ? \"number\"\n : isString(value)\n ? \"string\"\n : isObject(value)\n ? \"object\"\n : Array.isArray(value)\n ? \"array\"\n : undefined;\n}\n\n/**\n * Resolves a local JSON Schema `$ref` (e.g. `#/$defs/Name`) to the referenced definition name.\n */\nfunction resolveLocalRefName(ref: string): string | undefined {\n return /^#\\/(?:definitions|\\$defs)\\/(.+)$/.exec(ref)?.[1];\n}\n\n/**\n * Converts an arbitrary definition name into a safe JavaScript identifier suffix.\n */\nfunction toParserIdentifier(name: string): string {\n const cleaned = name.replace(/[^\\w$]/gu, \"_\");\n\n return `parse_${/^\\d/u.test(cleaned) ? `_${cleaned}` : cleaned}`;\n}\n\n/**\n * Returns the list of JSON Schema `type` keyword values declared on a fragment,\n * preserving `object` and `array` (which {@link readSchemaTypes} intentionally drops).\n */\nfunction readDeclaredTypes(schema: JsonSchemaLike): JsonSchemaType[] {\n const type = schema.type;\n if (Array.isArray(type)) {\n return [...type];\n }\n\n return type ? [type] : [];\n}\n\n/**\n * Generates a JavaScript expression that builds a path string for a child element.\n */\nfunction childPath(pathExpr: string, segment: string): string {\n return `${pathExpr} + ${JSON.stringify(segment)}`;\n}\n\n/**\n * Generates standalone parser code for a JSON Schema.\n *\n * @remarks\n * The generated `parse` function reads an arbitrary input value and converts it\n * into the shape described by the schema. It walks the schema recursively to:\n *\n * - resolve local `$ref` pointers (`#/$defs/*` and `#/definitions/*`) into\n * dedicated parser functions so recursive schemas are supported,\n * - apply `default` values for object properties (and root/array values) that\n * are missing from the input,\n * - coerce primitive values to the declared type (for example `\"42\"` to `42`\n * for an `integer` schema, or `1` to `true` for a `boolean` schema),\n * - validate `const`, `enum`, `oneOf`/`anyOf` and `allOf` constraints, and\n * - collect detailed, path-aware errors and throw a `ParserError` when the\n * input cannot be converted into a valid value.\n *\n * @param schema - The JSON Schema to generate parser code for.\n * @returns The generated standalone parser code as a string.\n */\nexport function generateParserCode(schema: JsonSchema): string {\n const rootSchema =\n typeof schema === \"boolean\" ? schema : (schema as JsonSchemaLike);\n\n const definitions: Record<string, JsonSchema> =\n typeof rootSchema === \"boolean\"\n ? {}\n : {\n ...(\n rootSchema as {\n definitions?: Record<string, JsonSchema>;\n }\n ).definitions,\n ...rootSchema.$defs\n };\n\n const tempCounter = {} as Record<string, number>;\n function nextTemp(prefix: string): string {\n const id = tempCounter[prefix] ?? 0;\n tempCounter[prefix] = id + 1;\n\n return `${prefix}${id > 0 ? `${id}` : \"\"}`;\n }\n\n /**\n * Generates inline parsing statements for a schema fragment.\n */\n function generateStatements(\n fragment: JsonSchemaLike,\n valueExpr: string,\n pathExpr: string,\n targetVar: string,\n errorsVar = \"errors\"\n ): string[] {\n if (typeof fragment === \"boolean\") {\n return fragment\n ? [`${targetVar} = ${valueExpr};`]\n : [\n `${errorsVar}.push({ path: ${pathExpr}, message: \"No value is allowed at this location\" });`,\n `${targetVar} = ${valueExpr};`\n ];\n }\n\n if (isSetString(fragment.$ref)) {\n const refName = resolveLocalRefName(fragment.$ref);\n if (refName && refName in definitions) {\n return [\n `${targetVar} = ${toParserIdentifier(refName)}(${valueExpr}, ${pathExpr}, ${errorsVar});`\n ];\n }\n\n // Unknown / external reference — pass the value through unchanged.\n return [`${targetVar} = ${valueExpr};`];\n }\n\n const valueVar = nextTemp(\n fragment.name ? `${camelCase(fragment.name)}Value` : \"value\"\n );\n const pathVar = nextTemp(\n fragment.name ? `${camelCase(fragment.name)}Path` : \"path\"\n );\n const lines: string[] = [\n `const ${valueVar} = ${valueExpr};`,\n `const ${pathVar} = ${pathExpr};`\n ];\n\n if (fragment.default !== undefined) {\n lines.push(\n `if (${valueVar} === undefined) {`,\n ` ${targetVar} = ${JSON.stringify(fragment.default)};`,\n `} else {`\n );\n\n if (isSchemaNullable(fragment)) {\n lines.push(\n ` if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n ` } else {`\n );\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n lines.push(` }`);\n } else {\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n }\n\n lines.push(`}`);\n\n return lines;\n }\n\n lines.push(\n `if (${valueVar} === undefined) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"A value is required\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n );\n\n if (isSchemaNullable(fragment)) {\n lines.push(\n ` if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n ` } else {`\n );\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n lines.push(` }`);\n } else {\n lines.push(\n ...generateCoreStatements(\n fragment,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n }\n\n lines.push(`}`);\n\n return lines;\n }\n\n /**\n * Generates inline parsing statements assuming `value` is already defined.\n */\n function generateCoreStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const lines: string[] = [];\n\n if (view.const !== undefined) {\n const constValue = JSON.stringify(view.const);\n lines.push(\n `if (JSON.stringify(${valueVar}) !== ${constValue}) { ${\n errorsVar\n }.push({ path: ${pathVar}, message: \"Expected the constant value \" + ${\n constValue\n } }); }`,\n `${targetVar} = ${constValue};`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.enum)) {\n const enumValues = JSON.stringify(view.enum);\n lines.push(\n `if (!${enumValues}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${\n valueVar\n }))) { ${errorsVar}.push({ path: ${\n pathVar\n }, message: \"Expected one of \" + ${enumValues} }); }`,\n `${targetVar} = ${valueVar};`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.oneOf) || Array.isArray(view.anyOf)) {\n const branches = view.oneOf ?? view.anyOf ?? [];\n const matchedVar = nextTemp(\n view.name ? `${camelCase(view.name)}Matched` : \"matched\"\n );\n\n lines.push(`let ${matchedVar} = false;`);\n\n for (const branch of branches) {\n const branchErrorsVar = nextTemp(\n view.name ? `${camelCase(view.name)}BranchErrors` : \"branchErrors\"\n );\n const branchResultVar = nextTemp(\n view.name ? `${camelCase(view.name)}BranchResult` : \"branchResult\"\n );\n\n lines.push(`if (!${matchedVar}) {`);\n lines.push(\n ` const ${branchErrorsVar}: { path: string; message: string }[] = [];`,\n ` let ${branchResultVar};`\n );\n lines.push(\n ...generateStatements(\n branch,\n valueVar,\n pathVar,\n branchResultVar,\n branchErrorsVar\n )\n );\n lines.push(\n ` if (${branchErrorsVar}.length === 0) {`,\n ` ${targetVar} = ${branchResultVar};`,\n ` ${matchedVar} = true;`,\n ` }`,\n `}`\n );\n }\n\n lines.push(\n `if (!${matchedVar}) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Value does not match any of the allowed schemas\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n\n return lines;\n }\n\n if (Array.isArray(view.allOf)) {\n const { allOf, ...rest } = view;\n const merged = merge(rest, ...allOf);\n lines.push(\n ...generateStatements(merged, valueVar, pathVar, targetVar, errorsVar)\n );\n\n return lines;\n }\n\n const declaredTypes = readDeclaredTypes(view);\n const primaryType =\n getPrimarySchemaType(view) ??\n declaredTypes.find(type => type !== \"null\") ??\n (view.properties ? \"object\" : view.items ? \"array\" : undefined);\n\n switch (primaryType) {\n case \"object\":\n lines.push(\n ...generateObjectStatements(\n view,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n break;\n case \"array\":\n lines.push(\n ...generateArrayStatements(\n view,\n valueVar,\n pathVar,\n targetVar,\n errorsVar\n )\n );\n break;\n case \"string\":\n lines.push(\n `if (typeof ${valueVar} === \"string\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"number\" || typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = String(${valueVar});`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a string value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"integer\":\n lines.push(\n `if (typeof ${valueVar} === \"number\" && Number.isInteger(${valueVar})) {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"string\" && ${valueVar}.trim() !== \"\" && Number.isInteger(Number(${valueVar}))) {`,\n ` ${targetVar} = Number(${valueVar});`,\n `} else if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar} ? 1 : 0;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an integer value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"number\":\n lines.push(\n `if (typeof ${valueVar} === \"number\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (typeof ${valueVar} === \"string\" && ${valueVar}.trim() !== \"\" && !Number.isNaN(Number(${valueVar}))) {`,\n ` ${targetVar} = Number(${valueVar});`,\n `} else if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar} ? 1 : 0;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a number value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"boolean\":\n lines.push(\n `if (typeof ${valueVar} === \"boolean\") {`,\n ` ${targetVar} = ${valueVar};`,\n `} else if (${valueVar} === \"true\" || ${valueVar} === 1) {`,\n ` ${targetVar} = true;`,\n `} else if (${valueVar} === \"false\" || ${valueVar} === 0) {`,\n ` ${targetVar} = false;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a boolean value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case \"null\":\n lines.push(\n `if (${valueVar} === null) {`,\n ` ${targetVar} = null;`,\n `} else {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected a null value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `}`\n );\n break;\n case undefined:\n default:\n lines.push(`${targetVar} = ${valueVar};`);\n break;\n }\n\n return lines;\n }\n\n /**\n * Generates the parsing statements for an `object` schema, applying property\n * defaults and recursing into each declared property.\n */\n function generateObjectStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const type = stringifyType(view);\n\n const lines: string[] = [\n `if (typeof ${valueVar} !== \"object\" || ${valueVar} === null || Array.isArray(${valueVar})) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an object value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n ];\n\n const resultVar = nextTemp(\n type || view.name ? `${camelCase(type || view.name)}Schema` : \"schema\"\n );\n lines.push(`const ${resultVar} = {} as Record<string, any>`);\n\n const properties = isJsonSchemaObject(view) ? getPropertiesList(view) : [];\n const propertyNames = new Set<string>();\n\n for (const property of properties) {\n const name = property.name;\n propertyNames.add(name);\n\n const accessor = property.alias?.length\n ? `(${valueVar}[${JSON.stringify(name)}] ?? ${property.alias\n .map(alias => `${valueVar}[${JSON.stringify(alias)}]`)\n .join(\" ?? \")})`\n : `${valueVar}[${JSON.stringify(name)}]`;\n const propertyPath = childPath(pathVar, `.${name}`);\n const propertyVar = nextTemp(\n name ? `${camelCase(name)}Property` : \"property\"\n );\n\n const missingBranch =\n property.default !== undefined\n ? `${resultVar}[${JSON.stringify(name)}] = ${JSON.stringify(\n property.default\n )};`\n : property.required\n ? `errors.push({ path: ${propertyPath}, message: \"Required property is missing\" });`\n : \"\";\n\n lines.push(\n ` if (${accessor} !== undefined) {`,\n ` let ${propertyVar};`\n );\n lines.push(\n ...generateStatements(\n property as JsonSchemaLike,\n accessor,\n propertyPath,\n propertyVar,\n errorsVar\n )\n );\n lines.push(`${resultVar}[${JSON.stringify(name)}] = ${propertyVar};`);\n if (missingBranch) {\n lines.push(`} else { ${missingBranch} }`);\n } else {\n lines.push(\"}\");\n }\n }\n\n const additional = view.additionalProperties;\n if (isJsonSchema(additional)) {\n const additionalVar = nextTemp(\n type || view.name\n ? `${camelCase(type || view.name)}AdditionalProperties`\n : \"additionalProperties\"\n );\n\n lines.push(\n ` for (const key of Object.keys(${valueVar})) {`,\n ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`,\n ` let ${additionalVar};`\n );\n lines.push(\n ...generateStatements(\n additional,\n `${valueVar}[key]`,\n `${pathVar} + \".\" + key`,\n additionalVar,\n errorsVar\n )\n );\n lines.push(`${resultVar}[key] = ${additionalVar};`, `}`);\n } else if (additional !== false) {\n lines.push(\n ` for (const key of Object.keys(${valueVar})) {`,\n ` if (${JSON.stringify([...propertyNames])}.includes(key)) { continue; }`,\n ` ${resultVar}[key] = ${valueVar}[key];`,\n `}`\n );\n }\n\n lines.push(`${targetVar} = ${resultVar};`, `}`);\n\n return lines;\n }\n\n /**\n * Generates the parsing statements for an `array` schema, recursing into each\n * item (supporting both list and tuple `items`/`prefixItems` forms).\n */\n function generateArrayStatements(\n view: JsonSchemaLike,\n valueVar: string,\n pathVar: string,\n targetVar: string,\n errorsVar: string\n ): string[] {\n const lines: string[] = [\n `if (!Array.isArray(${valueVar})) {`,\n ` ${errorsVar}.push({ path: ${pathVar}, message: \"Expected an array value\" });`,\n ` ${targetVar} = ${valueVar};`,\n `} else {`\n ];\n\n const resultVar = nextTemp(\n view.name ? `${camelCase(view.name)}Array` : \"array\"\n );\n lines.push(` const ${resultVar}: unknown[] = [];`);\n\n const tupleItems =\n view.prefixItems ?? (Array.isArray(view.items) ? view.items : undefined);\n\n if (tupleItems) {\n const listItems = !Array.isArray(view.items) ? view.items : undefined;\n lines.push(\n ` for (let index = 0; index < ${valueVar}.length; index += 1) {`,\n ` const item = ${valueVar}[index];`,\n ` let itemResult;`\n );\n\n tupleItems.forEach((item, index) => {\n lines.push(\n `${index === 0 ? \" if\" : \" else if\"} (index === ${index}) {`\n );\n lines.push(\n ...generateStatements(\n item,\n \"item\",\n childPath(pathVar, `[${index}]`),\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\"}\");\n });\n\n if (listItems) {\n lines.push(\"else {\");\n lines.push(\n ...generateStatements(\n listItems as JsonSchemaLike,\n \"item\",\n `${pathVar} + \"[\" + index + \"]\"`,\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\"}\");\n } else {\n lines.push(\"else { itemResult = item; }\");\n }\n\n lines.push(\n ` ${resultVar}.push(itemResult);`,\n ` }`,\n ` ${targetVar} = ${resultVar};`,\n `}`\n );\n\n return lines;\n }\n\n const itemSchema = (view.items ?? true) as JsonSchema;\n lines.push(\n ` for (let index = 0; index < ${valueVar}.length; index += 1) {`,\n ` const item = ${valueVar}[index];`,\n ` let itemResult;`\n );\n lines.push(\n ...generateStatements(\n itemSchema,\n \"item\",\n `${pathVar} + \"[\" + index + \"]\"`,\n \"itemResult\",\n errorsVar\n )\n );\n lines.push(\n ` ${resultVar}.push(itemResult);`,\n ` }`,\n ` ${targetVar} = ${resultVar};`,\n `}`\n );\n\n return lines;\n }\n\n const parserFunctions = Object.entries(definitions).map(\n ([name, definition]) =>\n `function ${toParserIdentifier(name)}(value, path, errors) {\\nlet result;\\n${generateStatements(\n definition,\n \"value\",\n \"path\",\n \"result\",\n \"errors\"\n ).join(\"\\n\")}\\n\\n return result${\n definition.name ? ` as ${stringifyType(definition)}` : \"\"\n };\\n}`\n );\n\n return `/**\n * Error thrown when an input value cannot be parsed into the type described by the JSON Schema.\n */\nexport class ParserError extends Error {\n public override name = \"ParserError\";\n\n public errors: { path: string; message: string }[];\n\n public constructor(errors: { path: string; message: string }[]) {\n super(\n \"Failed to parse the provided value against the JSON Schema:\\\\n\" +\n errors.map(error => \" - \" + error.path + \": \" + error.message).join(\"\\\\n\")\n );\n\n this.errors = errors;\n }\n}\n\n${parserFunctions.join(\"\\n\\n\")}\n\n/**\n * Parses an input value into the type described by the JSON Schema.\n *\n * @remarks\n * The parser applies default values for missing properties, coerces primitive values to the declared type, and throws a {@link ParserError} (containing a detailed list of validation errors) when the value cannot be converted into a valid result.\n *\n * @param value - The input value to parse.\n * @returns The parsed value conforming to the schema.\n */\nexport function parse(value: Record<string, unknown>)${\n schema.name ? `: ${stringifyType(schema)}` : \"\"\n } {\n const errors: { path: string; message: string }[] = [];\n\n let result;\n${generateStatements(schema, \"value\", '\"$\"', \"result\", \"errors\").join(\"\\n\")}\n\n if (errors.length > 0) {\n throw new ParserError(errors);\n }\n\n return result${schema.name ? ` as ${stringifyType(schema)}` : \"\"};\n}`;\n}\n\n/**\n * Generates standalone JSON Schema validation code using Ajv.\n *\n * @remarks\n * 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.\n *\n * @param schema - The JSON Schema to generate validation code for.\n * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.\n * @returns The generated standalone validation code as a string.\n */\nexport function generateValidationCode(\n schema: JsonSchema,\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(getValidator(schema), refsOrFuncts);\n}\n\n/**\n * Generates standalone JavaScript code for validating and parsing data according to a JSON Schema.\n *\n * @remarks\n * The generated code includes:\n * - 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.\n * - 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.\n *\n * @param schema - The JSON Schema to generate code for.\n * @param refsOrFuncts - Optional additional references or functions for Ajv's standalone code generation.\n * @returns The generated standalone validation and parsing code as a string.\n */\nexport function generateCode(\n schema: JsonSchema,\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return `${generateValidationCode(\n schema,\n refsOrFuncts\n )}\\n\\n${generateParserCode(schema)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoCA,SAAgB,eACd,OACA,MACQ;CACR,OAAOA,cAAY,KAAK,IACpB,cACAC,SAAO,KAAK,IACV,SACA,SAAS,aAAaC,YAAU,KAAK,IACnC,OAAO,OAAO,KAAK,CAAC,IACpB,SAAS,YAAYC,WAAS,KAAK,IACjC,OAAO,WAAW,OAAO,KAAK,CAAC,EAAE,eAAe,QAAW,EACzD,uBAAuB,GACzB,CAAC,IACD,SAAS,YACP,OAAO,SAAS,OAAO,KAAK,CAAC,EAAE,eAAe,IAC9C,SAAS,YAAY,SAAS,YAAY,SAAS,UACjD,KAAK,UAAU,KAAK,IACpB,OAAO,KAAK;AAC5B;;;;AAKA,SAAgB,cAAc,QAA6B;CACzD,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,OAAO,WAAW,WACpB,OAAO,SAAS,YAAY;CAG9B,IAAI,mBAAmB,MAAM,KAAKC,cAAY,OAAO,IAAI,GACvD,OAAO,OAAO;CAGhB,MAAM,eAAe;CAErB,IAAIA,cAAY,aAAa,IAAI,GAG/B,OAFc,oCAAoC,KAAK,aAAa,IAEzD,IAAI,MAAM,aAAa;CAGpC,MAAM,cAAc,qBAAqB,MAAM;CAC/C,IAAI,aAAa;EACf,IAAI,gBAAgB,aAAa,gBAAgB,UAC/C,OAAO;EAGT,OAAO;CACT;CAEA,IAAI,aAAa,SAAS,WAAW,MAAM,QAAQ,aAAa,IAAI,GAGlE,OAFmB,aAAa,KAG7B,KAAK,UAAmB,KAAK,UAAU,KAAK,CAAC,EAC7C,KAAK,KAAK;CAGf,IAAI,aAAa,UAAU,QACzB,OAAO,KAAK,UAAU,aAAa,KAAK;CAG1C,IAAI,aAAa,SAAS,WAAW,aAAa,OAKhD,OAAO,GAAG,cAJI,MAA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S,EAAE,KAAK,MAAM,EAAE;;;;;;;;;;;uDAY3B,OAAO,OAAO,KAAK,cAAc,MAAM,MAAM,GAC9C;;;;EAID,mBAAmB,QAAQ,SAAS,SAAO,UAAU,QAAQ,EAAE,KAAK,IAAI,EAAE;;;;;;iBAM3D,OAAO,OAAO,OAAO,cAAc,MAAM,MAAM,GAAG;;AAEnE;;;;;;;;;;;AAYA,SAAgB,uBACd,QACA,cACA;CACA,OAAO,eAAe,aAAa,MAAM,GAAG,YAAY;AAC1D;;;;;;;;;;;;;AAcA,SAAgB,aACd,QACA,cACA;CACA,OAAO,GAAG,uBACR,QACA,YACF,EAAE,MAAM,mBAAmB,MAAM;AACnC"}
|
package/dist/resolve.cjs
CHANGED
|
@@ -35,7 +35,7 @@ async function resolveModule(context, input, overrides) {
|
|
|
35
35
|
throw new Error(`The module "${moduleName}" could not be resolved while evaluating "${fileReference.file}". It is possible the required built-in modules have not yet been generated. Please check the order of your plugins. ${context.config.logLevel.general === "debug" || context.config.logLevel.general === "trace" ? `
|
|
36
36
|
|
|
37
37
|
Bundle output for module:
|
|
38
|
-
${result.text}` : ""}`);
|
|
38
|
+
${result.text && result.text.length > 2e4 ? `${result.text.slice(0, 2e4)}\n... [truncated]` : result.text}` : ""}`);
|
|
39
39
|
}
|
|
40
40
|
throw new Error(`Failed to evaluate the bundled module for "${fileReference.file}". Error: ${error.message}${context.config.logLevel.general === "debug" || context.config.logLevel.general === "trace" ? `
|
|
41
41
|
|
package/dist/resolve.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.d.cts","names":[],"sources":["../src/resolve.ts"],"mappings":";;;;;;;;AAsCA;;;;;;iBAAsB,aAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,SAAA,GAAY,aAAA,GACX,OAAA,CAAQ,OAAA;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"resolve.d.cts","names":[],"sources":["../src/resolve.ts"],"mappings":";;;;;;;;AAsCA;;;;;;iBAAsB,aAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,SAAA,GAAY,aAAA,GACX,OAAA,CAAQ,OAAA;;;;;;;;;iBA2EW,OAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,OAAA,GAAU,aAAA,GACT,OAAA,CAAQ,OAAA;;;;;;;;;iBAiGW,iBAAA,kBACH,aAAA,GAAgB,aAAA,EAEjC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,aAAA,EACP,OAAA,GAAU,aAAA,GACT,OAAA,CAAQ,IAAA"}
|
package/dist/resolve.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.d.mts","names":[],"sources":["../src/resolve.ts"],"mappings":";;;;;;;;AAsCA;;;;;;iBAAsB,aAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,SAAA,GAAY,aAAA,GACX,OAAA,CAAQ,OAAA;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"resolve.d.mts","names":[],"sources":["../src/resolve.ts"],"mappings":";;;;;;;;AAsCA;;;;;;iBAAsB,aAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,SAAA,GAAY,aAAA,GACX,OAAA,CAAQ,OAAA;;;;;;;;;iBA2EW,OAAA,2BAEH,iBAAA,GAAoB,iBAAA,EAErC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,kBAAA,EACP,OAAA,GAAU,aAAA,GACT,OAAA,CAAQ,OAAA;;;;;;;;;iBAiGW,iBAAA,kBACH,aAAA,GAAgB,aAAA,EAEjC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,aAAA,EACP,OAAA,GAAU,aAAA,GACT,OAAA,CAAQ,IAAA"}
|
package/dist/resolve.mjs
CHANGED
|
@@ -33,7 +33,7 @@ async function resolveModule(context, input, overrides) {
|
|
|
33
33
|
throw new Error(`The module "${moduleName}" could not be resolved while evaluating "${fileReference.file}". It is possible the required built-in modules have not yet been generated. Please check the order of your plugins. ${context.config.logLevel.general === "debug" || context.config.logLevel.general === "trace" ? `
|
|
34
34
|
|
|
35
35
|
Bundle output for module:
|
|
36
|
-
${result.text}` : ""}`);
|
|
36
|
+
${result.text && result.text.length > 2e4 ? `${result.text.slice(0, 2e4)}\n... [truncated]` : result.text}` : ""}`);
|
|
37
37
|
}
|
|
38
38
|
throw new Error(`Failed to evaluate the bundled module for "${fileReference.file}". Error: ${error.message}${context.config.logLevel.general === "debug" || context.config.logLevel.general === "trace" ? `
|
|
39
39
|
|
package/dist/resolve.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve.mjs","names":["parseYaml","parseToml"],"sources":["../src/resolve.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { PluginContext, UnresolvedContext } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { reflect, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { extractFileReference } from \"@stryke/convert/extract-file-reference\";\nimport { findFileDotExtension, findFileExtensionSafe } from \"@stryke/path/find\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { FileReference, FileReferenceInput } from \"@stryke/types/configuration\";\nimport defu from \"defu\";\nimport { parse as parseToml } from \"smol-toml\";\nimport { parse as parseYaml } from \"yaml\";\nimport { bundle, BundleOptions } from \"./bundle\";\n\n/**\n * Compiles a type definition to a module and returns the module.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param overrides - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the compiled module.\n */\nexport async function resolveModule<\n TResult,\n TContext extends UnresolvedContext = UnresolvedContext\n>(\n context: TContext,\n input: FileReferenceInput,\n overrides?: BundleOptions\n): Promise<TResult> {\n const fileReference = extractFileReference(input);\n if (!fileReference) {\n throw new Error(\n `Failed to extract a file reference from the provided input ${JSON.stringify(\n input\n )}. The input must be a string or an object with a \"file\" property that specifies the file path and optional export name.`\n );\n }\n\n const result = await bundle<TContext>(context, fileReference.file, overrides);\n\n let resolved: any;\n try {\n resolved = await context.resolver.evalModule(result.text, {\n filename: result.path,\n ext: findFileDotExtension(result.path)\n });\n } catch (error) {\n if (\n isSetString((error as Error).message) &&\n new RegExp(\n `Cannot find module '${context.config.framework?.name || \"powerlines\"}:.*'`\n ).test((error as Error).message)\n ) {\n const moduleName = (error as Error).message.match(\n new RegExp(\n `Cannot find module '(${context.config.framework?.name || \"powerlines\"}:.*)'`\n )\n )?.[1];\n throw new Error(\n `The module \"${moduleName}\" could not be resolved while evaluating \"${\n fileReference.file\n }\". It is possible the required built-in modules have not yet been generated. Please check the order of your plugins. ${\n context.config.logLevel.general === \"debug\" ||\n context.config.logLevel.general === \"trace\"\n ? `\n\nBundle output for module:\n${result.text}`\n : \"\"\n }`\n );\n }\n\n throw new Error(\n `Failed to evaluate the bundled module for \"${\n fileReference.file\n }\". Error: ${(error as Error).message}${\n context.config.logLevel.general === \"debug\" ||\n context.config.logLevel.general === \"trace\"\n ? `\n\nBundle output for module:\n${result.text}`\n : \"\"\n }`\n );\n }\n\n return resolved;\n}\n\n/**\n * Compiles a type definition to a module and returns the specified export from the module.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the compiled module.\n */\nexport async function resolve<\n TResult,\n TContext extends UnresolvedContext = UnresolvedContext\n>(\n context: TContext,\n input: FileReferenceInput,\n options?: BundleOptions\n): Promise<TResult> {\n const fileReference = extractFileReference(input);\n if (!fileReference) {\n throw new Error(\n `Failed to extract a file reference from the provided input. The input must be a string or an object with a \"file\" property that specifies the file path and optional export name.`\n );\n }\n\n const extension = findFileExtensionSafe(fileReference.file);\n if (extension.startsWith(\"json\")) {\n try {\n const json = await context.fs.read(fileReference.file);\n if (!isSetString(json)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid JSON.`\n );\n }\n\n return JSON.parse(json) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the JSON file at \"${fileReference.file}\". Please ensure the file exists and contains valid JSON. Error: ${(error as Error).message}`\n );\n }\n } else if (extension === \"yaml\" || extension === \"yml\") {\n try {\n const yaml = await context.fs.read(fileReference.file);\n if (!isSetString(yaml)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid YAML.`\n );\n }\n\n return parseYaml(yaml) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the YAML file at \"${fileReference.file}\". Please ensure the file exists and contains valid YAML. Error: ${(error as Error).message}`\n );\n }\n } else if (extension === \"toml\") {\n try {\n const toml = await context.fs.read(fileReference.file);\n if (!isSetString(toml)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid TOML.`\n );\n }\n\n return parseToml(toml) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the TOML file at \"${fileReference.file}\". Please ensure the file exists and contains valid TOML. Error: ${(error as Error).message}`\n );\n }\n }\n\n const resolved = await resolveModule<Record<string, any>, TContext>(\n context,\n fileReference,\n options\n );\n\n let exportName = fileReference.export;\n if (!exportName) {\n exportName = \"default\";\n }\n\n const resolvedExport = resolved[exportName] ?? resolved[`__Ω${exportName}`];\n if (resolvedExport === undefined) {\n throw new Error(\n `The export \"${exportName}\" could not be resolved in the \"${\n fileReference.file\n }\" module. ${\n Object.keys(resolved).length === 0\n ? `After bundling, no exports were found in the module. Please ensure that the \"${\n fileReference.file\n }\" module has a \"${exportName}\" export with the desired value.`\n : `After bundling, the available exports were: ${Object.keys(\n resolved\n ).join(\n \", \"\n )}. Please ensure that the export exists and is correctly named.`\n }`\n );\n }\n\n return resolvedExport;\n}\n\n/**\n * Resolves a type definition to a Deepkit Type reflection. This function compiles the provided type definition to a module, evaluates the module to get the specified export, and then reflects the export to get its Deepkit Type reflection.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the Deepkit Type reflection.\n */\nexport async function resolveReflection<\n TContext extends PluginContext = PluginContext\n>(\n context: TContext,\n input: FileReference,\n options?: BundleOptions\n): Promise<Type> {\n return reflect(\n await resolve<Type>(\n context,\n input,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n )\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA,eAAsB,cAIpB,SACA,OACA,WACkB;CAClB,MAAM,gBAAgB,qBAAqB,KAAK;CAChD,IAAI,CAAC,eACH,MAAM,IAAI,MACR,8DAA8D,KAAK,UACjE,KACF,EAAE,wHACJ;CAGF,MAAM,SAAS,MAAM,OAAiB,SAAS,cAAc,MAAM,SAAS;CAE5E,IAAI;CACJ,IAAI;EACF,WAAW,MAAM,QAAQ,SAAS,WAAW,OAAO,MAAM;GACxD,UAAU,OAAO;GACjB,KAAK,qBAAqB,OAAO,IAAI;EACvC,CAAC;CACH,SAAS,OAAO;EACd,I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,MAAM,IAAI,MACR,6CAA6C,cAAc,KAAK,mEAAoE,MAAgB,SACtJ;CACF;MACK,IAAI,cAAc,QACvB,IAAI;EACF,MAAM,OAAO,MAAM,QAAQ,GAAG,KAAK,cAAc,IAAI;EACrD,IAAI,CAAC,YAAY,IAAI,GACnB,MAAM,IAAI,MACR,gBAAgB,cAAc,KAAK,wFACrC;EAGF,OAAOC,MAAU,IAAI;CACvB,SAAS,OAAO;EACd,MAAM,IAAI,MACR,6CAA6C,cAAc,KAAK,mEAAoE,MAAgB,SACtJ;CACF;CAGF,MAAM,WAAW,MAAM,cACrB,SACA,eACA,OACF;CAEA,IAAI,aAAa,cAAc;CAC/B,IAAI,CAAC,YACH,aAAa;CAGf,MAAM,iBAAiB,SAAS,eAAe,SAAS,MAAM;CAC9D,IAAI,mBAAmB,QACrB,MAAM,IAAI,MACR,eAAe,WAAW,kCACxB,cAAc,KACf,YACC,OAAO,KAAK,QAAQ,EAAE,WAAW,IAC7B,gFACE,cAAc,KACf,kBAAkB,WAAW,oCAC9B,+CAA+C,OAAO,KACpD,QACF,EAAE,KACA,IACF,EAAE,iEAEV;CAGF,OAAO;AACT;;;;;;;;;AAUA,eAAsB,kBAGpB,SACA,OACA,SACe;CACf,OAAO,QACL,MAAM,QACJ,SACA,OACA,KAAK,SAAS,EACZ,SAAS,CACP,cAAc,SAAS;EACrB,YAAY;EACZ,OAAO;CACT,CAAC,CACH,EACF,CAAC,CACH,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"resolve.mjs","names":["parseYaml","parseToml"],"sources":["../src/resolve.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { PluginContext, UnresolvedContext } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { reflect, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { extractFileReference } from \"@stryke/convert/extract-file-reference\";\nimport { findFileDotExtension, findFileExtensionSafe } from \"@stryke/path/find\";\nimport { isSetString } from \"@stryke/type-checks/is-set-string\";\nimport { FileReference, FileReferenceInput } from \"@stryke/types/configuration\";\nimport defu from \"defu\";\nimport { parse as parseToml } from \"smol-toml\";\nimport { parse as parseYaml } from \"yaml\";\nimport { bundle, BundleOptions } from \"./bundle\";\n\n/**\n * Compiles a type definition to a module and returns the module.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param overrides - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the compiled module.\n */\nexport async function resolveModule<\n TResult,\n TContext extends UnresolvedContext = UnresolvedContext\n>(\n context: TContext,\n input: FileReferenceInput,\n overrides?: BundleOptions\n): Promise<TResult> {\n const fileReference = extractFileReference(input);\n if (!fileReference) {\n throw new Error(\n `Failed to extract a file reference from the provided input ${JSON.stringify(\n input\n )}. The input must be a string or an object with a \"file\" property that specifies the file path and optional export name.`\n );\n }\n\n const result = await bundle<TContext>(context, fileReference.file, overrides);\n\n let resolved: any;\n try {\n resolved = await context.resolver.evalModule(result.text, {\n filename: result.path,\n ext: findFileDotExtension(result.path)\n });\n } catch (error) {\n if (\n isSetString((error as Error).message) &&\n new RegExp(\n `Cannot find module '${context.config.framework?.name || \"powerlines\"}:.*'`\n ).test((error as Error).message)\n ) {\n const moduleName = (error as Error).message.match(\n new RegExp(\n `Cannot find module '(${context.config.framework?.name || \"powerlines\"}:.*)'`\n )\n )?.[1];\n throw new Error(\n `The module \"${moduleName}\" could not be resolved while evaluating \"${\n fileReference.file\n }\". It is possible the required built-in modules have not yet been generated. Please check the order of your plugins. ${\n context.config.logLevel.general === \"debug\" ||\n context.config.logLevel.general === \"trace\"\n ? `\n\nBundle output for module:\n${\n result.text && result.text.length > 20_000\n ? `${result.text.slice(0, 20_000)}\\n... [truncated]`\n : result.text\n}`\n : \"\"\n }`\n );\n }\n\n throw new Error(\n `Failed to evaluate the bundled module for \"${\n fileReference.file\n }\". Error: ${(error as Error).message}${\n context.config.logLevel.general === \"debug\" ||\n context.config.logLevel.general === \"trace\"\n ? `\n\nBundle output for module:\n${result.text}`\n : \"\"\n }`\n );\n }\n\n return resolved;\n}\n\n/**\n * Compiles a type definition to a module and returns the specified export from the module.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the compiled module.\n */\nexport async function resolve<\n TResult,\n TContext extends UnresolvedContext = UnresolvedContext\n>(\n context: TContext,\n input: FileReferenceInput,\n options?: BundleOptions\n): Promise<TResult> {\n const fileReference = extractFileReference(input);\n if (!fileReference) {\n throw new Error(\n `Failed to extract a file reference from the provided input. The input must be a string or an object with a \"file\" property that specifies the file path and optional export name.`\n );\n }\n\n const extension = findFileExtensionSafe(fileReference.file);\n if (extension.startsWith(\"json\")) {\n try {\n const json = await context.fs.read(fileReference.file);\n if (!isSetString(json)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid JSON.`\n );\n }\n\n return JSON.parse(json) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the JSON file at \"${fileReference.file}\". Please ensure the file exists and contains valid JSON. Error: ${(error as Error).message}`\n );\n }\n } else if (extension === \"yaml\" || extension === \"yml\") {\n try {\n const yaml = await context.fs.read(fileReference.file);\n if (!isSetString(yaml)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid YAML.`\n );\n }\n\n return parseYaml(yaml) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the YAML file at \"${fileReference.file}\". Please ensure the file exists and contains valid YAML. Error: ${(error as Error).message}`\n );\n }\n } else if (extension === \"toml\") {\n try {\n const toml = await context.fs.read(fileReference.file);\n if (!isSetString(toml)) {\n throw new Error(\n `The file at \"${fileReference.file}\" could not be read as a string. Please ensure the file exists and contains valid TOML.`\n );\n }\n\n return parseToml(toml) as TResult;\n } catch (error) {\n throw new Error(\n `Failed to read or parse the TOML file at \"${fileReference.file}\". Please ensure the file exists and contains valid TOML. Error: ${(error as Error).message}`\n );\n }\n }\n\n const resolved = await resolveModule<Record<string, any>, TContext>(\n context,\n fileReference,\n options\n );\n\n let exportName = fileReference.export;\n if (!exportName) {\n exportName = \"default\";\n }\n\n const resolvedExport = resolved[exportName] ?? resolved[`__Ω${exportName}`];\n if (resolvedExport === undefined) {\n throw new Error(\n `The export \"${exportName}\" could not be resolved in the \"${\n fileReference.file\n }\" module. ${\n Object.keys(resolved).length === 0\n ? `After bundling, no exports were found in the module. Please ensure that the \"${\n fileReference.file\n }\" module has a \"${exportName}\" export with the desired value.`\n : `After bundling, the available exports were: ${Object.keys(\n resolved\n ).join(\n \", \"\n )}. Please ensure that the export exists and is correctly named.`\n }`\n );\n }\n\n return resolvedExport;\n}\n\n/**\n * Resolves a type definition to a Deepkit Type reflection. This function compiles the provided type definition to a module, evaluates the module to get the specified export, and then reflects the export to get its Deepkit Type reflection.\n *\n * @param context - The context object containing the environment paths.\n * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the Deepkit Type reflection.\n */\nexport async function resolveReflection<\n TContext extends PluginContext = PluginContext\n>(\n context: TContext,\n input: FileReference,\n options?: BundleOptions\n): Promise<Type> {\n return reflect(\n await resolve<Type>(\n context,\n input,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n )\n );\n}\n"],"mappings":";;;;;;;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OAAO,QACL,MAAM,QACJ,SACA,OACA,KAAK,SAAS,EACZ,SAAS,CACP,cAAc,SAAS;EACrB,YAAY;EACZ,OAAO;CACT,CAAC,CACH,EACF,CAAC,CACH,CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powerlines/schema",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.88",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A package containing a Powerlines plugin to assist in developing other Powerlines plugins.",
|
|
6
6
|
"keywords": [
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
"typings": "dist/index.d.mts",
|
|
60
60
|
"files": ["dist"],
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@powerlines/core": "^0.48.
|
|
63
|
-
"@powerlines/deepkit": "^0.9.
|
|
64
|
-
"@powerlines/unplugin": "^0.0.
|
|
62
|
+
"@powerlines/core": "^0.48.38",
|
|
63
|
+
"@powerlines/deepkit": "^0.9.70",
|
|
64
|
+
"@powerlines/unplugin": "^0.0.86",
|
|
65
65
|
"@standard-schema/spec": "^1.1.0",
|
|
66
66
|
"@stryke/convert": "^0.7.14",
|
|
67
67
|
"@stryke/hash": "^0.13.37",
|
|
@@ -96,5 +96,5 @@
|
|
|
96
96
|
"zod": { "optional": true }
|
|
97
97
|
},
|
|
98
98
|
"publishConfig": { "access": "public" },
|
|
99
|
-
"gitHead": "
|
|
99
|
+
"gitHead": "87e51702e7912e7e0f335da1c4cff9712ec4bdba"
|
|
100
100
|
}
|