@powerlines/schema 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +36 -22
  2. package/dist/bundle.d.cts +2 -2
  3. package/dist/bundle.d.cts.map +1 -1
  4. package/dist/bundle.d.mts +2 -2
  5. package/dist/bundle.d.mts.map +1 -1
  6. package/dist/bundle.mjs.map +1 -1
  7. package/dist/codegen.cjs +27 -0
  8. package/dist/codegen.d.cts +15 -0
  9. package/dist/codegen.d.cts.map +1 -0
  10. package/dist/codegen.d.mts +15 -0
  11. package/dist/codegen.d.mts.map +1 -0
  12. package/dist/codegen.mjs +24 -0
  13. package/dist/codegen.mjs.map +1 -0
  14. package/dist/extract.cjs +201 -52
  15. package/dist/extract.d.cts +81 -16
  16. package/dist/extract.d.cts.map +1 -1
  17. package/dist/extract.d.mts +81 -16
  18. package/dist/extract.d.mts.map +1 -1
  19. package/dist/extract.mjs +199 -55
  20. package/dist/extract.mjs.map +1 -1
  21. package/dist/index.cjs +15 -3
  22. package/dist/index.d.cts +7 -5
  23. package/dist/index.d.mts +7 -5
  24. package/dist/index.mjs +6 -4
  25. package/dist/jtd.cjs +385 -0
  26. package/dist/jtd.d.cts +15 -0
  27. package/dist/jtd.d.cts.map +1 -0
  28. package/dist/jtd.d.mts +15 -0
  29. package/dist/jtd.d.mts.map +1 -0
  30. package/dist/jtd.mjs +384 -0
  31. package/dist/jtd.mjs.map +1 -0
  32. package/dist/reflection.cjs +321 -100
  33. package/dist/reflection.d.cts +16 -13
  34. package/dist/reflection.d.cts.map +1 -1
  35. package/dist/reflection.d.mts +16 -13
  36. package/dist/reflection.d.mts.map +1 -1
  37. package/dist/reflection.mjs +323 -101
  38. package/dist/reflection.mjs.map +1 -1
  39. package/dist/resolve.d.cts +5 -5
  40. package/dist/resolve.d.cts.map +1 -1
  41. package/dist/resolve.d.mts +5 -5
  42. package/dist/resolve.d.mts.map +1 -1
  43. package/dist/resolve.mjs.map +1 -1
  44. package/dist/type-checks.cjs +76 -0
  45. package/dist/type-checks.d.cts +43 -0
  46. package/dist/type-checks.d.cts.map +1 -0
  47. package/dist/type-checks.d.mts +43 -0
  48. package/dist/type-checks.d.mts.map +1 -0
  49. package/dist/type-checks.mjs +71 -0
  50. package/dist/type-checks.mjs.map +1 -0
  51. package/dist/types.d.cts +166 -24
  52. package/dist/types.d.cts.map +1 -1
  53. package/dist/types.d.mts +166 -24
  54. package/dist/types.d.mts.map +1 -1
  55. package/package.json +25 -19
  56. package/dist/is-schema-definition.cjs +0 -18
  57. package/dist/is-schema-definition.d.cts +0 -13
  58. package/dist/is-schema-definition.d.cts.map +0 -1
  59. package/dist/is-schema-definition.d.mts +0 -13
  60. package/dist/is-schema-definition.d.mts.map +0 -1
  61. package/dist/is-schema-definition.mjs +0 -17
  62. package/dist/is-schema-definition.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"extract.mjs","names":["isSetObject"],"sources":["../src/extract.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 } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport type { JsonSchema7Type } from \"@stryke/json\";\nimport { isJsonSchema7ObjectType, isStandardJsonSchema } from \"@stryke/json\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport { extractJsonSchema7, isZod3Type } from \"@stryke/zod\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport { isSchemaDefinition } from \"./is-schema-definition\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n SchemaDefinition,\n SchemaDefinitionInput,\n SchemaDefinitionParameter\n} from \"./types\";\n\n/**\n * Converts a reflected Deepkit {@link @powerlines/deepkit/vendor/type#Type} into a JSON Schema (draft-07) representation.\n *\n * @remarks\n * This function delegates to an internal recursive walker that handles the full set of Deepkit reflection kinds.\n *\n * @param reflection - The reflected Deepkit Type to convert.\n * @returns A JSON Schema (draft-07) fragment representing the type, or `undefined` when no schema could be produced.\n */\nexport function extractReflection(\n reflection: Type\n): JsonSchema7Type | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema(reflection);\n}\n\n/**\n * Extracts a JSON Schema object from a given schema definition, if possible.\n *\n * @remarks\n * This function checks if the provided schema is a Zod schema, a Standard JSON Schema, or already a JSON Schema object. If it is a Zod schema, it extracts the corresponding JSON Schema. If it is a Standard JSON Schema, it retrieves the input JSON Schema targeting draft-07. Finally, it checks if the resulting JSON Schema is an object type and returns it if so.\n *\n * @param schema - The schema definition to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, or a JSON Schema object.\n * @returns The extracted JSON Schema (draft-07) object if successful, otherwise undefined.\n */\nexport function extractJsonSchema(\n schema: unknown\n): JsonSchema7Type | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchema7ObjectType(schema))\n ) {\n let jsonSchema: JsonSchema7Type;\n if (isZod3Type(schema)) {\n jsonSchema = extractJsonSchema7(schema);\n } else if (isStandardJsonSchema(schema)) {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-07\"\n });\n } else {\n jsonSchema = schema;\n }\n\n if (isJsonSchema7ObjectType(jsonSchema)) {\n return jsonSchema;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `SchemaDefinition` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `SchemaDefinition` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractSchema(input: SchemaDefinitionInput): SchemaDefinition {\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n const schema = extractJsonSchema(input);\n if (schema) {\n return {\n schema,\n variant: \"zod3\",\n input\n };\n }\n } else if (isStandardJsonSchema(input)) {\n const schema = extractJsonSchema(input);\n if (schema) {\n return {\n schema,\n variant: \"standard-schema\",\n input\n };\n }\n } else if (isJsonSchema7ObjectType(input)) {\n const schema = extractJsonSchema(input);\n if (schema) {\n return {\n schema,\n variant: \"json-schema\",\n input\n };\n }\n } else if (isType(input)) {\n const schema = extractReflection(input);\n if (schema) {\n return {\n schema,\n variant: \"reflection\",\n input\n };\n }\n }\n }\n\n throw new Error(\n `Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * const schema = await extract(context, \"./schemas/*.ts\");\n * ```\n *\n * @param context - The plugin context used for resolving the schema definition input.\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param options - Optional overrides for the ESBuild configuration used during resolution.\n * @returns A promise that resolves to a SchemaDefinition containing the extracted JSON Schema and its variant, or the bytecode if JSON Schema extraction is not possible.\n */\nexport async function extract<TContext extends PluginContext = PluginContext>(\n context: TContext,\n input: SchemaDefinitionParameter,\n options: Partial<BuildOptions> = {}\n): Promise<SchemaDefinition> {\n if (isSchemaDefinition(input)) {\n return input;\n }\n\n let inputObject = input as SchemaDefinitionInput;\n if (isSetString(input) || isTypeDefinition(input)) {\n inputObject = await resolve<SchemaDefinitionInput>(\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 return extractSchema(inputObject);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAgB,kBACd,YAC6B;AAC7B,KAAI,CAAC,OAAO,WAAW,CACrB;AAGF,QAAO,uBAAuB,WAAW;;;;;;;;;;;AAY3C,SAAgB,kBACd,QAC6B;AAC7B,KACEA,cAAY,OAAO,KAClB,WAAW,OAAO,IACjB,qBAAqB,OAAO,IAC5B,wBAAwB,OAAO,GACjC;EACA,IAAI;AACJ,MAAI,WAAW,OAAO,CACpB,cAAa,mBAAmB,OAAO;WAC9B,qBAAqB,OAAO,CACrC,cAAa,OAAO,aAAa,WAAW,MAAM,EAChD,QAAQ,YACT,CAAC;MAEF,cAAa;AAGf,MAAI,wBAAwB,WAAW,CACrC,QAAO;;;;;;;;;;AAcb,SAAgB,cAAc,OAAgD;AAC5E,KAAIA,cAAY,MAAM,EACpB;MAAI,WAAW,MAAM,EAAE;GACrB,MAAM,SAAS,kBAAkB,MAAM;AACvC,OAAI,OACF,QAAO;IACL;IACA,SAAS;IACT;IACD;aAEM,qBAAqB,MAAM,EAAE;GACtC,MAAM,SAAS,kBAAkB,MAAM;AACvC,OAAI,OACF,QAAO;IACL;IACA,SAAS;IACT;IACD;aAEM,wBAAwB,MAAM,EAAE;GACzC,MAAM,SAAS,kBAAkB,MAAM;AACvC,OAAI,OACF,QAAO;IACL;IACA,SAAS;IACT;IACD;aAEM,OAAO,MAAM,EAAE;GACxB,MAAM,SAAS,kBAAkB,MAAM;AACvC,OAAI,OACF,QAAO;IACL;IACA,SAAS;IACT;IACD;;;AAKP,OAAM,IAAI,MACR,8KACD;;;;;;;;;;;;;;;AAgBH,eAAsB,QACpB,SACA,OACA,UAAiC,EAAE,EACR;AAC3B,KAAI,mBAAmB,MAAM,CAC3B,QAAO;CAGT,IAAI,cAAc;AAClB,KAAI,YAAY,MAAM,IAAI,iBAAiB,MAAM,CAC/C,eAAc,MAAM,QAClB,SACA,OACA,KAAK,SAAS,EACZ,SAAS,CACP,cAAc,SAAS;EACrB,YAAY;EACZ,OAAO;EACR,CAAC,CACH,EACF,CAAC,CACH;AAGH,QAAO,cAAc,YAAY"}
