@temporary-name/server 1.9.3-alpha.5dc8b200530586870ac736830d4584e0333cfd05 → 1.9.3-alpha.62d88f5cf3908d4411b5278f1824b69334da8072

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 (42) hide show
  1. package/dist/adapters/aws-lambda/index.d.mts +5 -6
  2. package/dist/adapters/aws-lambda/index.d.ts +5 -6
  3. package/dist/adapters/aws-lambda/index.mjs +5 -6
  4. package/dist/adapters/fetch/index.d.mts +8 -85
  5. package/dist/adapters/fetch/index.d.ts +8 -85
  6. package/dist/adapters/fetch/index.mjs +17 -157
  7. package/dist/adapters/node/index.d.mts +9 -63
  8. package/dist/adapters/node/index.d.ts +9 -63
  9. package/dist/adapters/node/index.mjs +15 -122
  10. package/dist/{adapters/standard → handler}/index.d.mts +5 -7
  11. package/dist/{adapters/standard → handler}/index.d.ts +5 -7
  12. package/dist/handler/index.mjs +8 -0
  13. package/dist/index.d.mts +355 -208
  14. package/dist/index.d.ts +355 -208
  15. package/dist/index.mjs +421 -207
  16. package/dist/openapi/index.d.mts +18 -53
  17. package/dist/openapi/index.d.ts +18 -53
  18. package/dist/openapi/index.mjs +391 -368
  19. package/dist/shared/server.Blt424vz.mjs +523 -0
  20. package/dist/shared/server.Bmxjwleq.d.ts +39 -0
  21. package/dist/shared/server.BnAF9pfn.mjs +339 -0
  22. package/dist/shared/server.CCWAen7P.mjs +156 -0
  23. package/dist/shared/server.CjPiuQYH.d.mts +51 -0
  24. package/dist/shared/server.CjPiuQYH.d.ts +51 -0
  25. package/dist/shared/server.DLyn62VH.d.mts +39 -0
  26. package/dist/shared/server.DpIhEnBO.d.mts +515 -0
  27. package/dist/shared/server.DpIhEnBO.d.ts +515 -0
  28. package/dist/shared/server.MJ43MXYj.mjs +432 -0
  29. package/package.json +13 -19
  30. package/dist/adapters/standard/index.mjs +0 -9
  31. package/dist/plugins/index.d.mts +0 -84
  32. package/dist/plugins/index.d.ts +0 -84
  33. package/dist/plugins/index.mjs +0 -116
  34. package/dist/shared/server.B-meye9-.d.ts +0 -55
  35. package/dist/shared/server.Ba0Z2fNc.mjs +0 -254
  36. package/dist/shared/server.DkYpsO6W.d.mts +0 -251
  37. package/dist/shared/server.DkYpsO6W.d.ts +0 -251
  38. package/dist/shared/server.DwNnHUZP.d.ts +0 -23
  39. package/dist/shared/server.I-tTl_ce.d.mts +0 -23
  40. package/dist/shared/server.JtIZ8YG7.mjs +0 -237
  41. package/dist/shared/server.miXh-9wo.mjs +0 -416
  42. package/dist/shared/server.vLcMd_kA.d.mts +0 -55
