Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/add-schema-is-non-blank.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

Add `Schema.isNonBlank` to reject empty and whitespace-only strings while preserving accepted strings unchanged, including surrounding whitespace. Add `SchemaRepresentation.isNonBlankReviver` to reconstruct persisted checks.
5 changes: 5 additions & 0 deletions .changeset/schema-is-well-formed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Add `Schema.isWellFormed()` to validate Unicode strings and generate well-formed examples with `Arbitrary.schema`.
5 changes: 5 additions & 0 deletions .changeset/standard-json-schema-openapi-3-0.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": minor
---

Support the `openapi-3.0` target in `Schema.toStandardJSONSchemaV1`.
173 changes: 173 additions & 0 deletions packages/effect/src/JsonSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -798,6 +798,28 @@ export function toMultiDocumentComponents(
}
}

/**
* Converts a `Document<"draft-2020-12">` to OpenAPI 3.0 Schema Objects for a
* standalone schema.
*
* This builds on the Draft-04 conversion, so definitions are referenced via
* `#/definitions/<name>` rather than `#/components/schemas/<name>`. It writes
* `{ type: "null" }` as `nullable: true` on a typed `anyOf` branch, and as
* `{ enum: [null] }` where no such branch exists, because `nullable` only
* applies next to `type`. It also splits `type` arrays, writes the first of
* `examples` as `example` and drops the root `$schema`. Tuples, pattern
* properties, dependencies and schema identifiers throw.
*
* @internal
*/
export function toStandaloneOpenApi3_0(
document: Document<"draft-2020-12">
): { readonly schema: JsonSchema; readonly definitions: Definitions } {
return convertDocument(document, openApi30Adapter, {
booleanAdapter: (schema) => schema ? {} : { not: {} }
})
}

/** @internal */
export const VALID_OPEN_API_COMPONENTS_SCHEMAS_KEY_REGEXP = /^[a-zA-Z0-9.\-_]+$/

Expand Down Expand Up @@ -1753,3 +1775,154 @@ function convertDraft04ExclusiveBound(
InternalRecord.assignProperty(out, boundKey, bound)
}
}

const OPEN_API_30_TARGET_COLLISIONS = ["discriminator", "example", "externalDocs", "nullable", "xml"]
const OPEN_API_30_UNSUPPORTED_KEYWORDS = [
"$anchor",
"$id",
"dependentRequired",
"dependentSchemas",
"patternProperties",
"prefixItems"
]
// Keywords that `nullable` cannot be combined with, because they would also
// apply to `null` once the null branch is merged into the typed branch.
const OPEN_API_30_NULLABLE_BRANCH_BLOCKERS = ["$ref", "allOf", "anyOf", "contains", "if", "not", "oneOf"]
const OPEN_API_30_HOISTABLE_KEYWORDS = new Set([
"$comment",
"default",
"deprecated",
"description",
"examples",
"readOnly",
"title",
"writeOnly"
])

function openApi30Adapter(source: JsonSchema, context: Context): JsonSchema {
rejectKeywordCollisions(source, OPEN_API_30_TARGET_COLLISIONS, "OpenAPI 3.0", "Draft 2020-12")
for (const key of OPEN_API_30_UNSUPPORTED_KEYWORDS) {
if (Object.hasOwn(source, key)) {
unsupported(
key,
"OpenAPI 3.0",
key === "prefixItems" ? "items must be a single schema" : "the target dialect has no equivalent"
)
}
}
if (Object.hasOwn(source, "$schema") && !isMetaSchemaUri(source.$schema, META_SCHEMA_URI_DRAFT_2020_12)) {
unsupported("$schema", "OpenAPI 3.0", "a Schema Object cannot declare a dialect")
}

const nullableIndex = getOpenApi30NullableIndex(source)
const out = nullableIndex === undefined
? draft04Adapter(source, context)
: convertOpenApi30NullableAnyOf(source, source.anyOf as ReadonlyArray<unknown>, nullableIndex, context)

delete out.$schema
convertOpenApi30Type(out)
if (Array.isArray(out.examples)) {
const examples = out.examples
delete out.examples
if (examples.length > 0) InternalRecord.assignProperty(out, "example", examples[0])
}
return out
}

// Returns the `anyOf` branch that can absorb the `{ type: "null" }` branches
// as `nullable: true`.
function getOpenApi30NullableIndex(source: JsonSchema): number | undefined {
if (!Array.isArray(source.anyOf) || Object.hasOwn(source, "$ref") || !source.anyOf.some(isOpenApi30NullSchema)) {
return undefined
}
const index = source.anyOf.findIndex((branch) =>
Predicate.isObject(branch) &&
typeof branch.type === "string" &&
branch.type !== "null" &&
!OPEN_API_30_NULLABLE_BRANCH_BLOCKERS.some((key) => Object.hasOwn(branch, key)) &&
!(Object.hasOwn(branch, "const") && Object.hasOwn(branch, "enum"))
)
return index === -1 ? undefined : index
}

function isOpenApi30NullSchema(schema: unknown): boolean {
return Predicate.isObject(schema) && schema.type === "null" && Object.keys(schema).length === 1
}

function convertOpenApi30NullableAnyOf(
source: JsonSchema,
anyOf: ReadonlyArray<unknown>,
nullableIndex: number,
context: Context
): JsonSchema {
const rest: JsonSchema = {}
for (const key of Object.keys(source)) {
if (key !== "anyOf") InternalRecord.assignProperty(rest, key, source[key])
}
const branches = anyOf.flatMap((branch, index) => isOpenApi30NullSchema(branch) ? [] : [index])
const nullableBranch = anyOf[nullableIndex] as JsonSchema

if (
branches.length === 1 &&
Object.keys(rest).every((key) => OPEN_API_30_HOISTABLE_KEYWORDS.has(key) && !Object.hasOwn(nullableBranch, key))
) {
const out = context.schemaAt(nullableBranch, ["anyOf", String(nullableIndex)], []) as JsonSchema
setOpenApi30Nullable(out)
const annotations = draft04Adapter(rest, context)
for (const key of Object.keys(annotations)) InternalRecord.assignProperty(out, key, annotations[key])
return out
}

const out = draft04Adapter(rest, context)
InternalRecord.assignProperty(
out,
"anyOf",
branches.map((sourceIndex, targetIndex) => {
const branch = context.schemaAt(
anyOf[sourceIndex],
["anyOf", String(sourceIndex)],
["anyOf", String(targetIndex)]
) as JsonSchema
if (sourceIndex === nullableIndex) {
setOpenApi30Nullable(branch)
}
return branch
})
)
return out
}

function setOpenApi30Nullable(out: JsonSchema): void {
InternalRecord.assignProperty(out, "nullable", true)
if (Array.isArray(out.enum) && !out.enum.includes(null)) {
InternalRecord.assignProperty(out, "enum", [...out.enum, null])
}
}

function convertOpenApi30Type(out: JsonSchema): void {
const type = out.type
if (type !== "null" && !Array.isArray(type)) {
return
}
const types = Array.isArray(type) ? type.filter((type) => type !== "null") : []
const nullable = Array.isArray(type) && types.length < type.length
delete out.type
if (types.length === 0) {
// OpenAPI 3.0 has no `null` type, and `nullable` requires a `type`.
InternalRecord.assignProperty(
out,
"enum",
Array.isArray(out.enum) ? out.enum.filter((value) => value === null) : [null]
)
} else if (types.length === 1) {
InternalRecord.assignProperty(out, "type", types[0])
if (nullable) InternalRecord.assignProperty(out, "nullable", true)
} else {
const anyOf = types.map((type, index): JsonSchema => index === 0 && nullable ? { type, nullable: true } : { type })
if (Object.hasOwn(out, "anyOf")) {
appendAllOf(out, { anyOf })
} else {
InternalRecord.assignProperty(out, "anyOf", anyOf)
}
}
}
62 changes: 62 additions & 0 deletions packages/effect/src/Schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import * as SchemaTransformation from "./SchemaTransformation.ts"
import * as SemVer_ from "./SemVer.ts"
import * as SemVerRange_ from "./SemVerRange.ts"
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "./StandardSchema.ts"
import * as Str from "./String.ts"
import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts"
import * as Struct_ from "./Struct.ts"
import type { IsUnion, RequiredKeys } from "./Types.ts"
Expand Down Expand Up @@ -6919,6 +6920,66 @@ export function isTrimmed(annotations?: Annotations.Filter) {
}
)
}