1
+ {"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchemaZod"],"sources":["../src/extract.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 { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport {\n isJsonSchemaObjectType,\n isStandardJsonSchema,\n JsonSchemaType\n} from \"@stryke/json\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport * as z3 from \"zod/v3\";\nimport { jsonSchemaToJtd } from \"./jtd\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isExtractedSchema,\n isJTDSchema,\n isSchema,\n isUntypedInput,\n isUntypedSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchemaLike,\n JTDSchemaType,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaMetadata,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema\n} from \"./types\";\n\n/**\n * Creates a hash string for a given schema definition input. The function checks the type of the input and generates a hash based on its content. If the input is a Zod schema, it hashes the JSON representation of its internal definition. If the input is a Standard JSON Schema, it hashes the JSON representation of its internal standard schema. If the input is already a JSON Schema object, it hashes its JSON representation directly. If the input is a reflected Deepkit Type object, it hashes its JSON representation. The resulting hash string can be used for caching or comparison purposes.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchemaObjectType(input)) {\n return murmurhash({ variant, input });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link @powerlines/deepkit/vendor/type#Type} into a JSON Schema (draft-07) representation.\n *\n * @remarks\n * This function delegates to an internal recursive walker that handles the full set of Deepkit reflection kinds.\n *\n * @param reflection - The reflected Deepkit Type to convert.\n * @returns A JSON Schema (draft-07) fragment representing the type, or `undefined` when no schema could be produced.\n */\nexport function extractReflection<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(reflection: Type): JTDSchemaType<TMetadata> | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema<TMetadata>(reflection);\n}\n\n/**\n * Extracts a JSON Type Definition (RFC 8927) schema from a given schema definition, if possible.\n *\n * @remarks\n * This function checks if the provided input is a Zod schema, a Standard JSON Schema, or already a JSON Schema object, extracts a JSON Schema fragment via the appropriate adapter (Zod and Standard Schema produce draft-07 fragments), and then converts that fragment into a valid JTD form suitable for AJV's JTD validator.\n *\n * @param schema - The schema definition to extract from. This can be a Zod schema, a Standard JSON Schema, or a JSON Schema object.\n * @returns The extracted JTD schema if successful, otherwise undefined.\n */\nexport function extractJsonSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: unknown): JTDSchemaType<TMetadata> | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchemaObjectType(schema) ||\n isUntypedInput(schema) ||\n isUntypedSchema(schema))\n ) {\n let jsonSchema: unknown;\n if (isZod3Type(schema)) {\n jsonSchema = extractJsonSchemaZod(schema);\n } else if (isStandardJsonSchema(schema)) {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n } else if (isUntypedInput(schema)) {\n jsonSchema = schema.$schema;\n } else {\n jsonSchema = schema;\n }\n\n const jtd = jsonSchemaToJtd<TMetadata>(jsonSchema as JsonSchemaLike);\n if (jtd) {\n return jtd;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJTDSchema(input)) {\n return \"jtd-schema\";\n } else if (isJsonSchemaObjectType(input)) {\n return \"json-schema\";\n } else if (isType(input)) {\n return \"reflection\";\n } else if (isUntypedInput(input) || isUntypedSchema(input)) {\n return \"untyped\";\n }\n }\n\n throw new Error(\n `Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts a JSON Schema object from a given schema definition input. The input can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding JSON Schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns the extracted JSON Schema if successful; otherwise, it throws an error.\n *\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param variant - The variant of the schema definition to extract.\n * @returns The extracted JSON Schema if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport async function extractSchemaSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JTDSchemaType<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JTDSchemaType<TMetadata> | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\"\n ) {\n const jsonSchema = extractJsonSchema<TMetadata>(input);\n if (jsonSchema) {\n schema = jsonSchemaToJtd<TMetadata>(jsonSchema);\n }\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection<TMetadata>(input as Type);\n } else if (resolvedVariant === \"jtd-schema\") {\n schema = input as JTDSchemaType<TMetadata>;\n }\n\n if (schema) {\n return schema;\n }\n\n throw new Error(\n `Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param variant - The variant of the schema definition to extract.\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractSource<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchemaType\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n } else if (variant === \"jtd-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"jtd-schema\",\n schema: input as JTDSchemaType<TMetadata>\n };\n }\n\n throw new Error(\n `Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extractSchema(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extractSchema(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extractSchema(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extractSchema(context, reflectionType);\n * ```\n *\n * @param context - The plugin context used for resolving the schema definition input.\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param options - Optional overrides for the ESBuild configuration used during resolution.\n * @returns A promise that resolves to a {@link ExtractedSchema} containing the extracted JSON Schema and its variant, or the bytecode if JSON Schema extraction is not possible.\n */\nexport async function extractSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<ExtractedSchema<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input;\n }\n\n if (isSchema<TMetadata>(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"jtd-schema\", input.schema),\n variant: \"jtd-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n if (variant === \"type-definition\") {\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as TypeDefinitionReference,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"jtd-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"type-definition\", \"json-schema\", \"jtd-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchemaSchema<TMetadata>(source.schema, source.variant),\n hash: extractHash(variant, input)\n };\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://github.com/colinhacks/zod\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The {@link Context | context} used for resolving the {@link Schema | schema} definition input.\n * @param input - The input object or string to extract the {@link Schema | schema} from. This can be {@link TypeDefinitionReference | a string that references a Typescript module}, a [Zod v3 schema](https://github.com/colinhacks/zod), any type that adheres to [the Standard JSON Schema specification](https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec), a [JSON Schema object](https://json-schema.org/), a [JTD schema object](https://ajv.js.org/json-type-definition.html), an [untyped schema](https://github.com/unjs/untyped), or a [TypeScript type reflection](https://deepkit.io/en/documentation/runtime-types/reflection).\n * @param options - Optional overrides for the [ESBuild configuration](https://esbuild.github.io/api/#general-options) used during resolution.\n * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.\n */\nexport async function extract<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<Schema<TMetadata>> {\n const result = await extractSchema<TMetadata>(context, input, options);\n\n return result;\n}\n"],"mappings":"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"}
package/dist/index.cjs CHANGED
@@ -1,17 +1,29 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_bundle = require('./bundle.cjs');
3
- const require_is_schema_definition = require('./is-schema-definition.cjs');
3
+ const require_codegen = require('./codegen.cjs');
4
+ const require_jtd = require('./jtd.cjs');
4
5
  const require_reflection = require('./reflection.cjs');
