@open-wa/schema 5.6.7 → 5.10.0
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/calling-media--BLrFrPc.cjs.map +1 -1
- package/dist/calling-media-BNTYvogE.mjs.map +1 -1
- package/dist/{calling-media-CeGgSzhw.d.cts → calling-media-TZ9L95OH.d.cts} +2 -1
- package/dist/{calling-media-CeGgSzhw.d.cts.map → calling-media-TZ9L95OH.d.cts.map} +1 -1
- package/dist/{calling-media-CeGgSzhw.d.mts → calling-media-TZ9L95OH.d.mts} +2 -1
- package/dist/{calling-media-CeGgSzhw.d.mts.map → calling-media-TZ9L95OH.d.mts.map} +1 -1
- package/dist/calling-media.d.cts +1 -1
- package/dist/calling-media.d.mts +1 -1
- package/dist/generated/index.cjs +1 -1
- package/dist/generated/index.d.cts +141 -581
- package/dist/generated/index.d.cts.map +1 -1
- package/dist/generated/index.d.mts +141 -581
- package/dist/generated/index.d.mts.map +1 -1
- package/dist/generated/index.mjs +1 -1
- package/dist/{index-HeicIada.d.cts → index-BETdayaV.d.cts} +53 -232
- package/dist/index-BETdayaV.d.cts.map +1 -0
- package/dist/{index-C3kjyOe-.d.mts → index-DH0WRSA7.d.mts} +53 -232
- package/dist/index-DH0WRSA7.d.mts.map +1 -0
- package/dist/index.cjs +7 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -3
- package/dist/{interactive-DxUwKpzK.d.cts → interactive-BE_M4nur.d.cts} +14 -6
- package/dist/interactive-BE_M4nur.d.cts.map +1 -0
- package/dist/{interactive-DxUwKpzK.d.mts → interactive-BE_M4nur.d.mts} +14 -6
- package/dist/interactive-BE_M4nur.d.mts.map +1 -0
- package/dist/interactive-ClvvgmVP.cjs +630 -0
- package/dist/interactive-ClvvgmVP.cjs.map +1 -0
- package/dist/interactive-Dec4HB2U.mjs +475 -0
- package/dist/interactive-Dec4HB2U.mjs.map +1 -0
- package/dist/interactive.cjs +26 -304
- package/dist/interactive.d.cts +2 -2
- package/dist/interactive.d.mts +2 -2
- package/dist/interactive.mjs +2 -283
- package/dist/methods/index.cjs +1 -1
- package/dist/methods/index.d.cts +1 -1
- package/dist/methods/index.d.mts +1 -1
- package/dist/methods/index.mjs +1 -1
- package/dist/{methods-QZbG0hN2.cjs → methods-9kRJiEdZ.cjs} +14 -78
- package/dist/methods-9kRJiEdZ.cjs.map +1 -0
- package/dist/{methods-CGm5G9VI.mjs → methods-NixIgGkq.mjs} +6 -64
- package/dist/methods-NixIgGkq.mjs.map +1 -0
- package/package.json +3 -3
- package/src/__tests__/booking-time.contract.test.ts +88 -0
- package/src/booking-time.ts +39 -0
- package/src/calling-media.ts +2 -0
- package/src/calling.ts +1 -0
- package/src/common-types.ts +1 -1
- package/src/effect-projection.ts +90 -47
- package/src/generated/asyncapi.json +191 -89
- package/src/generated/openapi.json +1681 -1307
- package/src/interactive.ts +12 -1
- package/src/methods/calls.ts +2 -2
- package/dist/index-C3kjyOe-.d.mts.map +0 -1
- package/dist/index-HeicIada.d.cts.map +0 -1
- package/dist/interactive-DxUwKpzK.d.cts.map +0 -1
- package/dist/interactive-DxUwKpzK.d.mts.map +0 -1
- package/dist/interactive.cjs.map +0 -1
- package/dist/interactive.mjs.map +0 -1
- package/dist/methods-CGm5G9VI.mjs.map +0 -1
- package/dist/methods-QZbG0hN2.cjs.map +0 -1
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { expect, test } from 'vitest';
|
|
2
|
+
import { Schema, SchemaGetter } from 'effect';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { BookingTimestampSchema, normalizeBookingTimestamp, type BookingTimestamp } from '../booking-time';
|
|
5
|
+
import { BookingTimestampRegistrySchema, InteractiveContentSchema, defineInteractiveMessage, type DecodedInteractiveContent } from '../interactive';
|
|
6
|
+
import { projectEffectSchema } from '../effect-projection';
|
|
7
|
+
import { CallSnapshotSchema } from '../calling';
|
|
8
|
+
import { EventInputRegistrySchema } from '../whatsapp-event-registry';
|
|
9
|
+
|
|
10
|
+
type Assert<T extends true> = T;
|
|
11
|
+
type Equal<A, B> = [A, B] extends [B, A] ? true : false;
|
|
12
|
+
export type RegistryAcceptsTimestampStrings = Assert<Equal<z.input<typeof BookingTimestampRegistrySchema>, string>>;
|
|
13
|
+
export type RegistryReturnsEffectBrand = Assert<Equal<z.output<typeof BookingTimestampRegistrySchema>, BookingTimestamp>>;
|
|
14
|
+
export type DecoderReturnsEffectBrand = Assert<Equal<ReturnType<typeof normalizeBookingTimestamp>, BookingTimestamp>>;
|
|
15
|
+
type ParsedBooking = Extract<DecodedInteractiveContent, { type: 'booking' }>;
|
|
16
|
+
export type ParsedBookingRequiresBrand = Assert<Equal<ParsedBooking['booking']['startAt'], BookingTimestamp>>;
|
|
17
|
+
export type RawStringsCannotBeParsedTimestamps = Assert<string extends BookingTimestamp ? false : true>;
|
|
18
|
+
|
|
19
|
+
test('Effect and the serving projection decode offsets and fractions and encode canonical UTC seconds', () => {
|
|
20
|
+
const input = '2026-07-26T00:00:00.987+01:00';
|
|
21
|
+
const expected = '2026-07-25T23:00:00Z';
|
|
22
|
+
const decoded = normalizeBookingTimestamp(input);
|
|
23
|
+
expect(decoded).toBe(expected);
|
|
24
|
+
expect(Schema.encodeSync(BookingTimestampSchema)(decoded)).toBe(expected);
|
|
25
|
+
expect(BookingTimestampRegistrySchema.parse(input)).toBe(expected);
|
|
26
|
+
expect(z.encode(BookingTimestampRegistrySchema, decoded)).toBe(expected);
|
|
27
|
+
expect(z.safeEncode(BookingTimestampRegistrySchema, input as BookingTimestamp).success).toBe(false);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
test('invalid calendar dates and ambiguous timestamps fail in both Effect and the projection', () => {
|
|
31
|
+
const invalid = ['2026-02-29T14:00:00Z', '2026-04-31T14:00:00Z', '2026-13-01T14:00:00Z',
|
|
32
|
+
'2026-10-26T24:00:00Z', '2026-10-26T14:00:00+24:00', '2026-10-26T14:00:00', '2026-10-26', 'not a date'];
|
|
33
|
+
for (const input of invalid) {
|
|
34
|
+
expect(() => normalizeBookingTimestamp(input)).toThrow();
|
|
35
|
+
expect(BookingTimestampRegistrySchema.safeParse(input).success).toBe(false);
|
|
36
|
+
}
|
|
37
|
+
expect(normalizeBookingTimestamp('2028-02-29T14:00:00Z')).toBe('2028-02-29T14:00:00Z');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test('builders normalize automatically and reject ranges collapsed by whole-second precision', () => {
|
|
41
|
+
const content = { type: 'booking' as const, body: 'Booking', booking: {
|
|
42
|
+
startAt: '2026-07-26T14:00:00.100+01:00', endAt: '2026-07-26T14:30:00.900+01:00', location: 'Office',
|
|
43
|
+
} };
|
|
44
|
+
const parsed = defineInteractiveMessage(content);
|
|
45
|
+
expect(parsed.booking).toEqual({ startAt: '2026-07-26T13:00:00Z', endAt: '2026-07-26T13:30:00Z', location: 'Office' });
|
|
46
|
+
expect(content.booking.startAt).toBe('2026-07-26T14:00:00.100+01:00');
|
|
47
|
+
expect(() => InteractiveContentSchema.parse({ ...content, booking: {
|
|
48
|
+
...content.booking, endAt: '2026-07-26T14:00:00.500+01:00',
|
|
49
|
+
} })).toThrow('after');
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
test('input and output JSON Schema retain their distinct patterns and Effect metadata', () => {
|
|
53
|
+
const input = z.toJSONSchema(BookingTimestampRegistrySchema, { io: 'input' });
|
|
54
|
+
const output = z.toJSONSchema(BookingTimestampRegistrySchema, { io: 'output' });
|
|
55
|
+
expect(input).toMatchObject({ type: 'string', format: 'date-time', examples: ['2026-10-26T14:00:00Z', '2026-07-26T14:00:00.000+01:00'] });
|
|
56
|
+
expect(input.description).toContain('Decoding converts');
|
|
57
|
+
expect(output).toMatchObject({ type: 'string', format: 'date-time', title: 'BookingTimestamp', examples: ['2026-10-26T14:00:00Z'] });
|
|
58
|
+
expect(output.description).toContain('whole seconds');
|
|
59
|
+
expect(new RegExp(input.pattern!).test('2026-07-26T14:00:00.123+01:00')).toBe(true);
|
|
60
|
+
expect(new RegExp(output.pattern!).test('2026-07-26T14:00:00.123Z')).toBe(false);
|
|
61
|
+
expect(new RegExp(output.pattern!).test('2026-07-26T14:00:00Z')).toBe(true);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test('the bridge executes nested Effect transformations, refinements and encoders while retaining Struct.shape', () => {
|
|
65
|
+
const count = Schema.String.pipe(Schema.decodeTo(Schema.Number, {
|
|
66
|
+
decode: SchemaGetter.transform(Number), encode: SchemaGetter.transform(String),
|
|
67
|
+
}));
|
|
68
|
+
const effect = Schema.Struct({ count, until: Schema.optional(count) }).check(Schema.makeFilter(value =>
|
|
69
|
+
value.until === undefined || value.until > value.count || 'until must follow count'));
|
|
70
|
+
const projected = projectEffectSchema(effect);
|
|
71
|
+
expect('shape' in projected).toBe(true);
|
|
72
|
+
expect(projected.parse({ count: '2', until: '3' })).toEqual({ count: 2, until: 3 });
|
|
73
|
+
expect(projected.parse({ count: '2' })).toEqual({ count: 2 });
|
|
74
|
+
expect(z.encode(projected, { count: 2, until: 3 })).toEqual({ count: '2', until: '3' });
|
|
75
|
+
expect(projected.safeParse({ count: '2', until: '1' }).success).toBe(false);
|
|
76
|
+
expect(z.safeEncode(projected, { count: 2, until: 1 }).success).toBe(false);
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test('existing call and event projections retain optional fields and validation', () => {
|
|
80
|
+
const call = { id: 'id', sessionId: 'session', generation: 'generation', peer: 'peer', state: 'active', direction: 'incoming',
|
|
81
|
+
video: false, terminal: false, observedAt: 1 };
|
|
82
|
+
const projected = projectEffectSchema(CallSnapshotSchema);
|
|
83
|
+
expect(projected.parse(call)).toEqual(call);
|
|
84
|
+
expect(projected.safeParse({ ...call, direction: 'sideways' }).success).toBe(false);
|
|
85
|
+
expect(EventInputRegistrySchema.parse({ name: 'Meetup', startTime: 100 })).toEqual({ name: 'Meetup', startTime: 100 });
|
|
86
|
+
expect(EventInputRegistrySchema.safeParse({ name: 'Meetup', startTime: 1.5 }).success).toBe(false);
|
|
87
|
+
expect(EventInputRegistrySchema.safeParse({ name: 'Meetup', startTime: 100, endTime: 99 }).success).toBe(false);
|
|
88
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Schema, SchemaGetter } from 'effect';
|
|
2
|
+
|
|
3
|
+
const isoTimestamp = /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/u;
|
|
4
|
+
const utcSeconds = /^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\dZ$/u;
|
|
5
|
+
const calendarDate = Schema.makeFilter<string>((value) => {
|
|
6
|
+
const year = Number(value.slice(0, 4));
|
|
7
|
+
const month = Number(value.slice(5, 7));
|
|
8
|
+
const day = Number(value.slice(8, 10));
|
|
9
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
10
|
+
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
11
|
+
return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1] && Number.isFinite(Date.parse(value))
|
|
12
|
+
|| 'Use a real calendar date and an explicit UTC or numeric timezone';
|
|
13
|
+
}, {
|
|
14
|
+
// Calendar arithmetic has no exact JSON Schema equivalent; retain the other
|
|
15
|
+
// constraints and let the Effect decoder enforce the complete calendar rule.
|
|
16
|
+
toJsonSchema: () => [{}, true],
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const canonicalTimestamp = Schema.String.check(Schema.isPattern(utcSeconds), calendarDate).annotate({
|
|
20
|
+
title: 'BookingTimestamp',
|
|
21
|
+
description: 'Validated native booking timestamp, encoded as UTC ISO 8601 with whole seconds and no fractional seconds.',
|
|
22
|
+
format: 'date-time',
|
|
23
|
+
examples: ['2026-10-26T14:00:00Z'],
|
|
24
|
+
}).pipe(Schema.brand('BookingTimestamp'));
|
|
25
|
+
|
|
26
|
+
/** Effect owns validation, normalization and encoding for native booking dates. */
|
|
27
|
+
export const BookingTimestampSchema = Schema.String.check(Schema.isPattern(isoTimestamp), calendarDate).annotate({
|
|
28
|
+
description: 'ISO 8601 booking timestamp with an explicit timezone. Decoding converts offsets and fractional seconds to UTC whole seconds for WhatsApp.',
|
|
29
|
+
format: 'date-time',
|
|
30
|
+
examples: ['2026-10-26T14:00:00Z', '2026-07-26T14:00:00.000+01:00'],
|
|
31
|
+
}).pipe(Schema.decodeTo(canonicalTimestamp, {
|
|
32
|
+
decode: SchemaGetter.transform((value) => new Date(value).toISOString().replace(/\.\d{3}Z$/, 'Z')),
|
|
33
|
+
encode: SchemaGetter.transform((value) => value),
|
|
34
|
+
}));
|
|
35
|
+
|
|
36
|
+
export type BookingTimestamp = typeof BookingTimestampSchema.Type;
|
|
37
|
+
|
|
38
|
+
/** Validate and normalize an external timestamp before constructing typed booking data. */
|
|
39
|
+
export const normalizeBookingTimestamp = Schema.decodeUnknownSync(BookingTimestampSchema);
|
package/src/calling-media.ts
CHANGED
|
@@ -31,6 +31,8 @@ export interface CallMediaOptions {
|
|
|
31
31
|
speaker?: AudioOutput;
|
|
32
32
|
camera?: VideoInput;
|
|
33
33
|
onMediaFailure?: 'end' | 'keep-open';
|
|
34
|
+
/** Explicitly replace a server-owned source, or return a remote source to the host. */
|
|
35
|
+
takeover?: boolean;
|
|
34
36
|
}
|
|
35
37
|
export interface CallingOptions {
|
|
36
38
|
defaults?: CallMediaOptions;
|
package/src/calling.ts
CHANGED
|
@@ -10,6 +10,7 @@ export const MediaDescriptorSchema = Schema.Struct({
|
|
|
10
10
|
export const CallMediaOptionsSchema = Schema.Struct({
|
|
11
11
|
microphone: Schema.optional(Schema.Unknown), speaker: Schema.optional(Schema.Unknown), camera: Schema.optional(Schema.Unknown),
|
|
12
12
|
onMediaFailure: Schema.optional(Schema.Literals(['end', 'keep-open'])),
|
|
13
|
+
takeover: Schema.optional(Schema.Boolean),
|
|
13
14
|
});
|
|
14
15
|
export const CallIdentitySchema = Schema.Struct({
|
|
15
16
|
id: Schema.String,
|
package/src/common-types.ts
CHANGED
|
@@ -235,7 +235,7 @@ export const ContactSchema = z.object({
|
|
|
235
235
|
msgs: z.array(z.unknown()).nullable().optional(), // Raw nested messages avoid recursive serialization
|
|
236
236
|
profilePicThumbObj: z.object({
|
|
237
237
|
eurl: z.string().optional(),
|
|
238
|
-
id:
|
|
238
|
+
id: ContactIdSchema.optional().describe('Serialized contact ID returned by the profile-picture serializer'),
|
|
239
239
|
img: z.string().optional(),
|
|
240
240
|
imgFull: z.string().optional(),
|
|
241
241
|
tag: z.string().optional(),
|
package/src/effect-projection.ts
CHANGED
|
@@ -1,67 +1,110 @@
|
|
|
1
1
|
import { Schema } from 'effect';
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
|
|
4
|
-
type JsonSchema = { $ref?: string; type?: string; const?: unknown; enum?: unknown[]; anyOf?: JsonSchema[]; oneOf?: JsonSchema[]; properties?: Record<string, JsonSchema>; required?: string[]; items?: JsonSchema; additionalProperties?: boolean | JsonSchema; minimum?: number; maximum?: number; exclusiveMinimum?: number; exclusiveMaximum?: number; minLength?: number; maxLength?: number };
|
|
4
|
+
type JsonSchema = { $ref?: string; type?: string; const?: unknown; enum?: unknown[]; anyOf?: JsonSchema[]; oneOf?: JsonSchema[]; allOf?: JsonSchema[]; properties?: Record<string, JsonSchema>; required?: string[]; items?: JsonSchema; additionalProperties?: boolean | JsonSchema; minimum?: number; maximum?: number; exclusiveMinimum?: number; exclusiveMaximum?: number; minLength?: number; maxLength?: number; pattern?: string; format?: string; title?: string; description?: string; examples?: unknown[] };
|
|
5
|
+
export type SyncEffectSchema = Schema.Top & Schema.ConstraintCodec<unknown, unknown>;
|
|
5
6
|
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
// JSON codec generation maps undefined to null. Project Struct fields from
|
|
9
|
-
// their original schemas so optional properties retain their JS semantics.
|
|
10
|
-
if ('fields' in schema) {
|
|
11
|
-
const fields = schema.fields as Record<string, Schema.Top>;
|
|
12
|
-
const shape = Object.fromEntries(Object.entries(fields).map(([name, field]) => {
|
|
13
|
-
const optional = field.ast.context?.isOptional === true;
|
|
14
|
-
const hasUndefined = field.ast._tag === 'Union' && field.ast.types.some(member => member._tag === 'Undefined');
|
|
15
|
-
const valueSchema = !optional ? field : hasUndefined
|
|
16
|
-
? Schema.required(field as Schema.optional<Schema.Top>)
|
|
17
|
-
: Schema.requiredKey(field as Schema.optionalKey<Schema.Top>);
|
|
18
|
-
const value = projectEffectSchema(valueSchema);
|
|
19
|
-
return [name, optional ? value.optional() : value];
|
|
20
|
-
}));
|
|
21
|
-
return z.object(shape) as z.ZodType<S['Type'], S['Encoded']>;
|
|
22
|
-
}
|
|
23
|
-
const document = Schema.toJsonSchemaDocument(schema);
|
|
7
|
+
/** JSON Schema is presentation metadata; Effect remains the validation/codec authority. */
|
|
8
|
+
function projectDocument(document: ReturnType<typeof Schema.toJsonSchemaDocument>): z.ZodType {
|
|
24
9
|
const project = (node: JsonSchema): z.ZodType => {
|
|
25
|
-
|
|
10
|
+
let value: z.ZodType;
|
|
11
|
+
if (node.allOf) {
|
|
12
|
+
const { allOf, ...base } = node;
|
|
13
|
+
value = project(base);
|
|
14
|
+
for (const clause of allOf) {
|
|
15
|
+
const metadataOnly = Object.keys(clause).every(key => ['title', 'description', 'examples', 'format'].includes(key));
|
|
16
|
+
value = metadataOnly ? value.meta(clause) : z.intersection(value, project({ type: node.type, ...clause }));
|
|
17
|
+
}
|
|
18
|
+
} else if (node.$ref) {
|
|
26
19
|
const key = node.$ref.split('/').at(-1)!;
|
|
27
|
-
|
|
28
|
-
}
|
|
29
|
-
if (
|
|
30
|
-
if (node.
|
|
31
|
-
|
|
32
|
-
if (members) return z.union(members.map(project));
|
|
33
|
-
switch (node.type) {
|
|
20
|
+
value = project(document.definitions[key] as JsonSchema);
|
|
21
|
+
} else if ('const' in node) value = z.literal(node.const as string | number | boolean | null);
|
|
22
|
+
else if (node.enum) value = z.union(node.enum.map(item => z.literal(item as string | number | boolean | null)));
|
|
23
|
+
else if (node.anyOf ?? node.oneOf) value = z.union((node.anyOf ?? node.oneOf)!.map(project));
|
|
24
|
+
else switch (node.type) {
|
|
34
25
|
case 'string': {
|
|
35
|
-
let
|
|
36
|
-
if (node.minLength !== undefined)
|
|
37
|
-
if (node.maxLength !== undefined)
|
|
38
|
-
|
|
26
|
+
let string = z.string();
|
|
27
|
+
if (node.minLength !== undefined) string = string.min(node.minLength);
|
|
28
|
+
if (node.maxLength !== undefined) string = string.max(node.maxLength);
|
|
29
|
+
if (node.pattern !== undefined) string = string.regex(new RegExp(node.pattern));
|
|
30
|
+
value = string;
|
|
31
|
+
break;
|
|
39
32
|
}
|
|
40
33
|
case 'number':
|
|
41
34
|
case 'integer': {
|
|
42
|
-
let
|
|
43
|
-
if (node.minimum !== undefined)
|
|
44
|
-
if (node.maximum !== undefined)
|
|
45
|
-
if (node.exclusiveMinimum !== undefined)
|
|
46
|
-
if (node.exclusiveMaximum !== undefined)
|
|
47
|
-
|
|
35
|
+
let number = node.type === 'integer' ? z.number().int() : z.number();
|
|
36
|
+
if (node.minimum !== undefined) number = number.min(node.minimum);
|
|
37
|
+
if (node.maximum !== undefined) number = number.max(node.maximum);
|
|
38
|
+
if (node.exclusiveMinimum !== undefined) number = number.gt(node.exclusiveMinimum);
|
|
39
|
+
if (node.exclusiveMaximum !== undefined) number = number.lt(node.exclusiveMaximum);
|
|
40
|
+
value = number;
|
|
41
|
+
break;
|
|
48
42
|
}
|
|
49
|
-
case 'boolean':
|
|
50
|
-
case 'null':
|
|
51
|
-
case 'array':
|
|
43
|
+
case 'boolean': value = z.boolean(); break;
|
|
44
|
+
case 'null': value = z.null(); break;
|
|
45
|
+
case 'array': value = z.array(project(node.items ?? {})); break;
|
|
52
46
|
case 'object': {
|
|
53
47
|
const properties = node.properties ?? {};
|
|
54
48
|
const values = typeof node.additionalProperties === 'object' ? project(node.additionalProperties) : node.additionalProperties ? z.unknown() : undefined;
|
|
55
|
-
if (!Object.keys(properties).length && values)
|
|
49
|
+
if (!Object.keys(properties).length && values) { value = z.record(z.string(), values); break; }
|
|
56
50
|
const required = new Set(node.required ?? []);
|
|
57
|
-
const object = z.object(Object.fromEntries(Object.entries(properties).map(([key,
|
|
58
|
-
const
|
|
59
|
-
return [key, required.has(key) ?
|
|
51
|
+
const object = z.object(Object.fromEntries(Object.entries(properties).map(([key, field]) => {
|
|
52
|
+
const property = project(field);
|
|
53
|
+
return [key, required.has(key) ? property : property.optional()];
|
|
60
54
|
})));
|
|
61
|
-
|
|
55
|
+
value = values ? object.catchall(values) : object;
|
|
56
|
+
break;
|
|
62
57
|
}
|
|
63
|
-
default:
|
|
58
|
+
default: value = z.unknown();
|
|
64
59
|
}
|
|
60
|
+
const { title, description, examples, format } = node;
|
|
61
|
+
return value.meta({ ...(title ? { title } : {}), ...(description ? { description } : {}), ...(examples ? { examples } : {}), ...(format ? { format } : {}) });
|
|
65
62
|
};
|
|
66
|
-
return project(document.schema as JsonSchema)
|
|
63
|
+
return project(document.schema as JsonSchema);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Project synchronous Effect contracts into the method/listener/OpenUI registry. */
|
|
67
|
+
export function projectEffectSchema<S extends SyncEffectSchema>(schema: S): z.ZodType<S['Type'], S['Encoded']> {
|
|
68
|
+
const decoded = Schema.toType(schema);
|
|
69
|
+
const encoded = Schema.toEncoded(schema);
|
|
70
|
+
// Keep Struct.shape for the serving registry, while field codecs perform their
|
|
71
|
+
// real transformations and decoded Struct checks remain authoritative.
|
|
72
|
+
if ('fields' in schema) {
|
|
73
|
+
const fields = schema.fields as Record<string, SyncEffectSchema>;
|
|
74
|
+
const shape = Object.fromEntries(Object.entries(fields).map(([name, field]) => {
|
|
75
|
+
const optional = field.ast.context?.isOptional === true;
|
|
76
|
+
const hasUndefined = field.ast._tag === 'Union' && field.ast.types.some(member => member._tag === 'Undefined');
|
|
77
|
+
const valueSchema = !optional ? field : hasUndefined
|
|
78
|
+
? Schema.required(field as Schema.optional<SyncEffectSchema>)
|
|
79
|
+
: Schema.requiredKey(field as Schema.optionalKey<SyncEffectSchema>);
|
|
80
|
+
const value = projectEffectSchema(valueSchema);
|
|
81
|
+
return [name, optional ? value.optional() : value];
|
|
82
|
+
}));
|
|
83
|
+
return z.object(shape).superRefine((value, ctx) => {
|
|
84
|
+
try { Schema.decodeUnknownSync(decoded)(value); }
|
|
85
|
+
catch (error) { ctx.addIssue({ code: 'custom', message: String(error) }); }
|
|
86
|
+
}).meta(Schema.resolveAnnotations(schema) ?? {}) as z.ZodType<S['Type'], S['Encoded']>;
|
|
87
|
+
}
|
|
88
|
+
// Identity schemas need Effect's checks but no transformation wrapper. This
|
|
89
|
+
// retains native Zod kinds and input examples for registry documentation.
|
|
90
|
+
if (encoded.ast === decoded.ast) {
|
|
91
|
+
return projectDocument(Schema.toJsonSchemaDocument(schema)).superRefine((value, ctx) => {
|
|
92
|
+
try { Schema.decodeUnknownSync(schema)(value); }
|
|
93
|
+
catch (error) { ctx.addIssue({ code: 'custom', message: String(error) }); }
|
|
94
|
+
}).meta(Schema.resolveAnnotations(schema) ?? {}) as z.ZodType<S['Type'], S['Encoded']>;
|
|
95
|
+
}
|
|
96
|
+
return z.codec(
|
|
97
|
+
projectDocument(Schema.toJsonSchemaDocument(encoded)),
|
|
98
|
+
projectDocument(Schema.toJsonSchemaDocument(decoded)),
|
|
99
|
+
{
|
|
100
|
+
decode: (value, ctx) => {
|
|
101
|
+
try { return Schema.decodeUnknownSync(schema)(value); }
|
|
102
|
+
catch (error) { ctx.issues.push({ code: 'custom', input: value, message: String(error) }); return z.NEVER; }
|
|
103
|
+
},
|
|
104
|
+
encode: (value, ctx) => {
|
|
105
|
+
try { return Schema.encodeSync(schema)(Schema.decodeUnknownSync(decoded)(value)); }
|
|
106
|
+
catch (error) { ctx.issues.push({ code: 'custom', input: value, message: String(error) }); return z.NEVER; }
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
) as z.ZodType<S['Type'], S['Encoded']>;
|
|
67
110
|
}
|