my monorepo for atproto based applications
1/**
2 * GENERATED CODE - DO NOT MODIFY
3 */
4
5import { type ValidationResult } from "@atproto/lexicon";
6
7export type OmitKey<T, K extends keyof T> = {
8 [K2 in keyof T as K2 extends K ? never : K2]: T[K2];
9};
10
11export type $Typed<V, T extends string = string> = V & { $type: T };
12export type Un$Typed<V extends { $type?: string }> = OmitKey<V, "$type">;
13
14export type $Type<Id extends string, Hash extends string> = Hash extends "main"
15 ? Id
16 : `${Id}#${Hash}`;
17
18function isObject<V>(v: V): v is V & object {
19 return v != null && typeof v === "object";
20}
21
22function is$type<Id extends string, Hash extends string>(
23 $type: unknown,
24 id: Id,
25 hash: Hash,
26): $type is $Type<Id, Hash> {
27 return hash === "main"
28 ? $type === id
29 : // $type === `${id}#${hash}`
30 typeof $type === "string" &&
31 $type.length === id.length + 1 + hash.length &&
32 $type.charCodeAt(id.length) === 35 /* '#' */ &&
33 $type.startsWith(id) &&
34 $type.endsWith(hash);
35}
36
37export type $TypedObject<
38 V,
39 Id extends string,
40 Hash extends string,
41> = V extends {
42 $type: $Type<Id, Hash>;
43}
44 ? V
45 : V extends { $type?: string }
46 ? V extends { $type?: infer T extends $Type<Id, Hash> }
47 ? V & { $type: T }
48 : never
49 : V & { $type: $Type<Id, Hash> };
50
51export function is$typed<V, Id extends string, Hash extends string>(
52 v: V,
53 id: Id,
54 hash: Hash,
55): v is $TypedObject<V, Id, Hash> {
56 return isObject(v) && "$type" in v && is$type(v.$type, id, hash);
57}
58
59export function maybe$typed<V, Id extends string, Hash extends string>(
60 v: V,
61 id: Id,
62 hash: Hash,
63): v is V & object & { $type?: $Type<Id, Hash> } {
64 return (
65 isObject(v) &&
66 ("$type" in v ? v.$type === undefined || is$type(v.$type, id, hash) : true)
67 );
68}
69
70export type Validator<R = unknown> = (v: unknown) => ValidationResult<R>;
71export type ValidatorParam<V extends Validator> =
72 V extends Validator<infer R> ? R : never;
73
74/**
75 * Utility function that allows to convert a "validate*" utility function into a
76 * type predicate.
77 */
78export function asPredicate<V extends Validator>(validate: V) {
79 return function <T>(v: T): v is T & ValidatorParam<V> {
80 return validate(v).success;
81 };
82}