5
6
  const require_resolve = require('./resolve.cjs');
7
+ const require_type_checks = require('./type-checks.cjs');
6
8
  const require_extract = require('./extract.cjs');
7
9
 
8
10
  exports.bundle = require_bundle.bundle;
9
11
  exports.extract = require_extract.extract;
12
+ exports.extractHash = require_extract.extractHash;
10
13
  exports.extractJsonSchema = require_extract.extractJsonSchema;
11
14
  exports.extractReflection = require_extract.extractReflection;
15
+ exports.extractResolvedVariant = require_extract.extractResolvedVariant;
12
16
  exports.extractSchema = require_extract.extractSchema;
13
- exports.isSchemaDefinition = require_is_schema_definition.isSchemaDefinition;
14
- exports.objectReflectionToJsonSchema = require_reflection.objectReflectionToJsonSchema;
17
+ exports.extractSchemaSchema = require_extract.extractSchemaSchema;
18
+ exports.extractSource = require_extract.extractSource;
19
+ exports.extractVariant = require_extract.extractVariant;
20
+ exports.generateCode = require_codegen.generateCode;
21
+ exports.isExtractedSchema = require_type_checks.isExtractedSchema;
22
+ exports.isJTDSchema = require_type_checks.isJTDSchema;
23
+ exports.isSchema = require_type_checks.isSchema;
24
+ exports.isUntypedInput = require_type_checks.isUntypedInput;
25
+ exports.isUntypedSchema = require_type_checks.isUntypedSchema;
26
+ exports.jsonSchemaToJtd = require_jtd.jsonSchemaToJtd;
15
27
  exports.reflectionToJsonSchema = require_reflection.reflectionToJsonSchema;