package/dist/index.mjs CHANGED
@@ -1,17 +1,22 @@
1
- import { mergePrefix, mergeTags, ContractProcedure, mergeErrorMap, mergeMeta, parseEndpointDefinition, mergeRoute, prefixRoute, initialSchemas, isContractProcedure, getContractRouter } from '@temporary-name/contract';
2
- export { ValidationError, eventIterator, validateORPCError } from '@temporary-name/contract';
3
- import { assertNever, splitFirst, ORPCError, onError, resolveMaybeOptionalOptions } from '@temporary-name/shared';
4
- export { AsyncIteratorClass, EventPublisher, ORPCError, asyncIteratorToStream as eventIteratorToStream, isDefinedError, onError, onFinish, onStart, onSuccess, safe, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
1
+ import { assertNever, splitFirst, onError, isObject, toArray, guard, resolveMaybeOptionalOptions, isTypescriptObject, isPropertyKey } from '@temporary-name/shared';
2
+ export { AsyncIteratorClass, EventPublisher, asyncIteratorToStream as eventIteratorToStream, onError, onFinish, onStart, onSuccess, streamToAsyncIteratorClass as streamToEventIterator } from '@temporary-name/shared';
3
+ import * as z from '@temporary-name/zod';
5
4
  import { SchemaClass, object, core, gatingContext } from '@temporary-name/zod';
5
+ import { U as UnauthorizedError, P as Procedure, m as mergePrefix, a as mergeTags, b as enhanceRouter, C as Contract, p as parseEndpointDefinition, c as mergeRoute, d as prefixRoute, f as addMiddleware, I as InternalServerError, N as NotFoundError, F as ForbiddenError, B as BadRequestError, l as lazyInternal, h as getLazyMeta, u as unlazy, j as isProcedure } from './shared/server.MJ43MXYj.mjs';
6
+ export { A as APIError, y as BadGatewayError, n as ConflictError, q as ContentTooLargeError, G as GatewayTimeoutError, L as LAZY_SYMBOL, M as MethodNotAllowedError, k as NotAcceptableError, x as NotImplementedError, o as PreconditionFailedError, R as RequestTimeoutError, S as ServiceUnavailableError, T as TooManyRequestsError, w as UnprocessableContentError, v as UnsupportedMediaTypeError, V as ValidationError, K as createAccessibleLazyRouter, e as encodeError, W as endpointRegex, g as getDynamicParams, J as getRouter, i as isAPIErrorStatus, X as isDevelopment, D as isLazy, E as isStartWithMiddlewares, z as lazy, H as mergeMiddlewares, r as resolveContractProcedures, s as standardizeHTTPPath, t as toAPIError, O as traverseContractProcedures, Q as unlazyRouter } from './shared/server.MJ43MXYj.mjs';
6
7
  import { g as getCookie } from './shared/server.C1RJffw4.mjs';
7
- import { P as Procedure, c as createProcedureClient, e as enhanceRouter, a as addMiddleware, s as setHiddenRouterContract, l as lazyInternal, g as getLazyMeta, u as unlazy, i as isProcedure, b as isLazy, d as getRouter } from './shared/server.miXh-9wo.mjs';
8
- export { L as LAZY_SYMBOL, p as createAccessibleLazyRouter, f as createORPCErrorConstructorMap, o as getHiddenRouterContract, k as isStartWithMiddlewares, h as lazy, m as mergeCurrentContext, n as mergeMiddlewares, j as middlewareOutputFn, r as resolveContractProcedures, t as traverseContractProcedures, q as unlazyRouter } from './shared/server.miXh-9wo.mjs';
8
+ import { c as createProcedureClient } from './shared/server.CCWAen7P.mjs';
9
+ export { m as mergeCurrentContext, a as middlewareOutputFn } from './shared/server.CCWAen7P.mjs';
10
+ import { J as JsonSchemaXNativeType } from './shared/server.Blt424vz.mjs';
11
+ export { b as JSON_SCHEMA_INPUT_REGISTRY, c as JSON_SCHEMA_OUTPUT_REGISTRY, a as JSON_SCHEMA_REGISTRY, Z as ZodToJsonSchemaConverter, e as eventIterator, g as getEventIteratorSchemaDetails } from './shared/server.Blt424vz.mjs';
9
12
  export { getEventMeta, withEventMeta } from '@temporary-name/standard-server';
10
13
  import 'cookie';
14
+ import '@temporary-name/server/openapi';
15
+ import 'zod/v4/core';
11
16
 
12
17
  function validateTokenPrefix(prefix, token) {
13
18
  if (prefix && !token.startsWith(prefix)) {
14
- throw new ORPCError("UNAUTHORIZED", { message: `Invalid auth token. It must start with "${prefix}"` });
19
+ throw new UnauthorizedError({ message: `Invalid auth token. It must start with "${prefix}"` });
15
20
  }
16
21
  }
17
22
  function validateTokenAuth(config, token, options) {
@@ -19,47 +24,57 @@ function validateTokenAuth(config, token, options) {
19
24
  validateTokenPrefix(tokenPrefix, token);
20
25
  return validate(token, options);
21
26
  }
22
- function authByQuery(config, options) {
23
- const { name, tokenPrefix, validate } = config;
24
- const query = options.request.url.searchParams;
25
- const token = query.get(name);
26
- if (!token) return void 0;
27
- validateTokenPrefix(tokenPrefix, token);
28
- return validate(token, options);
29
- }
30
- function authByHeader(config, options) {
31
- const authHeader = options.request.headers.get(config.name);
32
- return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
33
- }
34
- function authByCookie(config, options) {
35
- const cookie = getCookie(options.request.headers, config.name);
36
- return cookie ? validateTokenAuth(config, cookie, options) : void 0;
37
- }
38
- function authByBearer(config, options) {
39
- const authHeader = options.request.headers.get("Authorization");
40
- if (!authHeader) return void 0;
41
- const [authType, bearer] = splitFirst(authHeader, " ");
42
- return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
43
- }
44
- function authByBasic(config, options) {
45
- const authHeader = options.request.headers.get("Authorization");
46
- if (!authHeader) return void 0;
47
- const [authType, encoded] = splitFirst(authHeader, " ");
48
- if (authType !== "Basic") return void 0;
49
- const decoded = Buffer.from(encoded, "base64").toString("utf-8");
50
- const [username, password] = splitFirst(decoded, ":");
51
- validateTokenPrefix(config.tokenPrefix, password);
52
- return config.validate(username, password, options);
53
- }
54
- function authByType(config, options) {
55
- const { type } = config;
56
- return type === "header" ? authByHeader(config, options) : type === "query" ? authByQuery(config, options) : type === "cookie" ? authByCookie(config, options) : type === "bearer" ? authByBearer(config, options) : type === "basic" ? authByBasic(config, options) : type === "none" ? false : assertNever(type);
27
+ function runAuth(config, options) {
28
+ switch (config.type) {
29
+ case "header": {
30
+ const authHeader = options.request.headers.get(config.name);
31
+ return authHeader ? validateTokenAuth(config, authHeader, options) : void 0;
32
+ }
33
+ case "query": {
34
+ const { name, tokenPrefix, validate } = config;
35
+ const query = options.request.url.searchParams;
36
+ const token = query.get(name);
37
+ if (!token) return void 0;
38
+ validateTokenPrefix(tokenPrefix, token);
39
+ return validate(token, options);
40
+ }
41
+ case "cookie": {
42
+ const cookie = getCookie(options.request.headers, config.name);
43
+ return cookie ? validateTokenAuth(config, cookie, options) : void 0;
44
+ }
45
+ case "bearer": {
46
+ const authHeader = options.request.headers.get("Authorization");
47
+ if (!authHeader) return void 0;
48
+ const [authType, bearer] = splitFirst(authHeader, " ");
49
+ return authType === "Bearer" ? validateTokenAuth(config, bearer, options) : void 0;
50
+ }
51
+ case "basic": {
52
+ const authHeader = options.request.headers.get("Authorization");
53
+ if (!authHeader) return void 0;
54
+ const [authType, encoded] = splitFirst(authHeader, " ");
55
+ if (authType !== "Basic") return void 0;
56
+ const decoded = Buffer.from(encoded, "base64").toString("utf-8");
57
+ const [username, password] = splitFirst(decoded, ":");
58
+ validateTokenPrefix(config.tokenPrefix, password);
59
+ return config.validate(username, password, options);
60
+ }
61
+ case "none": {
62
+ return false;
63
+ }
64
+ default: {
65
+ assertNever(config);
66
+ }
67
+ }
57
68
  }
58
69
  function authDescription(config) {
59
70
  const { type } = config;
60
71
  return type === "basic" ? "a Basic Authentication header" : type === "bearer" ? "a Bearer Authentication header" : type === "header" ? `a header named "${config.name}"` : type === "query" ? `a query parameter named "${config.name}"` : type === "cookie" ? `a cookie named "${config.name}"` : type === "none" ? "no authentication" : assertNever(type);
61
72
  }
62
73
 
74
+ function mergeMeta(meta1, meta2) {
75
+ return { ...meta1, ...meta2 };
76
+ }
77
+
63
78
  class DecoratedProcedure extends Procedure {
64
79
  /**
65
80
  * Make this procedure callable (works like a function while still being a procedure).
@@ -79,24 +94,19 @@ class DecoratedProcedure extends Procedure {
79
94
  }
80
95
  }
81
96
 
82
- class ProcedureBuilder extends ContractProcedure {
97
+ const initialSchemas = {
98
+ pathSchema: z.strictObject({}),
99
+ querySchema: z.strictObject({}),
100
+ bodySchema: z.strictObject({}),
101
+ outputSchema: z.unknown()
102
+ };
103
+
104
+ class ProcedureBuilder extends Contract {
83
105
  z;
84
106
  constructor(def) {
85
107
  super(def);
86
108
  this.z = new SchemaClass();
87
109
  }
88
- /**
89
- * Adds type-safe custom errors to the contract.
90
- * The provided errors are spared-merged with any existing errors in the contract.
91
- *
92
- * @see {@link https://orpc.unnoq.com/docs/error-handling#type%E2%80%90safe-error-handling Type-Safe Error Handling Docs}
93
- */
94
- errors(errors) {
95
- return new ProcedureBuilder({
96
- ...this["~orpc"],
97
- errorMap: mergeErrorMap(this["~orpc"].errorMap, errors)
98
- });
99
- }
100
110
  /**
101
111
  * Sets or updates the metadata for the contract.
102
112
  * The provided metadata is spared-merged with any existing metadata in the contract.
@@ -172,28 +182,25 @@ class ProcedureBuilder extends ContractProcedure {
172
182
  outputValidationIndex: this["~orpc"].middlewares.length
173
183
  });
174
184
  }
175
- /**
176
- * Uses a middleware to modify the context or improve the pipeline.
177
- *
178
- * @info Supports both normal middleware and inline middleware implementations.
179
- * @note The current context must be satisfy middleware dependent-context
180
- * @see {@link https://orpc.unnoq.com/docs/middleware Middleware Docs}
181
- */
182
185
  use(middleware) {
183
186
  return new this.constructor({
184
187
  ...this["~orpc"],
185
188
  middlewares: addMiddleware(this["~orpc"].middlewares, middleware)
186
189
  });
187
190
  }
188
- // `& {}` is so AuthType will be expanded in parameter info tooltips.
191
+ useErrors(errorMap) {
192
+ return new this.constructor({
193
+ ...this["~orpc"],
194
+ errorMap: { ...this["~orpc"].errorMap, ...errorMap }
195
+ });
196
+ }
189
197
  // The default of false for ValidatedAuthContext is used when you pass in the type 'none'. We use false
190
198
  // because we can't use null or undefined (see ValidatedAuthContext) but we still want it to be falsy.
191
- useAuth(type, ...rest) {
192
- const config = { type, ...rest[0] };
193
- const middleware = os.$context().middleware(async (options) => {
199
+ useAuth(config) {
200
+ const middleware = baseApi.$context().middleware(async (options) => {
194
201
  const { next, context } = options;
195
202
  if (context.auth) return next();
196
- const auth = await authByType(config, options);
203
+ const auth = await runAuth(config, options);
197
204
  if (auth === void 0) {
198
205
  const { authConfigs } = options.procedure["~orpc"];
199
206
  if (context.auth !== false && config === authConfigs.at(-1)) {
@@ -201,7 +208,7 @@ class ProcedureBuilder extends ContractProcedure {
201
208
  if (authConfigs.length > 1) {
202
209
  authDescriptions = `one of: ${authDescriptions}`;
203
210
  }
204
- throw new ORPCError("UNAUTHORIZED", {
211
+ throw new UnauthorizedError({
205
212
  message: `Authentication required. You must provide ${authDescriptions}`
206
213
  });
207
214
  }
@@ -283,31 +290,6 @@ function decorateMiddleware(middleware) {
283
290
  );
284
291
  return mapped;
285
292
  };
286
- decorated.concat = (concatMiddleware, mapInput) => {
287
- const mapped = mapInput ? decorateMiddleware(concatMiddleware).mapInput(mapInput) : concatMiddleware;
288
- const concatted = decorateMiddleware((options, input, output, ...rest) => {
289
- const merged = middleware(
290
- {
291
- ...options,
292
- next: (...[nextOptions1]) => mapped(
293
- {
294
- ...options,
295
- context: { ...options.context, ...nextOptions1?.context },
296
- next: (...[nextOptions2]) => options.next({ context: { ...nextOptions1?.context, ...nextOptions2?.context } })
297
- },
298
- input,
299
- output,
300
- ...rest
301
- )
302
- },
303
- input,
304
- output,
305
- ...rest
306
- );
307
- return merged;
308
- });
309
- return concatted;
310
- };
311
293
  return decorated;
312
294
  }
313
295
 
@@ -329,100 +311,348 @@ class Builder extends BuilderWithMiddlewares {
329
311
  return decorateMiddleware(middleware);
330
312
  }
331
313
  }
332
- function createApiBuilder(opts = {}) {
333
- return new Builder({
334
- route: {},
335
- meta: opts.meta ?? {},
336
- errorMap: {},
337
- inputValidationIndex: 0,
338
- outputValidationIndex: 0,
339
- middlewares: [
340
- onError((error, _options) => {
341
- console.dir(error, { depth: null });
342
- })
343
- ],
344
- schemas: initialSchemas,
345
- // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
346
- // the best solution). For now I've removed the interface to configure it externally.
347
- dedupeLeadingMiddlewares: true,
348
- authConfigs: []
349
- });
350
- }
351
- const os = createApiBuilder();
314
+ const baseApi = new Builder({
315
+ route: {},
316
+ meta: {},
317
+ errorMap: { BadRequestError, UnauthorizedError, ForbiddenError, NotFoundError, InternalServerError },
318
+ inputValidationIndex: 0,
319
+ outputValidationIndex: 0,
320
+ middlewares: [
321
+ onError((error, _options) => {
322
+ console.dir(error, { depth: null });
323
+ })
324
+ ],
325
+ schemas: initialSchemas,
326
+ // NB: this is a relic from orpc -- I'm not convinced there's a need for this (or if there is, that it's
327
+ // the best solution). For now I've removed the interface to configure it externally.
328
+ dedupeLeadingMiddlewares: true,
329
+ authConfigs: []
330
+ });
352
331
 
353
- function implementerInternal(contract, middlewares) {
354
- if (isContractProcedure(contract)) {
355
- const impl2 = new Builder({
356
- ...contract["~orpc"],
357
- middlewares,
358
- authConfigs: [],
359
- inputValidationIndex: middlewares.length,
360
- outputValidationIndex: middlewares.length,
361
- dedupeLeadingMiddlewares: true
362
- });
363
- return impl2;
332
+ const FLEXIBLE_DATE_FORMAT_REGEX = /^[^-]+-[^-]+-[^-]+$/;
333
+ class experimental_JsonSchemaCoercer {
334
+ coerce(schema, value, options = {}) {
335
+ const [, coerced] = this.#coerce(schema, value, options);
336
+ return coerced;
364
337
  }
365
- const impl = new Proxy(contract, {
366
- get: (target, key) => {
367
- if (typeof key !== "string") {
368
- return Reflect.get(target, key);
369
- }
370
- let method;
371
- if (key === "middleware") {
372
- method = (mid) => decorateMiddleware(mid);
373
- } else if (key === "use") {
374
- method = (mid) => {
375
- return implementerInternal(contract, addMiddleware(middlewares, mid));
376
- };
377
- } else if (key === "router") {
378
- method = (router) => {
379
- const adapted = enhanceRouter(router, {
380
- middlewares,
381
- errorMap: {},
382
- prefix: void 0,
383
- tags: void 0,
384
- dedupeLeadingMiddlewares: true
385
- });
386
- return setHiddenRouterContract(adapted, contract);
387
- };
338
+ #coerce(schema, originalValue, options) {
339
+ if (typeof schema === "boolean") {
340
+ return [schema, originalValue];
341
+ }
342
+ if (Array.isArray(schema.type)) {
343
+ return this.#coerce(
344
+ {
345
+ anyOf: schema.type.map((type) => ({ ...schema, type }))
346
+ },
347
+ originalValue,
348
+ options
349
+ );
350
+ }
351
+ let coerced = originalValue;
352
+ let satisfied = true;
353
+ if (typeof schema.$ref === "string") {
354
+ const refSchema = options?.components?.[schema.$ref];
355
+ if (refSchema !== void 0) {
356
+ const [subSatisfied, subCoerced] = this.#coerce(refSchema, coerced, options);
357
+ coerced = subCoerced;
358
+ satisfied = subSatisfied;
388
359
  }
389
- const next = getContractRouter(target, [key]);
390
- if (!next) {
391
- return method ?? next;
360
+ }
361
+ const enumValues = schema.const !== void 0 ? [schema.const] : schema.enum;
362
+ if (enumValues !== void 0 && !enumValues.includes(coerced)) {
363
+ if (typeof coerced === "string") {
364
+ const numberValue = this.#stringToNumber(coerced);
365
+ if (enumValues.includes(numberValue)) {
366
+ coerced = numberValue;
367
+ } else {
368
+ const booleanValue = this.#stringToBoolean(coerced);
369
+ if (enumValues.includes(booleanValue)) {
370
+ coerced = booleanValue;
371
+ } else {
372
+ satisfied = false;
373
+ }
374
+ }
375
+ } else {
376
+ satisfied = false;
392
377
  }
393
- const nextImpl = implementerInternal(next, middlewares);
394
- if (method) {
395
- return new Proxy(method, {
396
- get(_, key2) {
397
- return Reflect.get(nextImpl, key2);
378
+ }
379
+ if (typeof schema.type === "string") {
380
+ switch (schema.type) {
381
+ case "null": {
382
+ if (coerced !== null) {
383
+ satisfied = false;
384
+ }
385
+ break;
386
+ }
387
+ case "string": {
388
+ if (typeof coerced !== "string") {
389
+ satisfied = false;
390
+ }
391
+ break;
392
+ }
393
+ case "number": {
394
+ if (typeof coerced === "string") {
395
+ coerced = this.#stringToNumber(coerced);
396
+ }
397
+ if (typeof coerced !== "number") {
398
+ satisfied = false;
399
+ }
400
+ break;
401
+ }
402
+ case "integer": {
403
+ if (typeof coerced === "string") {
404
+ coerced = this.#stringToInteger(coerced);
405
+ }
406
+ if (typeof coerced !== "number" || !Number.isInteger(coerced)) {
407
+ satisfied = false;
408
+ }
409
+ break;
410
+ }
411
+ case "boolean": {
412
+ if (typeof coerced === "string") {
413
+ coerced = this.#stringToBoolean(coerced);
414
+ }
415
+ if (typeof coerced !== "boolean") {
416
+ satisfied = false;
417
+ }
418
+ break;
419
+ }
420
+ case "array": {
421
+ if (Array.isArray(coerced)) {
422
+ const prefixItemSchemas = "prefixItems" in schema ? toArray(schema.prefixItems) : Array.isArray(schema.items) ? schema.items : [];
423
+ const itemSchema = Array.isArray(schema.items) ? schema.additionalItems : schema.items;
424
+ let shouldUseCoercedItems = false;
425
+ const coercedItems = coerced.map((item, i) => {
426
+ const subSchema = prefixItemSchemas[i] ?? itemSchema;
427
+ if (subSchema === void 0) {
428
+ satisfied = false;
429
+ return item;
430
+ }
431
+ const [subSatisfied, subCoerced] = this.#coerce(subSchema, item, options);
432
+ if (!subSatisfied) {
433
+ satisfied = false;
434
+ }
435
+ if (subCoerced !== item) {
436
+ shouldUseCoercedItems = true;
437
+ }
438
+ return subCoerced;
439
+ });
440
+ if (coercedItems.length < prefixItemSchemas.length) {
441
+ satisfied = false;
442
+ }
443
+ if (shouldUseCoercedItems) {
444
+ coerced = coercedItems;
445
+ }
446
+ } else {
447
+ satisfied = false;
398
448
  }
399
- });
449
+ break;
450
+ }
451
+ case "object": {
452
+ if (Array.isArray(coerced)) {
453
+ coerced = { ...coerced };
454
+ }
455
+ if (isObject(coerced)) {
456
+ let shouldUseCoercedItems = false;
457
+ const coercedItems = {};
458
+ const patternProperties = Object.entries(schema.patternProperties ?? {}).map(
459
+ ([key, value]) => [new RegExp(key), value]
460
+ );
461
+ for (const key in coerced) {
462
+ const value = coerced[key];
463
+ const subSchema = schema.properties?.[key] ?? patternProperties.find(([pattern]) => pattern.test(key))?.[1] ?? schema.additionalProperties;
464
+ if (value === void 0 && !schema.required?.includes(key)) {
465
+ coercedItems[key] = value;
466
+ } else if (subSchema === void 0) {
467
+ coercedItems[key] = value;
468
+ satisfied = false;
469
+ } else {
470
+ const [subSatisfied, subCoerced] = this.#coerce(subSchema, value, options);
471
+ coercedItems[key] = subCoerced;
472
+ if (!subSatisfied) {
473
+ satisfied = false;
474
+ }
475
+ if (subCoerced !== value) {
476
+ shouldUseCoercedItems = true;
477
+ }
478
+ }
479
+ }
480
+ if (schema.required?.some((key) => !Object.hasOwn(coercedItems, key))) {
481
+ satisfied = false;
482
+ }
483
+ if (shouldUseCoercedItems) {
484
+ coerced = coercedItems;
485
+ }
486
+ } else {
487
+ satisfied = false;
488
+ }
489
+ break;
490
+ }
400
491
  }
401
- return nextImpl;
402
492
  }
403
- });
404
- return impl;
405
- }
406
- function implement(contract) {
407
- const implInternal = implementerInternal(contract, []);
408
- const impl = new Proxy(implInternal, {
409
- get: (target, key) => {
410
- let method;
411
- if (key === "$context") {
412
- method = () => impl;
493
+ if ("x-native-type" in schema && typeof schema["x-native-type"] === "string") {
494
+ switch (schema["x-native-type"]) {
495
+ case JsonSchemaXNativeType.Date: {
496
+ if (typeof coerced === "string") {
497
+ coerced = this.#stringToDate(coerced);
498
+ }
499
+ if (!(coerced instanceof Date)) {
500
+ satisfied = false;
501
+ }
502
+ break;
503
+ }
504
+ case JsonSchemaXNativeType.BigInt: {
505
+ switch (typeof coerced) {
506
+ case "string":
507
+ coerced = this.#stringToBigInt(coerced);
508
+ break;
509
+ case "number":
510
+ coerced = this.#numberToBigInt(coerced);
511
+ break;
512
+ }
513
+ if (typeof coerced !== "bigint") {
514
+ satisfied = false;
515
+ }
516
+ break;
517
+ }
518
+ case JsonSchemaXNativeType.RegExp: {
519
+ if (typeof coerced === "string") {
520
+ coerced = this.#stringToRegExp(coerced);
521
+ }
522
+ if (!(coerced instanceof RegExp)) {
523
+ satisfied = false;
524
+ }
525
+ break;
526
+ }
527
+ case JsonSchemaXNativeType.Url: {
528
+ if (typeof coerced === "string") {
529
+ coerced = this.#stringToURL(coerced);
530
+ }
531
+ if (!(coerced instanceof URL)) {
532
+ satisfied = false;
533
+ }
534
+ break;
535
+ }
536
+ case JsonSchemaXNativeType.Set: {
537
+ if (Array.isArray(coerced)) {
538
+ coerced = this.#arrayToSet(coerced);
539
+ }
540
+ if (!(coerced instanceof Set)) {
541
+ satisfied = false;
542
+ }
543
+ break;
544
+ }
545
+ case JsonSchemaXNativeType.Map: {
546
+ if (Array.isArray(coerced)) {
547
+ coerced = this.#arrayToMap(coerced);
548
+ }
549
+ if (!(coerced instanceof Map)) {
550
+ satisfied = false;
551
+ }
552
+ break;
553
+ }
413
554
  }
414
- const next = Reflect.get(target, key);
415
- if (!method || !next || typeof next !== "function" && typeof next !== "object") {
416
- return method || next;
555
+ }
556
+ if (schema.allOf) {
557
+ for (const subSchema of schema.allOf) {
558
+ const [subSatisfied, subCoerced] = this.#coerce(subSchema, coerced, options);
559
+ coerced = subCoerced;
560
+ if (!subSatisfied) {
561
+ satisfied = false;
562
+ }
417
563
  }
418
- return new Proxy(method, {
419
- get(_, key2) {
420
- return Reflect.get(next, key2);
564
+ }
565
+ for (const key of ["anyOf", "oneOf"]) {
566
+ if (schema[key]) {
567
+ let bestOptions;
568
+ for (const subSchema of schema[key]) {
569
+ const [subSatisfied, subCoerced] = this.#coerce(subSchema, coerced, options);
570
+ if (subSatisfied) {
571
+ if (!bestOptions || subCoerced === coerced) {
572
+ bestOptions = { coerced: subCoerced, satisfied: subSatisfied };
573
+ }
574
+ if (subCoerced === coerced) {
575
+ break;
576
+ }
577
+ }
421
578
  }
422
- });
579
+ coerced = bestOptions ? bestOptions.coerced : coerced;
580
+ satisfied = bestOptions ? bestOptions.satisfied : false;
581
+ }
582
+ }
583
+ if (typeof schema.not !== "undefined") {
584
+ const [notSatisfied] = this.#coerce(schema.not, coerced, options);
585
+ if (notSatisfied) {
586
+ satisfied = false;
587
+ }
588
+ }
589
+ return [satisfied, coerced];
590
+ }
591
+ #stringToNumber(value) {
592
+ const num = Number.parseFloat(value);
593
+ if (Number.isNaN(num) || num !== Number(value)) {
594
+ return value;
595
+ }
596
+ return num;
597
+ }
598
+ #stringToInteger(value) {
599
+ const num = Number.parseInt(value);
600
+ if (Number.isNaN(num) || num !== Number(value)) {
601
+ return value;
602
+ }
603
+ return num;
604
+ }
605
+ #stringToBoolean(value) {
606
+ const lower = value.toLowerCase();
607
+ if (lower === "false" || lower === "off") {
608
+ return false;
609
+ }
610
+ if (lower === "true" || lower === "on") {
611
+ return true;
612
+ }
613
+ return value;
614
+ }
615
+ #stringToBigInt(value) {
616
+ return guard(() => BigInt(value)) ?? value;
617
+ }
618
+ #numberToBigInt(value) {
619
+ return guard(() => BigInt(value)) ?? value;
620
+ }
621
+ #stringToDate(value) {
622
+ const date = new Date(value);
623
+ if (Number.isNaN(date.getTime()) || !FLEXIBLE_DATE_FORMAT_REGEX.test(value)) {
624
+ return value;
625
+ }
626
+ return date;
627
+ }
628
+ #stringToRegExp(value) {
629
+ const match = value.match(/^\/(.*)\/([a-z]*)$/);
630
+ if (match) {
631
+ const [, pattern, flags] = match;
632
+ return guard(() => new RegExp(pattern, flags)) ?? value;
633
+ }
634
+ return value;
635
+ }
636
+ #stringToURL(value) {
637
+ return guard(() => new URL(value)) ?? value;
638
+ }
639
+ #arrayToSet(value) {
640
+ const set = new Set(value);
641
+ if (set.size !== value.length) {
642
+ return value;
423
643
  }
424
- });
425
- return impl;
644
+ return set;
645
+ }
646
+ #arrayToMap(value) {
647
+ if (value.some((item) => !Array.isArray(item) || item.length !== 2)) {
648
+ return value;
649
+ }
650
+ const result = new Map(value);
651
+ if (result.size !== value.length) {
652
+ return value;
653
+ }
654
+ return result;
655
+ }
426
656
  }
427
657
 
428
658
  function createAssertedLazyProcedure(lazied) {
@@ -439,42 +669,26 @@ function createAssertedLazyProcedure(lazied) {
439
669
  }, getLazyMeta(lazied));
440
670
  return lazyProcedure;
441
671
  }
442
- function createContractedProcedure(procedure, contract) {
443
- return new Procedure({
444
- ...procedure["~orpc"],
445
- errorMap: contract["~orpc"].errorMap,
446
- route: contract["~orpc"].route,
447
- meta: contract["~orpc"].meta
448
- });
449
- }
450
672
  function call(procedure, input, ...rest) {
451
673
  const options = resolveMaybeOptionalOptions(rest);
452
674
  return createProcedureClient(procedure, options)(input, options);
453
675
  }
454
676
 
455
- function createRouterClient(router, ...rest) {
456
- const options = resolveMaybeOptionalOptions(rest);
457
- if (isProcedure(router)) {
458
- const caller = createProcedureClient(router, options);
459
- return caller;
460
- }
461
- const procedureCaller = isLazy(router) ? createProcedureClient(createAssertedLazyProcedure(router), options) : {};
462
- const recursive = new Proxy(procedureCaller, {
463
- get(target, key) {
464
- if (typeof key !== "string") {
465
- return Reflect.get(target, key);
466
- }
467
- const next = getRouter(router, [key]);
468
- if (!next) {
469
- return Reflect.get(target, key);
470
- }
471
- return createRouterClient(next, {
472
- ...rest[0],
473
- path: [...rest[0]?.path ?? [], key]
474
- });
677
+ function isSchemaIssue(issue) {
678
+ if (!isTypescriptObject(issue) || typeof issue.message !== "string") {
679
+ return false;
680
+ }
681
+ if (issue.path !== void 0) {
682
+ if (!Array.isArray(issue.path)) {
683
+ return false;
684
+ }
685
+ if (!issue.path.every(
686
+ (segment) => isPropertyKey(segment) || isTypescriptObject(segment) && isPropertyKey(segment.key)
687
+ )) {
688
+ return false;
475
689
  }
476
- });
477
- return recursive;
690
+ }
691
+ return true;
478
692
  }
479
693
 
480
- export { Builder, BuilderWithMiddlewares, DecoratedProcedure, Procedure, ProcedureBuilder, addMiddleware, call, createApiBuilder, createAssertedLazyProcedure, createContractedProcedure, createProcedureClient, createRouterClient, decorateMiddleware, enhanceRouter, getLazyMeta, getRouter, implement, implementerInternal, isLazy, isProcedure, lazyInternal, os, setHiddenRouterContract, unlazy };
694
+ export { BadRequestError, Builder, BuilderWithMiddlewares, Contract, DecoratedProcedure, ForbiddenError, InternalServerError, JsonSchemaXNativeType, NotFoundError, Procedure, ProcedureBuilder, UnauthorizedError, addMiddleware, baseApi, call, createAssertedLazyProcedure, createProcedureClient, decorateMiddleware, enhanceRouter, experimental_JsonSchemaCoercer, getLazyMeta, initialSchemas, isProcedure, isSchemaIssue, lazyInternal, mergeMeta, parseEndpointDefinition, unlazy };