Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow caller to customize type parsing behavior #3

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions src/simple-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export type SimpleTypeKind =
| "ARRAY"
// Special types
| "DATE"
| "PROMISE";
| "PROMISE"
| "CUSTOM";

export type SimpleTypeModifierKind = "EXPORT" | "AMBIENT" | "PUBLIC" | "PRIVATE" | "PROTECTED" | "STATIC" | "READONLY" | "ABSTRACT" | "ASYNC" | "DEFAULT";

Expand Down Expand Up @@ -272,7 +273,7 @@ export interface SimpleTypeMethod extends SimpleTypeBase {
export interface SimpleTypeGenericArguments extends SimpleTypeBase {
readonly kind: "GENERIC_ARGUMENTS"; // TODO: rename
/** The generic type being instantiated */
readonly target: Extract<SimpleType, { typeParameters?: unknown }>;
readonly target: Extract<SimpleType, { typeParameters?: unknown }> | SimpleTypeCustom;
/** The arguments passed to the generic */
readonly typeArguments: SimpleType[];
/** The concrete type resulting from applying the type parameters to the generic */
Expand Down Expand Up @@ -321,6 +322,11 @@ export interface SimpleTypePromise extends SimpleTypeBase {
readonly type: SimpleType;
}

export interface SimpleTypeCustom<T = unknown> extends SimpleTypeBase {
readonly kind: "CUSTOM";
readonly extra?: T;
}

export type SimpleType =
| SimpleTypeBigIntLiteral
| SimpleTypeEnumMember
Expand Down Expand Up @@ -354,7 +360,8 @@ export type SimpleType =
| SimpleTypeAlias
| SimpleTypeDate
| SimpleTypeGenericArguments
| SimpleTypeGenericParameter;
| SimpleTypeGenericParameter
| SimpleTypeCustom;

// Collect all values on place. This is a map so Typescript will complain if we forget any kind.
const SIMPLE_TYPE_MAP: Record<SimpleTypeKind, "primitive" | "primitive_literal" | undefined> = {
Expand Down Expand Up @@ -390,7 +397,8 @@ const SIMPLE_TYPE_MAP: Record<SimpleTypeKind, "primitive" | "primitive_literal"
PROMISE: undefined,
TUPLE: undefined,
UNION: undefined,
UNKNOWN: undefined
UNKNOWN: undefined,
CUSTOM: undefined
};

// Primitive, literal
Expand Down Expand Up @@ -447,4 +455,5 @@ export type SimpleTypeKindMap = {
ARRAY: SimpleTypeArray;
DATE: SimpleTypeDate;
PROMISE: SimpleTypePromise;
CUSTOM: SimpleTypeCustom;
};
85 changes: 66 additions & 19 deletions src/transform/to-simple-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,16 +61,35 @@ import {
symbolIsOptional
} from "../utils/ts-util";

export interface ToSimpleTypeOptions {
interface ToSimpleTypePureOptions {
eager?: boolean;
cache?: WeakMap<Type, SimpleType>;
}

interface ToCustomTypeArguments {
type: ts.Type;
checker: ts.TypeChecker;
ts: typeof tsModule;
/** True when `type` is the target of a GENERIC_ARGUMENTS instantiation */
generic: boolean;
}

type ToCustomType = (args: ToCustomTypeArguments) => SimpleType | ((concrete: SimpleType) => SimpleType) | undefined;

interface ToSimpleTypeConfigureTypeConstruction extends ToSimpleTypePureOptions {
/** With these options, the user must provide a cache because options modify how types are built, making repeat calls with the default cache non-deterministic */
cache: WeakMap<Type, SimpleType>;
/** Add methods like .getType(), .getTypeChecker() to each simple type */
addMethods?: boolean;
/** Add { kind: "ALIAS" } wrapper types around simple aliases. Otherwise, remove these wrappers. */
preserveSimpleAliases?: boolean;
/** If defined, called with each type, should return a CUSTOM type or undefined */
toCustomType?: ToCustomType;
}

interface ToSimpleTypeInternalOptions {
export type ToSimpleTypeOptions = ToSimpleTypePureOptions | ToSimpleTypeConfigureTypeConstruction;

interface ToSimpleTypeInternalOptions extends ToSimpleTypeConfigureTypeConstruction {
cache: WeakMap<Type, SimpleType>;
checker: TypeChecker;
ts: typeof tsModule;
Expand Down Expand Up @@ -105,8 +124,9 @@ export function toSimpleType(type: Type | Node | SimpleType, checker?: TypeCheck
checker,
eager: options.eager,
cache: options.cache || DEFAULT_TYPE_CACHE,
addMethods: options.addMethods,
preserveSimpleAliases: options.preserveSimpleAliases,
addMethods: "addMethods" in options ? options.addMethods : undefined,
preserveSimpleAliases: "preserveSimpleAliases" in options ? options.preserveSimpleAliases : undefined,
toCustomType: "toCustomType" in options ? options.toCustomType : undefined,
ts: getTypescriptModule()
});
}
Expand Down Expand Up @@ -207,8 +227,8 @@ function toSimpleTypeCached(type: Type, options: ToSimpleTypeInternalOptions): S
* @param type
* @param options
*/
function liftGenericType(type: Type, options: ToSimpleTypeInternalOptions): { generic: (instantiated: SimpleType) => SimpleType; instantiated: Type } | undefined {
const enhance = (instantiated: SimpleType) => withMethods(instantiated, type, options);
function liftGenericType(type: Type, options: ToSimpleTypeInternalOptions): { wrap: (instantiated: SimpleType) => SimpleType; instantiated: Type } | undefined {
const addMethods = (instantiated: SimpleType) => withMethods(instantiated, type, options);
const wrapIfAlias = (instantiated: SimpleType, ignoreTypeParams?: boolean): SimpleType => {
if (isAlias(type, options.ts)) {
const aliasName = type.aliasSymbol!.getName() || "";
Expand Down Expand Up @@ -257,19 +277,34 @@ function liftGenericType(type: Type, options: ToSimpleTypeInternalOptions): { ge

return {
instantiated: type,
generic: instantiated => {
wrap: instantiated => {
const typeArgumentsSimpleType = typeArguments.map(t => toSimpleTypeCached(t, options));

const generic: SimpleTypeGenericArguments = {
const customType = options.toCustomType?.({
...options,
type: type.target,
generic: true
});

const targetSimpleType =
typeof customType === "function"
? toSimpleTypeCached(type.target, options) /// XXX unlimited recursion?
: customType;

let generic: SimpleType = {
kind: "GENERIC_ARGUMENTS",
target: toSimpleTypeCached(type.target, options) as any,
target: targetSimpleType as any,
instantiated,
typeArguments: typeArgumentsSimpleType
};

if (typeof customType === "function") {
generic = customType(generic);
}

// This makes current tests work, but may be actually incorrect.
// vvvvvv
return enhance(wrapIfAlias(generic, true));
return addMethods(wrapIfAlias(generic, true));
}
};
}
Expand All @@ -279,8 +314,8 @@ function liftGenericType(type: Type, options: ToSimpleTypeInternalOptions): { ge
return {
// TODO: better type safety
instantiated: (type as any).target || type,
generic: instantiated => {
return enhance(wrapIfAlias(instantiated));
wrap: instantiated => {
return addMethods(wrapIfAlias(instantiated));
}
};
}
Expand Down Expand Up @@ -323,20 +358,37 @@ function memberWithMethods<T extends SimpleTypeMember>(obj: T, symbol: ts.Symbol
};
}

function toSimpleTypeInternal(type: Type, options: ToSimpleTypeInternalOptions): SimpleType {
function toSimpleTypeInternal(outerType: Type, options: ToSimpleTypeInternalOptions): SimpleType {
const { checker, ts } = options;

let type = outerType;
const symbol: ESSymbol | undefined = type.getSymbol();
const name = symbol != null ? getRealSymbolName(symbol, ts) : undefined;

let simpleType: SimpleType | undefined;
let enhance: (instantiated: SimpleType) => SimpleType = t => withMethods(t, type, options);

const generic = liftGenericType(type, options);
if (generic != null) {
type = generic.instantiated;
const originalEnhance = enhance;
enhance = t => generic.wrap(originalEnhance(t));
}

const enhance = (obj: SimpleType) => withMethods(obj, type, options);
// Custom types
const customType = options.toCustomType?.({
...options,
type,
generic: false
});
if (customType) {
if (typeof customType === "function") {
const originalEnhance = enhance;
enhance = t => withMethods(customType(originalEnhance(t)), outerType, options);
} else {
return enhance(customType);
}
}

// Literal types
if (isLiteral(type, ts)) {
Expand Down Expand Up @@ -671,11 +723,6 @@ function toSimpleTypeInternal(type: Type, options: ToSimpleTypeInternalOptions):
};
}

// Lift generic types and aliases if possible
if (generic != null) {
return generic.generic(enhance(simpleType));
}

return enhance(simpleType);
}

Expand Down
Loading