Skip to content

Instantly share code, notes, and snippets.

@webstrand
Last active April 3, 2021 22:01
Show Gist options
  • Select an option

  • Save webstrand/c6c2be0f3757ff6fe0f3d999be23940d to your computer and use it in GitHub Desktop.

Select an option

Save webstrand/c6c2be0f3757ff6fe0f3d999be23940d to your computer and use it in GitHub Desktop.
Validate an IPv4 binding string
type Octet =
| `${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`
| `${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`
| `1${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`
| `2${0 | 1 | 2 | 3 | 4 }${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`
| `2${5 }${0 | 1 | 2 | 3 | 4 | 5}`
type Protocol = 'tcp' | 'tcps';
type QuasiIPv4 = `${bigint}.${bigint}.${bigint}.${bigint}`
type QuasiBindingString = `${Protocol}://${'*' | QuasiIPv4}:${bigint}` | `${'ipc' | 'ipcs'}://${string}`;
type ValidateQuasiBindingString<T extends QuasiBindingString> = [T] extends [never] ? T :
T extends `${infer Proto}://${infer A}.${infer B}.${infer C}.${infer D}:${infer Port}`
? A extends Octet
? B extends Octet
? C extends Octet
? D extends Octet
? T
: `${D}` extends `${bigint}` ? `${Proto & Protocol}://${A}.${B}.${C}.${Octet}:${Port}` : QuasiBindingString
: `${C}` extends `${bigint}` ? `${Proto & Protocol}://${A}.${B}.${Octet}.${D}:${Port}` : QuasiBindingString
: `${B}` extends `${bigint}` ? `${Proto & Protocol}://${A}.${Octet}.${C}.${D}:${Port}` : QuasiBindingString
: `${A}` extends `${bigint}` ? `${Proto & Protocol}://${Octet}.${B}.${C}.${D}:${Port}` : QuasiBindingString
: T extends QuasiBindingString ? T : QuasiBindingString;
declare function connect<T extends QuasiBindingString>(s: ValidateQuasiBindingString<T>): void;
connect('tcp://*:50');
connect('tcp://1.1.1.1:50');
connect('tcps://*:50');
connect('tcps://1.1.1.1:50');
connect('ipc://google.com');
connect('ipcs://google.com');
connect('tcpd://*:50');
connect('tcp://1.1.256.1:50');
connect('tcps://*');
connect('tcps://-5.1.1.1:50');
connect('ipcd://google.com');
connect('ipcs:/d/google.com');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment