@temporary-name/server 1.9.3-alpha.f9f5ce625d5edee78250b87b3a64f1d9760c2244 → 1.9.3-alpha.fb7e3a67f82deaeffad5063e136b2f3c03c4b5b3

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