16
28
  exports.resolve = require_resolve.resolve;
17
29
  exports.resolveModule = require_resolve.resolveModule;
package/dist/index.d.cts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { BundleOptions, bundle } from "./bundle.cjs";
2
- import { SchemaDefinition, SchemaDefinitionBase, SchemaDefinitionInput, SchemaDefinitionJsonSchema, SchemaDefinitionParameter, SchemaDefinitionReflection, SchemaDefinitionStandardSchema, SchemaDefinitionVariant, SchemaDefinitionZod3 } from "./types.cjs";
3
- import { extract, extractJsonSchema, extractReflection, extractSchema } from "./extract.cjs";
4
- import { isSchemaDefinition } from "./is-schema-definition.cjs";
5
- import { objectReflectionToJsonSchema, reflectionToJsonSchema } from "./reflection.cjs";
2
+ import { generateCode } from "./codegen.cjs";
3
+ import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.cjs";
4
+ import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.cjs";
5
+ import { jsonSchemaToJtd } from "./jtd.cjs";
6
+ import { reflectionToJsonSchema } from "./reflection.cjs";
6
7
  import { resolve, resolveModule, resolveReflection } from "./resolve.cjs";
7
- export { BundleOptions, SchemaDefinition, SchemaDefinitionBase, SchemaDefinitionInput, SchemaDefinitionJsonSchema, SchemaDefinitionParameter, SchemaDefinitionReflection, SchemaDefinitionStandardSchema, SchemaDefinitionVariant, SchemaDefinitionZod3, bundle, extract, extractJsonSchema, extractReflection, extractSchema, isSchemaDefinition, objectReflectionToJsonSchema, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
8
+ import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
9
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { BundleOptions, bundle } from "./bundle.mjs";
2
- import { SchemaDefinition, SchemaDefinitionBase, SchemaDefinitionInput, SchemaDefinitionJsonSchema, SchemaDefinitionParameter, SchemaDefinitionReflection, SchemaDefinitionStandardSchema, SchemaDefinitionVariant, SchemaDefinitionZod3 } from "./types.mjs";
3
- import { extract, extractJsonSchema, extractReflection, extractSchema } from "./extract.mjs";
4
- import { isSchemaDefinition } from "./is-schema-definition.mjs";
5
- import { objectReflectionToJsonSchema, reflectionToJsonSchema } from "./reflection.mjs";
2
+ import { generateCode } from "./codegen.mjs";
3
+ import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.mjs";
4
+ import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
5
+ import { jsonSchemaToJtd } from "./jtd.mjs";
6
+ import { reflectionToJsonSchema } from "./reflection.mjs";
6
7
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
7
- export { BundleOptions, SchemaDefinition, SchemaDefinitionBase, SchemaDefinitionInput, SchemaDefinitionJsonSchema, SchemaDefinitionParameter, SchemaDefinitionReflection, SchemaDefinitionStandardSchema, SchemaDefinitionVariant, SchemaDefinitionZod3, bundle, extract, extractJsonSchema, extractReflection, extractSchema, isSchemaDefinition, objectReflectionToJsonSchema, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
8
+ import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
9
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
package/dist/index.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  import { bundle } from "./bundle.mjs";
2
- import { isSchemaDefinition } from "./is-schema-definition.mjs";
3
- import { objectReflectionToJsonSchema, reflectionToJsonSchema } from "./reflection.mjs";
2
+ import { generateCode } from "./codegen.mjs";
3
+ import { jsonSchemaToJtd } from "./jtd.mjs";
4
+ import { reflectionToJsonSchema } from "./reflection.mjs";
4
5
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
5
- import { extract, extractJsonSchema, extractReflection, extractSchema } from "./extract.mjs";
6
+ import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
7
+ import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
6
8
 
7
- export { bundle, extract, extractJsonSchema, extractReflection, extractSchema, isSchemaDefinition, objectReflectionToJsonSchema, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
9
+ export { bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
package/dist/jtd.cjs ADDED
@@ -0,0 +1,385 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ let _stryke_type_checks = require("@stryke/type-checks");
4
+ let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
5
+
6
+ //#region src/jtd.ts
7
+ /**
8
+ * Maps a JSON Schema `format` annotation for integers to the closest JTD numeric type.
9
+ *
10
+ * @param format - The JSON Schema format hint to map.
11
+ * @returns The matching JTD numeric type, or `undefined` if no exact match exists.
12
+ */
13
+ function jsonSchemaIntegerFormatToJtd(format) {
14
+ switch (format) {
15
+ case "int8": return "int8";
16
+ case "uint8": return "uint8";
17
+ case "int16": return "int16";
18
+ case "uint16": return "uint16";
19
+ case "int32": return "int32";
20
+ case "uint32": return "uint32";
21
+ case void 0:
22
+ default: return;
23
+ }
24
+ }
25
+ /**
26
+ * Maps a JSON Schema `format` annotation for floating point numbers to the closest JTD numeric type.
27
+ *
28
+ * @param format - The JSON Schema format hint to map.
29
+ * @returns The matching JTD numeric type, or `undefined` if no exact match exists.
30
+ */
31
+ function jsonSchemaNumberFormatToJtd(format) {
32
+ switch (format) {
33
+ case "float":
34
+ case "float32": return "float32";
35
+ case "double":
36
+ case "float64": return "float64";
37
+ case void 0:
38
+ default: return;
39
+ }
40
+ }
41
+ /**
42
+ * Picks the smallest unsigned JTD integer type that can hold the provided bounds.
43
+ *
44
+ * @param minimum - The inclusive lower bound, when known.
45
+ * @param maximum - The inclusive upper bound, when known.
46
+ * @returns The narrowest unsigned JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as an unsigned integer.
47
+ */
48
+ function pickUnsignedIntegerType(minimum, maximum) {
49
+ if (minimum === void 0 || minimum < 0) return;
50
+ if (maximum === void 0) return;
51
+ if (maximum <= 255) return "uint8";
52
+ if (maximum <= 65535) return "uint16";
53
+ if (maximum <= 4294967295) return "uint32";
54
+ }
55
+ /**
56
+ * Picks the smallest signed JTD integer type that can hold the provided bounds.
57
+ *
58
+ * @param minimum - The inclusive lower bound, when known.
59
+ * @param maximum - The inclusive upper bound, when known.
60
+ * @returns The narrowest signed JTD integer type that can represent the range, or `undefined` if the range cannot be expressed as a signed integer.
61
+ */
62
+ function pickSignedIntegerType(minimum, maximum) {
63
+ if (minimum !== void 0 && maximum !== void 0 && minimum >= -128 && maximum <= 127) return "int8";
64
+ if (minimum !== void 0 && maximum !== void 0 && minimum >= -32768 && maximum <= 32767) return "int16";
65
+ return "int32";
66
+ }
67
+ /**
68
+ * Tests whether the provided value is a non-null object that can be inspected as a JSON Schema fragment.
69
+ *
70
+ * @param value - The value to test.
71
+ * @returns `true` if the value is a plain object suitable for JSON-Schema conversion.
72
+ */
73
+ function isJsonSchemaLike(value) {
74
+ return (0, _stryke_type_checks_is_set_object.isSetObject)(value);
75
+ }
76
+ /**
77
+ * Reads the JSON Schema `type` field as an array, normalising the single-string form.
78
+ *
79
+ * @param schema - The JSON Schema fragment to inspect.
80
+ * @returns The list of JSON Schema type names declared on the fragment.
81
+ */
82
+ function readTypes(schema) {
83
+ if (Array.isArray(schema.type)) return schema.type;
84
+ if (typeof schema.type === "string") return [schema.type];
85
+ return [];
86
+ }
87
+ /**
88
+ * Builds a JTD `metadata` object from the JSON Schema annotation keywords found on a fragment.
89
+ *
90
+ * @param schema - The source JSON Schema fragment.
91
+ * @returns A metadata bag suitable for attaching to a JTD form, or `undefined` if no annotations are present.
92
+ */
93
+ function collectMetadata(schema) {
94
+ const metadata = {};
95
+ if ((0, _stryke_type_checks.isSetString)(schema.description)) metadata.description = schema.description;
96
+ if ((0, _stryke_type_checks.isSetArray)(schema.examples)) metadata.examples = schema.examples;
97
+ if ((0, _stryke_type_checks.isSetArray)(schema.alias) && schema.alias.every(_stryke_type_checks.isSetString)) metadata.alias = schema.alias;
98
+ if ((0, _stryke_type_checks.isSetString)(schema.table)) metadata.default = schema.table;
99
+ if ((0, _stryke_type_checks.isSetString)(schema.title)) metadata.title = schema.title;
100
+ if (!(0, _stryke_type_checks.isUndefined)(schema.default)) metadata.default = schema.default;
101
+ if ((0, _stryke_type_checks.isBoolean)(schema.isHidden)) metadata.isHidden = schema.isHidden;
102
+ else if ((0, _stryke_type_checks.isBoolean)(schema.hidden)) metadata.isHidden = schema.hidden;
103
+ if ((0, _stryke_type_checks.isBoolean)(schema.isIgnored)) metadata.isIgnored = schema.isIgnored;
104
+ else if ((0, _stryke_type_checks.isBoolean)(schema.ignored)) metadata.isIgnored = schema.ignored;
105
+ if ((0, _stryke_type_checks.isBoolean)(schema.isReadonly)) metadata.isReadonly = schema.isReadonly;
106
+ else if ((0, _stryke_type_checks.isBoolean)(schema.readonly)) metadata.isReadonly = schema.readonly;
107
+ if ((0, _stryke_type_checks.isBoolean)(schema.isPrimaryKey)) metadata.isPrimaryKey = schema.isPrimaryKey;
108
+ else if ((0, _stryke_type_checks.isBoolean)(schema.primaryKey)) metadata.isPrimaryKey = schema.primaryKey;
109
+ if ((0, _stryke_type_checks.isBoolean)(schema.isInternal)) metadata.isInternal = schema.isInternal;
110
+ else if ((0, _stryke_type_checks.isBoolean)(schema.internal)) metadata.isInternal = schema.internal;
111
+ if ((0, _stryke_type_checks.isBoolean)(schema.isRuntime)) metadata.isRuntime = schema.isRuntime;
112
+ else if ((0, _stryke_type_checks.isBoolean)(schema.runtime)) metadata.isRuntime = schema.runtime;
113
+ if ((0, _stryke_type_checks.isSetArray)(schema.union)) metadata.union = schema.union;
114
+ return Object.keys(metadata).length > 0 ? metadata : void 0;
115
+ }
116
+ /**
117
+ * Attaches metadata and nullability flags to a JTD form, mutating and returning the form.
118
+ *
119
+ * @param form - The base JTD form to decorate.
120
+ * @param schema - The source JSON Schema fragment from which annotations are read.
121
+ * @param nullable - Whether the schema is nullable in JTD semantics.
122
+ * @returns The decorated JTD form.
123
+ */
124
+ function decorate(form, schema, nullable) {
125
+ if (nullable) form.nullable = true;
126
+ const metadata = collectMetadata(schema);
127
+ if (metadata) form.metadata = metadata;
128
+ return form;
129
+ }
130
+ /**
131
+ * Determines whether the supplied list of JSON Schema types collapses to `null` only.
132
+ *
133
+ * @param types - The normalized list of JSON Schema type names.
134
+ * @returns `true` if the only declared type is `null`.
135
+ */
136
+ function isNullOnly(types) {
137
+ return types.length > 0 && types.every((t) => t === "null");
138
+ }
139
+ /**
140
+ * Splits a `null` declaration away from a list of JSON Schema types.
141
+ *
142
+ * @param types - The normalized list of JSON Schema type names.
143
+ * @returns A tuple of `[nonNullTypes, nullable]` describing the remaining types and whether `null` was present.
144
+ */
145
+ function stripNull(types) {
146
+ const nullable = types.includes("null");
147
+ return {
148
+ types: types.filter((t) => t !== "null"),
149
+ nullable
150
+ };
151
+ }
152
+ /**
153
+ * Converts a JSON Schema `enum` keyword to a JTD enum form, stringifying values when required.
154
+ *
155
+ * @param values - The raw enum values from the JSON Schema fragment.
156
+ * @returns A JTD enum form, or `undefined` if the enum cannot be represented (e.g. empty list).
157
+ */
158
+ function enumToJtd(values) {
159
+ const strings = values.filter((v) => v !== null && v !== void 0).map((v) => String(v));
160
+ if (strings.length === 0) return;
161
+ return { enum: Array.from(new Set(strings)) };
162
+ }
163
+ /**
164
+ * Selects the most appropriate JTD numeric `type` value for a JSON Schema integer fragment.
165
+ *
166
+ * @param schema - The integer JSON Schema fragment.
167
+ * @returns The chosen JTD integer type.
168
+ */
169
+ function pickIntegerJtdType(schema) {
170
+ const mapped = jsonSchemaIntegerFormatToJtd(schema.format);
171
+ if (mapped) return mapped;
172
+ const unsigned = pickUnsignedIntegerType(schema.minimum, schema.maximum);
173
+ if (unsigned) return unsigned;
174
+ return pickSignedIntegerType(schema.minimum, schema.maximum) ?? "int32";
175
+ }
176
+ /**
177
+ * Selects the most appropriate JTD numeric `type` value for a JSON Schema number fragment.
178
+ *
179
+ * @param schema - The number JSON Schema fragment.
180
+ * @returns The chosen JTD floating point type.
181
+ */
182
+ function pickNumberJtdType(schema) {
183
+ return jsonSchemaNumberFormatToJtd(schema.format) ?? "float64";
184
+ }
185
+ /**
186
+ * Selects the JTD string `type` value for a JSON Schema string fragment, mapping `format: "date-time"` to `timestamp`.
187
+ *
188
+ * @param schema - The string JSON Schema fragment.
189
+ * @returns The chosen JTD string type.
190
+ */
191
+ function pickStringJtdType(schema) {
192
+ if (schema.format === "date-time") return "timestamp";
193
+ return "string";
194
+ }
195
+ /**
196
+ * Converts a JSON Schema object fragment into a JTD properties form.
197
+ *
198
+ * @param schema - The object JSON Schema fragment.
199
+ * @param nullable - Whether the resulting JTD form should be nullable.
200
+ * @returns The JTD properties form representing the object.
201
+ */
202
+ function objectToJtd(schema, nullable) {
203
+ const required = new Set(schema.required ?? []);
204
+ const properties = {};
205
+ const optionalProperties = {};
206
+ const metadata = { default: schema.default ?? {} };
207
+ if (schema.properties) for (const [key, value] of Object.entries(schema.properties)) {
208
+ if (!(0, _stryke_type_checks.isUndefined)(value.default)) metadata.default[key] = value.default;
209
+ const converted = jsonSchemaToJtd(value);
210
+ if (!converted) continue;
211
+ if (required.has(key)) properties[key] = converted;
212
+ else optionalProperties[key] = converted;
213
+ }
214
+ const hasProperties = Object.keys(properties).length > 0;
215
+ const hasOptional = Object.keys(optionalProperties).length > 0;
216
+ if (!hasProperties && !hasOptional && isJsonSchemaLike(schema.additionalProperties)) {
217
+ const values = jsonSchemaToJtd(schema.additionalProperties);
218
+ if (values) return decorate({
219
+ metadata,
220
+ values
221
+ }, schema, nullable);
222
+ }
223
+ if (!hasProperties && !hasOptional && schema.patternProperties) {
224
+ const first = Object.values(schema.patternProperties)[0];
225
+ if (first) {
226
+ const values = jsonSchemaToJtd(first);
227
+ if (values) return decorate({
228
+ metadata,
229
+ values
230
+ }, schema, nullable);
231
+ }
232
+ }
233
+ const form = { metadata };
234
+ if (hasProperties) form.properties = properties;
235
+ else if (!hasOptional) form.properties = {};
236
+ if (hasOptional) form.optionalProperties = optionalProperties;
237
+ if (schema.additionalProperties === true || isJsonSchemaLike(schema.additionalProperties) || schema.patternProperties !== void 0) form.additionalProperties = true;
238
+ return decorate(form, schema, nullable);
239
+ }
240
+ /**
241
+ * Converts a JSON Schema array fragment into a JTD elements form.
242
+ *
243
+ * @param schema - The array JSON Schema fragment.
244
+ * @param nullable - Whether the resulting JTD form should be nullable.
245
+ * @returns The JTD elements form representing the array.
246
+ */
247
+ function arrayToJtd(schema, nullable) {
248
+ let elementSchema;
249
+ if (Array.isArray(schema.items)) elementSchema = schema.items[0];
250
+ else if (schema.items) elementSchema = schema.items;
251
+ return decorate({ elements: (elementSchema ? jsonSchemaToJtd(elementSchema) : {}) ?? {} }, schema, nullable);
252
+ }
253
+ /**
254
+ * Attempts to detect and emit a JTD discriminator form from a JSON Schema `oneOf` or `anyOf` fragment.
255
+ *
256
+ * @param schemas - The list of candidate JSON Schema fragments.
257
+ * @param nullable - Whether the resulting JTD form should be nullable.
258
+ * @returns A discriminator form when every branch shares a single tag property, otherwise `undefined`.
259
+ */
260
+ function tryDiscriminator(schemas, nullable) {
261
+ if (schemas.length < 2) return;
262
+ let candidateKey;
263
+ const mapping = {};
264
+ for (const branch of schemas) {
265
+ if (!isJsonSchemaLike(branch) || !branch.properties) return;
266
+ const constantTags = Object.entries(branch.properties).filter(([, value]) => isJsonSchemaLike(value) && (typeof value.const === "string" || Array.isArray(value.enum) && value.enum.length === 1 && typeof value.enum[0] === "string"));
267
+ if (constantTags.length === 0) return;
268
+ const [tagKey, tagSchema] = constantTags[0];
269
+ if (!candidateKey) candidateKey = tagKey;
270
+ else if (candidateKey !== tagKey) return;
271
+ const tag = typeof tagSchema.const === "string" ? tagSchema.const : tagSchema.enum?.[0];
272
+ const { [tagKey]: _omit, ...restProperties } = branch.properties;
273
+ const restRequired = (branch.required ?? []).filter((k) => k !== tagKey);
274
+ const branchForm = jsonSchemaToJtd({
275
+ ...branch,
276
+ properties: restProperties,
277
+ required: restRequired
278
+ });
279
+ if (!branchForm || !(0, _stryke_type_checks_is_set_object.isSetObject)(branchForm) || "ref" in branchForm) return;
280
+ mapping[tag] = branchForm;
281
+ }
282
+ if (!candidateKey) return;
283
+ const form = {
284
+ discriminator: candidateKey,
285
+ mapping
286
+ };
287
+ if (nullable) form.nullable = true;
288
+ return form;
289
+ }
290
+ /**
291
+ * Converts a JSON Schema fragment (draft-07 style, as produced by `zod-to-json-schema`, Standard Schema, etc.) into a valid JSON Type Definition (RFC 8927) schema.
292
+ *
293
+ * Unsupported JSON Schema keywords (`pattern`, `const`, `minItems`, `maxItems`, `uniqueItems`, etc.) are dropped — JTD intentionally omits these. Annotation keywords (`description`, `title`, `default`, `examples`) are preserved under the JTD `metadata` field.
294
+ *
295
+ * @param schema - The JSON Schema fragment to convert.
296
+ * @returns A valid JTD form, or `undefined` if the input cannot be represented.
297
+ */
298
+ function jsonSchemaToJtd(schema) {
299
+ if (!isJsonSchemaLike(schema)) return;
300
+ if ((0, _stryke_type_checks.isSetString)(schema.$ref)) {
301
+ const match = /^#\/(?:definitions|\$defs)\/(.+)$/.exec(schema.$ref);
302
+ if (match) return { ref: match[1] };
303
+ }
304
+ if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {
305
+ const merged = schema.allOf.reduce((acc, current) => mergeJsonSchema(acc, current), {});
306
+ const { allOf: _allOf, ...rest } = schema;
307
+ return jsonSchemaToJtd(mergeJsonSchema(merged, rest));
308
+ }
309
+ const rawTypes = readTypes(schema);
310
+ const { types: nonNullTypes, nullable: typeIsNullable } = stripNull(rawTypes);
311
+ const nullable = Boolean(schema.nullable) || typeIsNullable;
312
+ if (isNullOnly(rawTypes)) return decorate({}, schema, true);
313
+ if (Array.isArray(schema.enum)) {
314
+ const enumForm = enumToJtd(schema.enum);
315
+ if (enumForm) return decorate(enumForm, schema, nullable);
316
+ }
317
+ if ((0, _stryke_type_checks.isSetString)(schema.const)) return decorate({ enum: [schema.const] }, schema, nullable);
318
+ const union = schema.oneOf ?? schema.anyOf;
319
+ if (Array.isArray(union) && union.length > 0) {
320
+ const branches = union.filter(isJsonSchemaLike);
321
+ const onlyNullBranches = branches.filter((b) => readTypes(b).includes("null"));
322
+ const nonNullBranches = branches.filter((b) => !isNullOnly(readTypes(b)) && readTypes(b).join() !== "null");
323
+ const unionNullable = nullable || onlyNullBranches.length > 0;
324
+ if (nonNullBranches.length === 1) {
325
+ const collapsed = jsonSchemaToJtd(nonNullBranches[0]);
326
+ if (collapsed) return decorate(collapsed, schema, unionNullable);
327
+ }
328
+ const discriminated = tryDiscriminator(nonNullBranches, unionNullable);
329
+ if (discriminated) {
330
+ const metadata = collectMetadata(schema);
331
+ if (metadata) discriminated.metadata = metadata;
332
+ return discriminated;
333
+ }
334
+ const fallback = decorate({}, schema, unionNullable);
335
+ const metadata = fallback.metadata ?? {};
336
+ metadata.union = union;
337
+ fallback.metadata = metadata;
338
+ return fallback;
339
+ }
340
+ if (nonNullTypes.includes("object") || schema.properties || schema.patternProperties || isJsonSchemaLike(schema.additionalProperties)) {
341
+ const result = objectToJtd(schema, nullable);
342
+ const definitions = schema.definitions ?? schema.$defs;
343
+ if (definitions && Object.keys(definitions).length > 0) {
344
+ const converted = {};
345
+ for (const [key, value] of Object.entries(definitions)) {
346
+ const def = jsonSchemaToJtd(value);
347
+ if (def) converted[key] = def;
348
+ }
349
+ if (Object.keys(converted).length > 0) result.definitions = converted;
350
+ }
351
+ return result;
352
+ }
353
+ if (nonNullTypes.includes("array")) return arrayToJtd(schema, nullable);
354
+ if (nonNullTypes.length === 1) {
355
+ const t = nonNullTypes[0];
356
+ if (t === "string") return decorate({ type: pickStringJtdType(schema) }, schema, nullable);
357
+ if (t === "boolean") return decorate({ type: "boolean" }, schema, nullable);
358
+ if (t === "integer") return decorate({ type: pickIntegerJtdType(schema) }, schema, nullable);
359
+ if (t === "number") return decorate({ type: pickNumberJtdType(schema) }, schema, nullable);
360
+ }
361
+ if (nonNullTypes.length > 1) return decorate({}, schema, nullable);
362
+ return decorate({}, schema, nullable);
363
+ }
364
+ /**
365
+ * Shallow-merges two JSON Schema fragments, combining `required` arrays and `properties` maps.
366
+ *
367
+ * @param left - The base schema fragment.
368
+ * @param right - The schema fragment to merge into the base.
369
+ * @returns A merged schema fragment. Neither input is mutated.
370
+ */
371
+ function mergeJsonSchema(left, right) {
372
+ const merged = {
373
+ ...left,
374
+ ...right
375
+ };
376
+ if (left.properties || right.properties) merged.properties = {
377
+ ...left.properties ?? {},
378
+ ...right.properties ?? {}
379
+ };
380
+ if (left.required || right.required) merged.required = Array.from(new Set([...left.required ?? [], ...right.required ?? []]));
381
+ return merged;
382
+ }
383
+
384
+ //#endregion
385
+ exports.jsonSchemaToJtd = jsonSchemaToJtd;
package/dist/jtd.d.cts ADDED
@@ -0,0 +1,15 @@
1
+ import { JTDSchemaType, JsonSchemaLike, SchemaMetadata } from "./types.cjs";
2
+
3
+ //#region src/jtd.d.ts
4
+ /**
5
+ * Converts a JSON Schema fragment (draft-07 style, as produced by `zod-to-json-schema`, Standard Schema, etc.) into a valid JSON Type Definition (RFC 8927) schema.
6
+ *
7
+ * Unsupported JSON Schema keywords (`pattern`, `const`, `minItems`, `maxItems`, `uniqueItems`, etc.) are dropped — JTD intentionally omits these. Annotation keywords (`description`, `title`, `default`, `examples`) are preserved under the JTD `metadata` field.
8
+ *
9
+ * @param schema - The JSON Schema fragment to convert.
10
+ * @returns A valid JTD form, or `undefined` if the input cannot be represented.
11
+ */
12
+ declare function jsonSchemaToJtd<TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>>(schema: JsonSchemaLike | undefined | null): JTDSchemaType<TMetadata> | undefined;
13
+ //#endregion
14
+ export { jsonSchemaToJtd };
15
+ //# sourceMappingURL=jtd.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jtd.d.cts","names":[],"sources":["../src/jtd.ts"],"mappings":";;;;;AAgjBA;;;;;;iBAAgB,eAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CAEpD,MAAA,EAAQ,cAAA,sBACP,aAAA,CAAc,SAAA"}
package/dist/jtd.d.mts ADDED
@@ -0,0 +1,15 @@
1
+ import { JTDSchemaType, JsonSchemaLike, SchemaMetadata } from "./types.mjs";
2
+
3
+ //#region src/jtd.d.ts
4
+ /**
5
+ * Converts a JSON Schema fragment (draft-07 style, as produced by `zod-to-json-schema`, Standard Schema, etc.) into a valid JSON Type Definition (RFC 8927) schema.
6
+ *
7
+ * Unsupported JSON Schema keywords (`pattern`, `const`, `minItems`, `maxItems`, `uniqueItems`, etc.) are dropped — JTD intentionally omits these. Annotation keywords (`description`, `title`, `default`, `examples`) are preserved under the JTD `metadata` field.
8
+ *
9
+ * @param schema - The JSON Schema fragment to convert.
10
+ * @returns A valid JTD form, or `undefined` if the input cannot be represented.
11
+ */
12
+ declare function jsonSchemaToJtd<TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>>(schema: JsonSchemaLike | undefined | null): JTDSchemaType<TMetadata> | undefined;
13
+ //#endregion
14
+ export { jsonSchemaToJtd };
15
+ //# sourceMappingURL=jtd.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jtd.d.mts","names":[],"sources":["../src/jtd.ts"],"mappings":";;;;;AAgjBA;;;;;;iBAAgB,eAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CAEpD,MAAA,EAAQ,cAAA,sBACP,aAAA,CAAc,SAAA"}