/**
* Checks for at least one non-whitespace character, preserving the string
* unchanged, including leading and trailing whitespace.
*
* **When to use**
*
* Use when free-form text is required. To also forbid surrounding whitespace,
* combine {@link isNonEmpty} with {@link isTrimmed} instead.
*
* **Details**
*
* Rejects empty and whitespace-only strings using the same whitespace semantics
* as `String.hasNonWhitespace`. Supports JSON Schema pattern output and arbitrary
* generation through {@link isPattern}.
*
* @stability unstable
* @category validation
* @since 4.3.0
*/
export function isNonBlank(annotations?: Annotations.Filter) {
return isPattern(Str.NON_WHITESPACE_REGEXP, {
expected: "a string with at least one non-whitespace character",
representation: {
id: "effect/schema/isNonBlank",
payload: null
},
...annotations
})
}
/**
* Validates that a string contains no unpaired UTF-16 surrogates.
*
* **When to use**
*
* Use when text must cross an encoding boundary that requires well-formed Unicode.
*
* **Details**
*
* Accepts empty strings and supplementary characters such as emoji. Arbitrary
* generation preserves complete surrogate pairs when shrinking examples.
* JSON Schema expresses this check as a Unicode pattern.
*
* @see {@link isMaxCodePoints} for limiting the code point count
* @stability stable
* @category validation
* @since 4.3.0
*/
export function isWellFormed(annotations?: Annotations.Filter) {
return makeFilter(Str.isWellFormed, {
expected: "a well-formed Unicode string",
representation: {
id: "effect/schema/isWellFormed",
payload: null
},
toJsonSchema: () => ({ pattern: /^[^\uD800-\uDFFF]*$/u.source }),
arbitraryConstraint: { wellFormed: true },
...annotations
})
}
/**
* Validates that a string matches the specified regular expression pattern.
*
Expand Down Expand Up @@ -19091,6 +19152,7 @@ export declare namespace Annotations {
readonly maxLength?: number | undefined
readonly minCodePoints?: number | undefined
readonly maxCodePoints?: number | undefined
readonly wellFormed?: true | undefined
readonly minSize?: number | undefined
readonly maxSize?: number | undefined
readonly minProperties?: number | undefined
Expand Down
31 changes: 31 additions & 0 deletions packages/effect/src/SchemaRepresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,37 @@ export const isTrimmedReviver: FilterReviver<null> = makeReviverFilter(
({ annotations }) => Schema.isTrimmed(annotations)
)

/**
* Reconstructs persisted {@link Schema.isNonBlank} checks.
*
* @stability unstable
* @category validation
* @since 4.3.0
*/
export const isNonBlankReviver: FilterReviver<null> = makeReviverFilter(
"effect/schema/isNonBlank",
Schema.Null,
({ annotations }) => Schema.isNonBlank(annotations)
)

/**
* Reviver for persisted `isWellFormed` checks.
*
* **When to use**
*
* Use when reconstructing documents containing checks created by {@link Schema.isWellFormed}.
*
* @see {@link Schema.isWellFormed} for creating the corresponding check
* @stability stable
* @category validation
* @since 4.3.0
*/
export const isWellFormedReviver: FilterReviver<null> = makeReviverFilter(
"effect/schema/isWellFormed",
Schema.Null,
({ annotations }) => Schema.isWellFormed(annotations)
)

/**
* Reviver for persisted `isPattern` checks.
*
Expand Down
5 changes: 4 additions & 1 deletion packages/effect/src/String.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,9 @@ interface WellFormedNative {
export const isWellFormed = (self: string): boolean =>
(self as WellFormedNative).isWellFormed?.() ?? !loneSurrogate.test(self)

/** @internal */
export const NON_WHITESPACE_REGEXP = /\S/u

/**
* Checks whether a string contains at least one non-whitespace character.
*
Expand All @@ -502,7 +505,7 @@ export const isWellFormed = (self: string): boolean =>
* @category predicates
* @since 4.2.0
*/
export const hasNonWhitespace = (self: string): boolean => /\S/u.test(self)
export const hasNonWhitespace = (self: string): boolean => NON_WHITESPACE_REGEXP.test(self)

/**
* Returns the JavaScript string length, measured in UTF-16 code units.
Expand Down
Loading
Loading