trpc-msw 4.12.0 → 4.14.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.
Files changed (36) hide show
  1. package/dist/createTRPCMsw.d.ts +1 -1
  2. package/dist/createTRPCMsw.js +4 -3
  3. package/dist/models/MswWebSocketAdapter.d.ts +1 -1
  4. package/dist/models/MswWebSocketAdapter.js +1 -1
  5. package/dist/models/ProcedureResolver.d.ts +1 -1
  6. package/dist/models/SubscriptionRegistration.d.ts +1 -1
  7. package/dist/models/TRPCMswOptions.d.ts +9 -2
  8. package/dist/vendor/pnpm/tagged-tag@1.0.0/vendor/tagged-tag/index.d.ts +2 -0
  9. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/apply-default-options.d.ts +61 -0
  10. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/collapse-literals.d.ts +38 -0
  11. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/except.d.ts +105 -0
  12. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/if.d.ts +94 -0
  13. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/internal/object.d.ts +41 -0
  14. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/internal/string.d.ts +8 -0
  15. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/internal/type.d.ts +60 -0
  16. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/is-any.d.ts +31 -0
  17. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/is-never.d.ts +54 -0
  18. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/keys-of-union.d.ts +44 -0
  19. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/matching-key.d.ts +38 -0
  20. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/merge.d.ts +11 -0
  21. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/numeric.d.ts +24 -0
  22. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/omit-index-signature.d.ts +92 -0
  23. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/pick-index-signature.d.ts +46 -0
  24. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/primitive.d.ts +6 -0
  25. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/require-none.d.ts +43 -0
  26. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/required-keys-of.d.ts +37 -0
  27. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/string-to-number.d.ts +57 -0
  28. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/tagged.d.ts +95 -0
  29. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/union-member.d.ts +58 -0
  30. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/unknown-array.d.ts +25 -0
  31. package/dist/vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/unwrap-branded-primitive.d.ts +63 -0
  32. package/package.json +11 -10
  33. /package/dist/vendor/pnpm/{type-fest@6.0.0 → type-fest@6.0.3}/vendor/type-fest/source/promisable.d.ts +0 -0
  34. /package/dist/{packages → work/Esposter/Esposter/packages}/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.d.ts +0 -0
  35. /package/dist/{packages → work/Esposter/Esposter/packages}/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js +0 -0
  36. /package/dist/{packages → work/Esposter/Esposter/packages}/trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js +0 -0
@@ -1,4 +1,4 @@
1
1
  import { TRPCMsw } from "./models/TRPCMsw.js";
2
2
  import { TRPCMswOptions } from "./models/TRPCMswOptions.js";
3
3
  import { AnyTRPCRouter } from "@trpc/server";
4
- export declare const createTRPCMsw: <TRouter extends AnyTRPCRouter, TContext extends object = object>({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure, router, t, webSocketUrl }: TRPCMswOptions<TContext>) => TRPCMsw<TRouter, TContext>;
4
+ export declare const createTRPCMsw: <TRouter extends AnyTRPCRouter, TContext extends object = object>({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure, responseMeta, router, t, webSocketUrl }: TRPCMswOptions<TContext>) => TRPCMsw<TRouter, TContext>;
@@ -4,7 +4,6 @@ import { UnhandledProcedureAction } from "./models/UnhandledProcedureAction.js";
4
4
  import { checkIsProcedureType } from "./services/checkIsProcedureType.js";
5
5
  import { createMockRouter } from "./services/createMockRouter.js";
6
6
  import { getProcedurePaths } from "./services/getProcedurePaths.js";
7
- import { WebSocketServerAdapter } from "./packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js";
8
7
  import { omitUndefined } from "@esposter/shared";
9
8
  import { createTRPCRecursiveProxy } from "@trpc/server";
10
9
  import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
@@ -12,8 +11,9 @@ import { applyWSSHandler } from "@trpc/server/adapters/ws";
12
11
  import { http, ws } from "msw";
13
12
  import { IncomingMessage } from "node:http";
14
13
  import { Socket } from "node:net";
14
+ import { WebSocketServerAdapter } from "./work/Esposter/Esposter/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketServerAdapter.js";
15
15
  // src/createTRPCMsw.ts
16
- const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = UnhandledProcedureAction.Error, router, t, webSocketUrl }) => {
16
+ const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandledProcedure = UnhandledProcedureAction.Error, responseMeta, router, t, webSocketUrl }) => {
17
17
  const registrations = /* @__PURE__ */ new Map();
18
18
  const procedureTypes = /* @__PURE__ */ new Map();
19
19
  const endpointPathname = new URL(endpoint, "http://localhost").pathname;
@@ -24,7 +24,8 @@ const createTRPCMsw = ({ allowMethodOverride, createContext, endpoint, onUnhandl
24
24
  return fetchRequestHandler({
25
25
  ...omitUndefined({
26
26
  allowMethodOverride,
27
- createContext
27
+ createContext,
28
+ responseMeta
28
29
  }),
29
30
  endpoint: endpointPathname,
30
31
  req: request,
@@ -1,5 +1,5 @@
1
- import { WebSocketClientAdapter } from "../packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
2
1
  import { WebSocketHandlerConnection } from "msw";
2
+ import { WebSocketClientAdapter } from "../work/Esposter/Esposter/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
3
3
  type MswWebSocketClient = WebSocketHandlerConnection["client"];
4
4
  export declare class MswWebSocketAdapter extends WebSocketClientAdapter {
5
5
  constructor(client: MswWebSocketClient);
@@ -1,5 +1,5 @@
1
1
  import { toBuffer } from "../services/toBuffer.js";
2
- import { WebSocketClientAdapter } from "../packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
2
+ import { WebSocketClientAdapter } from "../work/Esposter/Esposter/packages/trpc-nuxt-module/dist/runtime/server/models/WebSocketClientAdapter.js";
3
3
  // src/models/MswWebSocketAdapter.ts
4
4
  var MswWebSocketAdapter = class extends WebSocketClientAdapter {
5
5
  constructor(client) {
@@ -1,4 +1,4 @@
1
1
  import { ProcedureResolverOptions } from "./ProcedureResolverOptions.js";
2
- import { Promisable } from "../vendor/pnpm/type-fest@6.0.0/vendor/type-fest/source/promisable.js";
3
2
  import { AnyTRPCProcedure, inferProcedureInput, inferProcedureOutput } from "@trpc/server";
3
+ import { Promisable } from "../vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/promisable.js";
4
4
  export type ProcedureResolver<TContext, TProcedure extends AnyTRPCProcedure> = (options: ProcedureResolverOptions<TContext, inferProcedureInput<TProcedure>>) => Promisable<inferProcedureOutput<TProcedure>>;
@@ -1,5 +1,5 @@
1
1
  import { ProcedureResolverOptions } from "./ProcedureResolverOptions.js";
2
- import { Promisable } from "../vendor/pnpm/type-fest@6.0.0/vendor/type-fest/source/promisable.js";
2
+ import { Promisable } from "../vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/promisable.js";
3
3
  export interface SubscriptionRegistration {
4
4
  resolver: (options: ProcedureResolverOptions<unknown, unknown>) => Promisable<AsyncIterable<unknown>>;
5
5
  type: "subscription";
@@ -1,14 +1,21 @@
1
1
  import { CreateContextOptions } from "./CreateContextOptions.js";
2
2
  import { TRPCMswRoot } from "./TRPCMswRoot.js";
3
3
  import { UnhandledProcedureAction } from "./UnhandledProcedureAction.js";
4
- import { Promisable } from "../vendor/pnpm/type-fest@6.0.0/vendor/type-fest/source/promisable.js";
5
4
  import { AnyTRPCRouter } from "@trpc/server";
5
+ import { FetchHandlerRequestOptions } from "@trpc/server/adapters/fetch";
6
+ import { Except } from "../vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/except.js";
7
+ import { Promisable } from "../vendor/pnpm/type-fest@6.0.3/vendor/type-fest/source/promisable.js";
6
8
  export interface TRPCMswOptions<TContext extends object> {
7
9
  allowMethodOverride?: boolean;
8
10
  createContext?: (options: CreateContextOptions) => Promisable<TContext>;
9
11
  endpoint: string;
10
12
  onUnhandledProcedure?: UnhandledProcedureAction;
13
+ responseMeta?: (options: Except<Parameters<ResponseMetaFn>[0], "ctx"> & {
14
+ ctx?: TContext;
15
+ }) => ReturnType<ResponseMetaFn>;
11
16
  router?: AnyTRPCRouter;
12
17
  t: TRPCMswRoot<TContext>;
13
18
  webSocketUrl?: string;
14
- }
19
+ }
20
+ type ResponseMetaFn = NonNullable<FetchHandlerRequestOptions<AnyTRPCRouter>["responseMeta"]>;
21
+ export {};
@@ -0,0 +1,2 @@
1
+ declare const tag: unique symbol;
2
+ export { tag as default };
@@ -0,0 +1,61 @@
1
+ import { SimplifyObject } from "./internal/object.js";
2
+ import { RequiredKeysOf } from "./required-keys-of.js";
3
+ import { _Merge } from "./merge.js";
4
+ import { IsAny } from "./is-any.js";
5
+ import { If } from "./if.js";
6
+ import { IsNever } from "./is-never.js";
7
+ import { MatchingKey } from "./matching-key.js";
8
+ /**
9
+ Apply default options to specified options, preserving literal types.
10
+
11
+ Useful for authors of configurable utility types. `Defaults` must give every optional option a default and must not give a default for a required option. Each default must be assignable to its option type. `SpecifiedOptions` must satisfy `Options`, including its required properties. Use {@link DefaultsFor} to define a defaults object.
12
+
13
+ The resolution is shallow, so a nested object is replaced as a whole. A specified option overrides its default. An optional or `undefined`-including specified option uses the default when the declared type does not admit `undefined`, and still overrides when the declared type admits `undefined`, such as `unknown` or `string | undefined`. A numeric key can use either spelling, so `0` and `'0'` name the same option. Every option declared in `Options` is required, and its `readonly` modifier comes from the chosen default or override.
14
+
15
+ @example
16
+ ```
17
+ import type {ApplyDefaultOptions} from 'type-fest';
18
+
19
+ type FormatOptions = {
20
+ uppercase?: boolean;
21
+ prefix?: string;
22
+ };
23
+
24
+ type DefaultFormatOptions = {
25
+ uppercase: false;
26
+ prefix: '';
27
+ };
28
+
29
+ type Format<Value extends string, Options extends FormatOptions = {}> = FormatWithOptions<Value, ApplyDefaultOptions<FormatOptions, DefaultFormatOptions, Options>>;
30
+
31
+ type FormatWithOptions<Value extends string, Options extends Required<FormatOptions>> = `${Options['prefix']}${Options['uppercase'] extends true ? Uppercase<Value> : Value}`;
32
+
33
+ type Plain = Format<'hello'>;
34
+ //=> 'hello'
35
+
36
+ type Heading = Format<'hello', {uppercase: true; prefix: '# '}>;
37
+ //=> '# HELLO'
38
+
39
+ type Resolved = ApplyDefaultOptions<FormatOptions, DefaultFormatOptions, {uppercase?: true}>;
40
+ //=> {uppercase: false; prefix: ''}
41
+ ```
42
+
43
+ Known limitations:
44
+ - Intended for an object with named properties. Arrays, tuples, and functions are not supported. A string index signature on `Options` blocks defaults for its named options.
45
+ - A union of option types or a union-valued option uses one resolution, usually the defaults. A `never` option value is not supported.
46
+ - Extra properties are allowed: an extra specified property is kept unless it can be `undefined`, and extra `Defaults` keys are kept.
47
+ - With `any` or `never` as `SpecifiedOptions`, the defaults are used, or `never` if `Options` has a required property.
48
+ - This does not model runtime object spread, so TypeScript may require concrete specified options instead of unresolved generics.
49
+
50
+ @see {@link DefaultsFor}
51
+ @category Object
52
+ */
53
+ export type ApplyDefaultOptions<Options extends object, Defaults extends SimplifyObject<Omit<Required<Options>, RequiredKeysOf<Options>> & Partial<Record<RequiredKeysOf<Options>, never>>>, SpecifiedOptions extends Options> =
54
+ // Keep the resolved type assignable to `Required<Options>` without inferring a result that can widen a specified generic value to its constraint.
55
+ _ApplyDefaultOptions<Options, Defaults, SpecifiedOptions> extends Required<Options> ? _ApplyDefaultOptions<Options, Defaults, SpecifiedOptions> : never;
56
+ type _ApplyDefaultOptions<Options extends object, Defaults, SpecifiedOptions> = If<IsAny<SpecifiedOptions>, Defaults, If<IsNever<SpecifiedOptions>, Defaults,
57
+ // The overrides are already an object map, so skip `Merge`'s array and equality dispatch.
58
+ _Merge<Defaults, { [
59
+ // The first `as` branch keeps the key of an option whose declared type admits `undefined`, like `unknown`, because `undefined` is one of its valid values. `-?` then strips the optional modifier, so an unnarrowed options type still resolves instead of failing the `Required<Options>` guard above.
60
+ Key in keyof SpecifiedOptions as undefined extends Required<Options>[MatchingKey<Options, Key>] ? Key : undefined extends SpecifiedOptions[Key] ? never : Key]-?: SpecifiedOptions[Key]; }>>>;
61
+ export {};
@@ -0,0 +1,38 @@
1
+ import { Primitive } from "./primitive.js";
2
+ /**
3
+ Collapse literal union members into broader types already present in the union.
4
+
5
+ Use-case: Normalize a {@link LiteralUnion} for type comparisons or conditional types while preserving unrelated union members. Complements {@link ExtractLiterals}, which keeps only the literals.
6
+
7
+ Unlike {@link LiteralToPrimitive}, this does not widen every literal: a literal changes only when a broader member of the union already covers it. Members that are not primitives are returned unchanged. It only removes the intersection with the empty object type (`& {}`) from primitive members, which lets TypeScript merge the union. This includes the `& Record<never, never>` of {@link LiteralUnion}, because `Record<never, never>` is `{}`. This is not recursive, and it does not merge the members of a branded or tagged type, because each member keeps its own brand or tag.
8
+
9
+ @example
10
+ ```
11
+ import type {CollapseLiterals, LiteralUnion} from 'type-fest';
12
+
13
+ type Theme = LiteralUnion<'auto' | 'dark', string>;
14
+
15
+ type ThemeValue = CollapseLiterals<Theme>;
16
+ //=> string
17
+
18
+ type OptionalTheme = CollapseLiterals<Theme | null | undefined>;
19
+ //=> string | null | undefined
20
+
21
+ type EventName = CollapseLiterals<LiteralUnion<'click' | 'onChange', `on${string}`>>;
22
+ //=> 'click' | `on${string}`
23
+
24
+ type Size = CollapseLiterals<LiteralUnion<1 | 2 | 3, number>>;
25
+ //=> number
26
+
27
+ type KnownTheme = CollapseLiterals<'auto' | 'dark'>;
28
+ //=> 'auto' | 'dark'
29
+ ```
30
+
31
+ @see {@link LiteralUnion}
32
+ @see {@link ExtractLiterals}
33
+ @see {@link LiteralToPrimitive}
34
+ @category Type
35
+ */
36
+ // Distribute first, so an object member in the union cannot stop the other members from collapsing.
37
+ // The primitive check also keeps `{}`-like inputs away from the `infer`, which turns them into `unknown`.
38
+ export type CollapseLiterals<Union> = Union extends Primitive ? Union extends (infer Collapsed) & {} ? Collapsed : Union : Union;
@@ -0,0 +1,105 @@
1
+ import { KeysOfUnion } from "./keys-of-union.js";
2
+ import { ApplyDefaultOptions } from "./apply-default-options.js";
3
+ import { RequireNone } from "./require-none.js";
4
+ /**
5
+ Filter out keys from an object.
6
+
7
+ Returns `never` if `Exclude` is strictly equal to `Key`.
8
+ Returns `never` if `Key` extends `Exclude`.
9
+ Returns `Key` otherwise.
10
+
11
+ @example
12
+ ```
13
+ type Filtered = Filter<'foo', 'foo'>;
14
+ //=> never
15
+ ```
16
+
17
+ @example
18
+ ```
19
+ type Filtered = Filter<'bar', string>;
20
+ //=> never
21
+ ```
22
+
23
+ @example
24
+ ```
25
+ type Filtered = Filter<'bar', 'foo'>;
26
+ //=> 'bar'
27
+ ```
28
+
29
+ @see {Except}
30
+ */
31
+ type Filter<KeyType, ExcludeType> = Exclude<KeyType, ExcludeType>;
32
+ export type ExceptOptions = {
33
+ /**
34
+ Disallow assigning non-specified properties.
35
+
36
+ Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.
37
+
38
+ @default false
39
+ */
40
+ requireExactProps?: boolean;
41
+ };
42
+ type DefaultExceptOptions = {
43
+ requireExactProps: false;
44
+ };
45
+ /**
46
+ Create a type from an object type without certain keys.
47
+
48
+ We recommend setting the `requireExactProps` option to `true`.
49
+
50
+ This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
51
+
52
+ This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
53
+
54
+ Note: For a generic conditional type, TypeScript only accepts the keys that all its branches share, because it does not know which branch applies. To remove a key that only some branches have, intersect it with `KeysOfUnion`, as in `Except<Conditional<T>, 'key' & KeysOfUnion<Conditional<T>>>`. When the resolved type does not have the key, nothing is removed.
55
+
56
+ @example
57
+ ```
58
+ import type {Except} from 'type-fest';
59
+
60
+ type Foo = {
61
+ a: number;
62
+ b: string;
63
+ };
64
+
65
+ type FooWithoutA = Except<Foo, 'a'>;
66
+ //=> {b: string}
67
+
68
+ // @ts-expect-error
69
+ const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
70
+ // errors: 'a' does not exist in type '{ b: string; }'
71
+
72
+ type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>;
73
+ //=> {a: number} & {b?: never}
74
+
75
+ // @ts-expect-error
76
+ const fooWithoutB: FooWithoutB = {a: 1, b: '2'};
77
+ // errors at 'b': Type 'string' is not assignable to type 'undefined'.
78
+
79
+ // The `Omit` utility type doesn't work when omitting specific keys from objects containing index signatures.
80
+
81
+ // Consider the following example:
82
+
83
+ type UserData = {
84
+ [metadata: string]: string;
85
+ email: string;
86
+ name: string;
87
+ role: 'admin' | 'user';
88
+ };
89
+
90
+ // `Omit` clearly doesn't behave as expected in this case:
91
+ type PostPayload = Omit<UserData, 'email'>;
92
+ //=> {[x: string]: string; [x: number]: string}
93
+
94
+ // In situations like this, `Except` works better.
95
+ // It simply removes the `email` key while preserving all the other keys.
96
+ type PostPayloadFixed = Except<UserData, 'email'>;
97
+ //=> {[x: string]: string; name: string; role: 'admin' | 'user'}
98
+ ```
99
+
100
+ @category Object
101
+ */
102
+ export type Except<ObjectType, KeysType extends KeysOfUnion<ObjectType>, Options extends ExceptOptions = {}> = _Except<ObjectType, KeysType, ApplyDefaultOptions<ExceptOptions, DefaultExceptOptions, Options>>;
103
+ // The mapped type is homomorphic, so it distributes over a union `ObjectType` by itself, and a generic `ObjectType` stays assignable to it. Only `requireExactProps` needs an explicit distribution, so that each member gets its own keys.
104
+ type _Except<ObjectType, KeysType, Options extends Required<ExceptOptions>> = Options['requireExactProps'] extends true ? ObjectType extends unknown ? { [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType]; } & RequireNone<KeysType & keyof ObjectType> : never : { [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType]; };
105
+ export {};
@@ -0,0 +1,94 @@
1
+ import { IsNever } from "./is-never.js";
2
+ /**
3
+ An if-else-like type that resolves depending on whether the given `boolean` type is `true` or `false`.
4
+
5
+ Use-cases:
6
+ - You can use this in combination with `Is*` types to create an if-else-like experience. For example, `If<IsAny<any>, 'is any', 'not any'>`.
7
+
8
+ Note:
9
+ - Returns a union of if branch and else branch if the given type is `boolean` or `any`. For example, `If<boolean, 'Y', 'N'>` will return `'Y' | 'N'`.
10
+ - Returns the else branch if the given type is `never`. For example, `If<never, 'Y', 'N'>` will return `'N'`.
11
+
12
+ @example
13
+ ```
14
+ import type {If} from 'type-fest';
15
+
16
+ type A = If<true, 'yes', 'no'>;
17
+ //=> 'yes'
18
+
19
+ type B = If<false, 'yes', 'no'>;
20
+ //=> 'no'
21
+
22
+ type C = If<boolean, 'yes', 'no'>;
23
+ //=> 'yes' | 'no'
24
+
25
+ type D = If<any, 'yes', 'no'>;
26
+ //=> 'yes' | 'no'
27
+
28
+ type E = If<never, 'yes', 'no'>;
29
+ //=> 'no'
30
+ ```
31
+
32
+ @example
33
+ ```
34
+ import type {If, IsAny, IsNever} from 'type-fest';
35
+
36
+ type A = If<IsAny<unknown>, 'is any', 'not any'>;
37
+ //=> 'not any'
38
+
39
+ type B = If<IsNever<never>, 'is never', 'not never'>;
40
+ //=> 'is never'
41
+ ```
42
+
43
+ @example
44
+ ```
45
+ import type {If, IsEqual} from 'type-fest';
46
+
47
+ type IfEqual<T, U, IfBranch, ElseBranch> = If<IsEqual<T, U>, IfBranch, ElseBranch>;
48
+
49
+ type A = IfEqual<string, string, 'equal', 'not equal'>;
50
+ //=> 'equal'
51
+
52
+ type B = IfEqual<string, number, 'equal', 'not equal'>;
53
+ //=> 'not equal'
54
+ ```
55
+
56
+ Note: Sometimes using the `If` type can make an implementation non–tail-recursive, which can impact performance. In such cases, it’s better to use a conditional directly. Refer to the following example:
57
+
58
+ @example
59
+ ```
60
+ import type {If, IsEqual, StringRepeat} from 'type-fest';
61
+
62
+ type HundredZeroes = StringRepeat<'0', 100>;
63
+
64
+ // The following implementation is not tail recursive
65
+ type Includes<S extends string, Char extends string> =
66
+ S extends `${infer First}${infer Rest}`
67
+ ? If<IsEqual<First, Char>,
68
+ 'found',
69
+ Includes<Rest, Char>>
70
+ : 'not found';
71
+
72
+ // Hence, instantiations with long strings will fail
73
+ // @ts-expect-error
74
+ type Fails = Includes<HundredZeroes, '1'>;
75
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
76
+ // Error: Type instantiation is excessively deep and possibly infinite.
77
+
78
+ // However, if we use a simple conditional instead of `If`, the implementation becomes tail-recursive
79
+ type IncludesWithoutIf<S extends string, Char extends string> =
80
+ S extends `${infer First}${infer Rest}`
81
+ ? IsEqual<First, Char> extends true
82
+ ? 'found'
83
+ : IncludesWithoutIf<Rest, Char>
84
+ : 'not found';
85
+
86
+ // Now, instantiations with long strings will work
87
+ type Works = IncludesWithoutIf<HundredZeroes, '1'>;
88
+ //=> 'not found'
89
+ ```
90
+
91
+ @category Type Guard
92
+ @category Utilities
93
+ */
94
+ export type If<Type extends boolean, IfBranch, ElseBranch> = IsNever<Type> extends true ? ElseBranch : Type extends true ? IfBranch : ElseBranch;
@@ -0,0 +1,41 @@
1
+ import { StringToNumber } from "../string-to-number.js";
2
+ import { KeyToString } from "./string.js";
3
+ /**
4
+ Flatten an object type. This is the plain definition `Simplify` had before it started returning a function, a class constructor, or a branded primitive as is.
5
+
6
+ Internal types use this instead of `Simplify`, because they only flatten object types they built themselves, where any call signature is already dropped or handled separately and no branded primitive can appear, so they do not need that check. Use `Simplify` if the input can be a function, a class constructor, or a branded primitive. Keeping the check out of them avoids its cost in every type that flattens its result, and avoids the risk of "excessively deep" errors in user code, which a conditional in `Simplify` once caused for types like `SetRequired`. See https://github.com/sindresorhus/type-fest/issues/436.
7
+ */
8
+ export type SimplifyObject<Type> = { [KeyType in keyof Type]: Type[KeyType]; } & {};
9
+ /**
10
+ Normalize keys by including string and number representations wherever applicable.
11
+
12
+ @example
13
+ ```ts
14
+ type A = NormalizedKeys<0 | '1'>;
15
+ //=> 0 | '0' | 1 | '1'
16
+
17
+ type B = NormalizedKeys<string>;
18
+ //=> string | number
19
+
20
+ type C = NormalizedKeys<number>;
21
+ //=> number | `${number}`
22
+
23
+ type D = NormalizedKeys<symbol | 'foo'>;
24
+ //=> symbol | 'foo'
25
+ ```
26
+ */
27
+ export type NormalizedKeys<Keys extends PropertyKey> = Keys | (string extends Keys ? number : never) | StringToNumber<Keys & string> | KeyToString<Keys & number>;
28
+ /**
29
+ Get the given keys with their numeric and string aliases, including the runtime string spelling of enum keys.
30
+
31
+ @example
32
+ ```ts
33
+ enum Color {
34
+ Red = 'red',
35
+ }
36
+
37
+ type A = KeyAliases<0 | Color.Red>;
38
+ //=> 0 | '0' | Color.Red | 'red'
39
+ ```
40
+ */
41
+ export type KeyAliases<Keys extends PropertyKey> = NormalizedKeys<Keys | KeyToString<Keys>>;
@@ -0,0 +1,8 @@
1
+ /**
2
+ Convert a string or number key to its template literal representation.
3
+
4
+ Note: This type is not the return type of the `.toString()` function.
5
+
6
+ Keep this separate from the public `ToString`: internal key and path matching relies on preserving branded template literal patterns and `${any}`.
7
+ */
8
+ export type KeyToString<Key> = Key extends string | number ? `${Key}` : never;
@@ -0,0 +1,60 @@
1
+ import { IsAny } from "../is-any.js";
2
+ import { IsNever } from "../is-never.js";
3
+ import { UnknownArray } from "../unknown-array.js";
4
+ /**
5
+ An if-else-like type that resolves depending on whether the given type is `any` or `never`.
6
+
7
+ @example
8
+ ```
9
+ // When `T` is neither `any` nor `never` (like `string`) => Returns the `ifNot` branch
10
+ type A = IfNotAnyOrNever<string, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
11
+ //=> 'VALID'
12
+
13
+ // When `T` is `any` => Returns the `ifAny` branch
14
+ type B = IfNotAnyOrNever<any, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
15
+ //=> 'IS_ANY'
16
+
17
+ // When `T` is `never` => Returns the `ifNever` branch
18
+ type C = IfNotAnyOrNever<never, {ifNot: 'VALID'; ifAny: 'IS_ANY'; ifNever: 'IS_NEVER'}>;
19
+ //=> 'IS_NEVER'
20
+ ```
21
+
22
+ Note: Wrapping a tail-recursive type with `IfNotAnyOrNever` makes the implementation non-tail-recursive. To fix this, move the recursion into a helper type. Refer to the following example:
23
+
24
+ @example
25
+ ```ts
26
+ import type {StringRepeat} from 'type-fest';
27
+
28
+ type NineHundredNinetyNineSpaces = StringRepeat<' ', 999>;
29
+
30
+ // The following implementation is not tail recursive
31
+ type TrimLeft<S extends string> = IfNotAnyOrNever<S, {ifNot: S extends ` ${infer R}` ? TrimLeft<R> : S}>;
32
+
33
+ // Hence, instantiations with long strings will fail
34
+ // @ts-expect-error
35
+ type T1 = TrimLeft<NineHundredNinetyNineSpaces>;
36
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
37
+ // Error: Type instantiation is excessively deep and possibly infinite.
38
+
39
+ // To fix this, move the recursion into a helper type
40
+ type TrimLeftOptimised<S extends string> = IfNotAnyOrNever<S, {ifNot: _TrimLeftOptimised<S>}>;
41
+
42
+ type _TrimLeftOptimised<S extends string> = S extends ` ${infer R}` ? _TrimLeftOptimised<R> : S;
43
+
44
+ type T2 = TrimLeftOptimised<NineHundredNinetyNineSpaces>;
45
+ //=> ''
46
+ ```
47
+ */
48
+ export type IfNotAnyOrNever<T, Cases extends {
49
+ ifNot: unknown;
50
+ ifAny?: unknown;
51
+ ifNever?: unknown;
52
+ }> = IsAny<T> extends true ? 'ifAny' extends keyof Cases ? Cases['ifAny'] : any : IsNever<T> extends true ? 'ifNever' extends keyof Cases ? Cases['ifNever'] : never : Cases['ifNot'];
53
+ /**
54
+ The call signature of the given type, rebuilt with its `this` parameter, which `Parameters` leaves out, so the rebuilt signature does not accept any receiver. A function that declares no `this` is rebuilt without one, like `OmitThisParameter` does, because `this: unknown` would reject a function that declares a `this`. `unknown` for a type that is not callable, so it can be intersected with anything.
55
+
56
+ Readonly rest parameters are preserved.
57
+
58
+ Note: An overloaded function keeps only its last signature, and a generic one loses its type parameters.
59
+ */
60
+ export type CallSignatureOf<Type> = Type extends ((this: infer Receiver, ...arguments_: infer Arguments extends UnknownArray) => infer Return) ? unknown extends Receiver ? (...arguments_: Arguments) => Return : (this: Receiver, ...arguments_: Arguments) => Return : unknown;
@@ -0,0 +1,31 @@
1
+ /**
2
+ Returns a boolean for whether the given type is `any`.
3
+
4
+ Returns `false` for `never` and `unknown`. Unions are normalized before the check.
5
+
6
+ @see https://stackoverflow.com/a/49928360/1490091
7
+
8
+ Useful in type utilities, such as disallowing `any`s to be passed to a function.
9
+
10
+ @example
11
+ ```
12
+ import type {IsAny} from 'type-fest';
13
+
14
+ const typedObject = {a: 1, b: 2} as const;
15
+ const anyObject: any = {a: 1, b: 2};
16
+
17
+ function get<O extends (IsAny<O> extends true ? {} : Record<string, number>), K extends keyof O = keyof O>(object: O, key: K) {
18
+ return object[key];
19
+ }
20
+
21
+ const typedA = get(typedObject, 'a');
22
+ //=> 1
23
+
24
+ const anyA = get(anyObject, 'a');
25
+ //=> any
26
+ ```
27
+
28
+ @category Type Guard
29
+ @category Utilities
30
+ */
31
+ export type IsAny<T> = 0 extends 1 & NoInfer<T> ? true : false;
@@ -0,0 +1,54 @@
1
+ /**
2
+ Returns a boolean for whether the given type is `never`.
3
+
4
+ @see https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
5
+ @see https://stackoverflow.com/a/53984913/10292952
6
+ @see https://www.zhenghao.io/posts/ts-never
7
+
8
+ Useful in type utilities, such as checking if something does not occur.
9
+
10
+ @example
11
+ ```
12
+ import type {IsNever, And} from 'type-fest';
13
+
14
+ type A = IsNever<never>;
15
+ //=> true
16
+
17
+ type B = IsNever<any>;
18
+ //=> false
19
+
20
+ type C = IsNever<unknown>;
21
+ //=> false
22
+
23
+ type D = IsNever<never[]>;
24
+ //=> false
25
+
26
+ type E = IsNever<object>;
27
+ //=> false
28
+
29
+ type F = IsNever<string>;
30
+ //=> false
31
+ ```
32
+
33
+ @example
34
+ ```
35
+ import type {IsNever} from 'type-fest';
36
+
37
+ type IsTrue<T> = T extends true ? true : false;
38
+
39
+ // When a distributive conditional is instantiated with `never`, the entire conditional results in `never`.
40
+ type A = IsTrue<never>;
41
+ //=> never
42
+
43
+ // If you don't want that behaviour, you can explicitly add an `IsNever` check before the distributive conditional.
44
+ type IsTrueFixed<T> =
45
+ IsNever<T> extends true ? false : T extends true ? true : false;
46
+
47
+ type B = IsTrueFixed<never>;
48
+ //=> false
49
+ ```
50
+
51
+ @category Type Guard
52
+ @category Utilities
53
+ */
54
+ export type IsNever<T> = [T] extends [never] ? true : false;
@@ -0,0 +1,44 @@
1
+ /**
2
+ Create a union of all keys from a given type, even those exclusive to specific union members.
3
+
4
+ Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
5
+
6
+ @see https://stackoverflow.com/a/49402091
7
+
8
+ @example
9
+ ```
10
+ import type {KeysOfUnion} from 'type-fest';
11
+
12
+ type A = {
13
+ common: string;
14
+ a: number;
15
+ };
16
+
17
+ type B = {
18
+ common: string;
19
+ b: string;
20
+ };
21
+
22
+ type C = {
23
+ common: string;
24
+ c: boolean;
25
+ };
26
+
27
+ type Union = A | B | C;
28
+
29
+ type CommonKeys = keyof Union;
30
+ //=> 'common'
31
+
32
+ type AllKeys = KeysOfUnion<Union>;
33
+ //=> 'common' | 'a' | 'b' | 'c'
34
+ ```
35
+
36
+ @category Object
37
+ */
38
+ export type KeysOfUnion<ObjectType> =
39
+ // Adds no keys, since these are the keys all members share, but it lets the compiler accept a key narrowed with `keyof` when `ObjectType` is generic, such as a conditional type that is not resolved yet.
40
+ keyof ObjectType |
41
+ // Infer a union of each member's keys from function return types.
42
+ // This avoids the record intersections and extra `& Union` that `UnionToIntersection` would create.
43
+ // The outer conditional prevents unresolved generic union keys from being treated as safe to index every member.
44
+ ((ObjectType extends unknown ? () => keyof ObjectType : never) extends (() => infer Keys extends PropertyKey) ? Keys : never);