Compare commits

...

21 Commits

Author SHA1 Message Date
Julien Valverdé
b2eae567c4 0.1.24 (#24)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/24
2024-05-13 01:25:25 +02:00
Julien Valverdé
7bc5d5b812 0.1.23 (#23)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/23
2024-05-12 03:58:36 +02:00
Julien Valverdé
5d949114e7 0.1.22 (#22)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/22
2024-05-12 03:38:52 +02:00
Julien Valverdé
4d19faa494 0.1.21 (#21)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/21
2024-05-12 01:11:51 +02:00
Julien Valverdé
4ff193ea96 0.1.20 (#20)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/20
2024-05-01 02:51:12 +02:00
Julien Valverdé
4b63b68b53 0.1.19 (#19)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/19
2024-03-24 22:21:10 +01:00
Julien Valverdé
ce7f03aa84 0.1.18 (#18)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/18
2024-03-23 20:22:11 +01:00
Julien Valverdé
33ef272114 0.1.17 (#17)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/17
2024-03-23 16:49:39 +01:00
Julien Valverdé
e2fbc1558a 0.1.16 (#16)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/16
2024-03-23 00:51:27 +01:00
Julien Valverdé
82627c88f6 0.1.15 (#15)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/15
2024-03-09 05:16:53 +01:00
Julien Valverdé
c7c10b3127 0.1.14 (#14)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/14
2024-03-08 20:01:21 +01:00
Julien Valverdé
9250a1fd0b 0.1.13 (#13)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/13
2024-02-28 01:27:09 +01:00
Julien Valverdé
1ac7ec5245 0.1.12 (#12)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/12
2024-02-25 03:25:55 +01:00
Julien Valverdé
9d15943c98 0.1.11 (#11)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/11
2024-02-24 23:42:24 +01:00
Julien Valverdé
58448c2135 0.1.10 (#10)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/10
2024-02-22 03:59:12 +01:00
Julien Valverdé
a74a11f684 0.1.9 (#9)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/9
2024-02-22 01:08:42 +01:00
Julien Valverdé
a272fa3b99 0.1.8 (#8)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/8
2024-02-21 17:44:23 +01:00
Julien Valverdé
4cb9ebd589 0.1.7 (#7)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/7
2024-02-21 04:44:24 +01:00
Julien Valverdé
605ae5c613 0.1.6 (#6)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/6
2024-02-20 03:54:13 +01:00
Julien Valverdé
563ed6c6be 0.1.5 (#5)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/5
2024-02-20 01:57:29 +01:00
Julien Valverdé
de3b23018a 0.1.4 (#4)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/traitify-ts/pulls/4
2024-02-20 01:39:38 +01:00
21 changed files with 1125 additions and 440 deletions

View File

@@ -16,8 +16,8 @@ local lint_step = {
local build_step = { local build_step = {
name: "build", name: "build",
image: bun_image, image: node_image,
commands: ["bun run build"], commands: ["npm run build"],
}; };
local pack_step = { local pack_step = {

BIN
bun.lockb

Binary file not shown.

View File

@@ -1,6 +1,6 @@
{ {
"name": "@thilawyn/traitify-ts", "name": "@thilawyn/traitify-ts",
"version": "0.1.3", "version": "0.1.24",
"type": "module", "type": "module",
"publishConfig": { "publishConfig": {
"registry": "https://git.jvalver.de/api/packages/thilawyn/npm/" "registry": "https://git.jvalver.de/api/packages/thilawyn/npm/"
@@ -8,38 +8,58 @@
"files": [ "files": [
"./dist" "./dist"
], ],
"types": "./dist/lib.d.ts",
"exports": { "exports": {
".": { ".": {
"import": { "import": {
"types": "./dist/lib.d.mts", "types": "./dist/lib.d.ts",
"default": "./dist/lib.mjs" "default": "./dist/lib.js"
}, },
"require": { "require": {
"types": "./dist/lib.d.cts", "types": "./dist/lib.d.cts",
"default": "./dist/lib.cjs" "default": "./dist/lib.cjs"
} }
},
"./effect": {
"import": {
"types": "./dist/effect/lib.d.ts",
"default": "./dist/effect/lib.js"
},
"require": {
"types": "./dist/effect/lib.d.cts",
"default": "./dist/effect/lib.cjs"
}
},
"./traitsUnique-DCJN7XEW": {
"import": {
"types": "./dist/traitsUnique-DCJN7XEW.d.ts"
},
"require": {
"types": "./dist/traitsUnique-DCJN7XEW.d.ts"
}
} }
}, },
"scripts": { "scripts": {
"build": "rollup -c rollup.config.ts", "build": "tsup",
"lint:tsc": "tsc --noEmit", "lint:tsc": "tsc --noEmit",
"clean:cache": "rm -f tsconfig.tsbuildinfo", "clean:cache": "rm -f tsconfig.tsbuildinfo",
"clean:dist": "rm -rf dist", "clean:dist": "rm -rf dist",
"clean:node": "rm -rf node_modules" "clean:node": "rm -rf node_modules"
}, },
"dependencies": { "dependencies": {
"hotscript": "^1.0.13", "remeda": "^1.61.0",
"type-fest": "^4.10.2" "type-fest": "^4.18.2"
}, },
"devDependencies": { "devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"bun-types": "latest", "bun-types": "latest",
"npm-check-updates": "^16.14.14", "npm-check-updates": "^16.14.20",
"npm-sort": "^0.0.4", "npm-sort": "^0.0.4",
"rollup": "^4.9.6", "tsup": "^8.0.2",
"rollup-plugin-cleanup": "^3.2.1", "tsx": "^4.10.1",
"rollup-plugin-ts": "^3.4.5", "typescript": "^5.4.5"
"tsx": "^4.7.0", },
"typescript": "^5.3.3" "optionalDependencies": {
"@effect/schema": "^0.67.0",
"effect": "^3.1.3"
} }
} }

View File

@@ -1,43 +0,0 @@
import { nodeResolve } from "@rollup/plugin-node-resolve"
import { defineConfig } from "rollup"
import cleanup from "rollup-plugin-cleanup"
import ts from "rollup-plugin-ts"
import pkg from "./package.json" assert { type: "json" }
export const createBundleConfig = (
input: string,
name: keyof typeof pkg.exports,
) => (
defineConfig({
input,
output: [
{
file: pkg.exports[name].import.default,
format: "esm",
},
{
file: pkg.exports[name].require.default,
format: "cjs",
},
],
external: id => !/^[./]/.test(id),
plugins: [
nodeResolve(),
ts(),
cleanup({
comments: "jsdoc",
extensions: ["ts"],
}),
],
})
)
export default [
createBundleConfig("src/lib.ts", "."),
]

View File

@@ -1,157 +1,136 @@
import { Fn, Pipe, Tuples } from "hotscript" import { AbstractConstructor, Constructor, Simplify } from "type-fest"
import { AbstractClass, Class, Opaque } from "type-fest" import { TraitExpression } from "./TraitExpression"
import { TraitExpression, emptyTraitExpression } from "./TraitExpression" import { Extend, StaticMembers } from "./util"
import { AbstractTag } from "./abstract"
import { ExtendFn, SimplifyFn, StaticMembers, StaticMembersFn } from "./util"
export type TraitApplierSuperTag = "@thilawyn/traitify-ts/TraitApplierSuper"
export type AddAbstractToImplClass<
ImplClass extends Class<{}, []>,
Abstract extends {},
> = (
Class<
Abstract & InstanceType<ImplClass>,
ConstructorParameters<ImplClass>
> &
StaticMembers<ImplClass>
)
export type RemoveAbstractFromImplClass<
ImplClassWithAbstract extends Class<Abstract, []> & { _tag: TraitApplierSuperTag },
Abstract extends {},
> = (
Class<
Omit<InstanceType<ImplClassWithAbstract>, keyof Abstract>,
ConstructorParameters<ImplClassWithAbstract>
> &
Omit<StaticMembers<ImplClassWithAbstract>, "_tag">
)
export class Trait< export class Trait<
Supertraits extends TraitExpression<typeof TraitExpression.NullSuperclass, Trait<any, any, any>[], Trait<any, any, any>[]>, SuperExpression extends TraitExpression<
Abstract extends {}, typeof TraitExpression.NullSuperclass,
ImplClass extends Class<{}, []>, readonly Trait<any, any, any, any>[]
>,
Abstract extends object,
StaticAbstract extends object,
ImplClass extends AbstractConstructor<object, []>,
> { > {
constructor( constructor(
readonly supertraits: Supertraits, readonly superExpression: SuperExpression,
readonly abstract: Abstract, readonly abstract: Abstract,
readonly apply: (Super: AbstractClass<{}>) => ImplClass, readonly staticAbstract: StaticAbstract,
readonly apply: (Super: AbstractConstructor<object>) => ImplClass,
) {} ) {}
} }
export namespace Trait { export namespace Trait {
export type OwnSupertraits<T> = ( export type SuperExpression<T> = (
T extends Trait<infer Supertraits, any, any> T extends Trait<infer SuperExpression, any, any, any>
? Supertraits ? SuperExpression
: never : never
) )
export interface OwnSupertraitsFn extends Fn {
return: Trait.OwnSupertraits<this["arg0"]>
}
export type OwnAbstract<T> = ( export type Supertraits<T> = (
T extends Trait<any, infer Abstract, any> TraitExpression.Traits<Trait.SuperExpression<T>>
)
export type Abstract<T> = (
T extends Trait<any, infer Abstract, any, any>
? Abstract ? Abstract
: never : never
) )
export interface OwnAbstractFn extends Fn {
return: Trait.OwnAbstract<this["arg0"]>
}
export type OwnImplClass<T> = ( export type StaticAbstract<T> = (
T extends Trait<any, any, infer ImplClass> T extends Trait<any, any, infer StaticAbstract, any>
? StaticAbstract
: never
)
export type ImplClass<T> = (
T extends Trait<any, any, any, infer ImplClass>
? ImplClass ? ImplClass
: never : never
) )
export interface OwnImplClassFn extends Fn {
return: Trait.OwnImplClass<this["arg0"]>
}
export type OwnImplInstance<T> = ( export type ImplInstance<T> = (
T extends Trait<any, any, infer ImplClass> InstanceType<Trait.ImplClass<T>>
? InstanceType<ImplClass>
: never
) )
export interface OwnImplInstanceFn extends Fn {
return: Trait.OwnImplInstance<this["arg0"]>
}
export type OwnClass<T> = ( export type ImplStaticMembers<T> = (
T extends Trait<any, infer Abstract, infer ImplClass> StaticMembers<Trait.ImplClass<T>>
? AddAbstractToImplClass<ImplClass, Abstract>
: never
) )
export interface OwnClassFn extends Fn {
return: Trait.OwnClass<this["arg0"]>
}
export type OwnInstance<T> = (
T extends Trait<any, infer Abstract, infer ImplClass>
? InstanceType<
AddAbstractToImplClass<ImplClass, Abstract>
>
: never
)
export interface OwnInstanceFn extends Fn {
return: Trait.OwnInstance<this["arg0"]>
}
export type Supertraits<T> = (
T extends Trait<infer Supertraits, any, any>
? TraitExpression.AllTraits<Supertraits>
: never
)
export interface SupertraitsFn extends Fn {
return: Trait.Supertraits<this["arg0"]>
}
export type Class<T> = (
AbstractClass<
Trait.Instance<T>,
any[]
> &
Pipe<T, [
Trait.SupertraitsFn,
Tuples.Append<T>,
Tuples.Map<Trait.OwnClassFn>,
Tuples.Map<StaticMembersFn>,
ExtendFn,
SimplifyFn,
]>
)
export interface ClassFn extends Fn {
return: Trait.Class<this["arg0"]>
}
export type Instance<T> = ( export type Instance<T> = (
Pipe<T, [ Extend<[
Trait.SupertraitsFn, Trait.Abstract<T>,
Tuples.Append<T>, Trait.ImplInstance<T>,
Tuples.Map<Trait.OwnInstanceFn>,
ExtendFn,
SimplifyFn,
]> ]>
) )
export interface InstanceFn extends Fn {
return: Trait.Instance<this["arg0"]>
}
}
export type Static<T> = (
export function trait< Extend<[
Abstract extends {}, Trait.StaticAbstract<T>,
ImplClassWithAbstract extends Class<Abstract, []> & { _tag: TraitApplierSuperTag }, Trait.ImplStaticMembers<T>,
>( ]>
abstract: Opaque<Abstract, AbstractTag>,
apply: (Super: AbstractClass<Abstract> & { _tag: TraitApplierSuperTag }) => ImplClassWithAbstract,
) {
return new Trait(
emptyTraitExpression,
abstract as Abstract,
apply as any as (Super: AbstractClass<{}>) => RemoveAbstractFromImplClass<ImplClassWithAbstract, Abstract>,
) )
} }
export namespace TraitTuple {
export type MapAbstract<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.Abstract<T[K]>
}
export type MapStaticAbstract<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.StaticAbstract<T[K]>
}
export type MapImplClass<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.ImplClass<T[K]>
}
export type MapImplInstance<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.ImplInstance<T[K]>
}
export type MapImplStaticMembers<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.ImplStaticMembers<T[K]>
}
export type MapInstance<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.Instance<T[K]>
}
export type MapStaticMembers<T> = {
[K in keyof T]: K extends keyof readonly []
? T[K]
: Trait.Static<T[K]>
}
}
export type TraitClass<T extends Trait<any, any, any, any>> = (
AbstractConstructor<TraitInstance<T>, any[]> &
TraitStaticMembers<T>
)
export type TraitConcreteClass<T extends Trait<any, any, any, any>> = (
Constructor<TraitInstance<T>, any[]> &
TraitStaticMembers<T>
)
export type TraitInstance<T extends Trait<any, any, any, any>> = (
Simplify<Trait.Instance<T>>
)
export type TraitStaticMembers<T extends Trait<any, any, any, any>> = (
Simplify<Trait.Static<T>>
)

180
src/TraitBuilder.ts Normal file
View File

@@ -0,0 +1,180 @@
import { AbstractConstructor, Constructor, Simplify } from "type-fest"
import { Trait } from "./Trait"
import { TraitExpression } from "./TraitExpression"
import { Extend, StaticMembers, type } from "./util"
declare const implSuperSymbol: unique symbol
export class TraitBuilder<
SuperExpression extends TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
Abstract extends object,
StaticAbstract extends object,
ImplClass extends AbstractConstructor<object, []>,
> {
constructor(
readonly traitSuperExpression: SuperExpression,
readonly traitAbstract: Abstract,
readonly traitStaticAbstract: StaticAbstract,
readonly traitApply: (Super: AbstractConstructor<object>) => ImplClass,
) {}
abstract<A extends AbstractConstructor<Abstract> & StaticAbstract>(
_: (Super: AbstractConstructor<Abstract> & StaticAbstract) => A
) {
return new TraitBuilder(
this.traitSuperExpression,
{} as Simplify<InstanceType<A>>,
{} as Simplify<StaticMembers<A>>,
this.traitApply,
)
}
abstractType<A extends Abstract>(
_: (Super: Abstract) => typeof type<A>
) {
return new TraitBuilder(
this.traitSuperExpression,
{} as Simplify<A>,
this.traitStaticAbstract,
this.traitApply,
)
}
staticAbstractType<A extends StaticAbstract>(
_: (Super: StaticAbstract) => typeof type<A>
) {
return new TraitBuilder(
this.traitSuperExpression,
this.traitAbstract,
{} as Simplify<A>,
this.traitApply,
)
}
implement<
ImplClassWithAbstract extends TraitBuilder.ImplSuper<typeof this> // TODO: find a way to set the constraint to concrete classes while keeping the Super arg as an abstract class
>(
apply: (Super: TraitBuilder.ImplSuper<typeof this>) => ImplClassWithAbstract
) {
return new TraitBuilder(
this.traitSuperExpression,
this.traitAbstract,
this.traitStaticAbstract,
apply as unknown as (Super: AbstractConstructor<object>) => (
AbstractConstructor<
Simplify<
Omit<
InstanceType<ImplClassWithAbstract>,
keyof Abstract | "constructor"
>
>
> &
Simplify<
Omit<
StaticMembers<ImplClassWithAbstract>,
keyof StaticAbstract | typeof implSuperSymbol
>
>
),
)
}
build() {
return new Trait(
this.traitSuperExpression,
this.traitAbstract,
this.traitStaticAbstract,
this.traitApply,
)
}
}
export namespace TraitBuilder {
export type ImplSuper<This> = (
This extends TraitBuilder<
any,
infer Abstract,
infer StaticAbstract,
infer ImplClass
>
? (
AbstractConstructor<
Simplify<
Extend<[
Abstract,
InstanceType<ImplClass>,
]>
>
> &
Simplify<
Extend<[
StaticAbstract,
StaticMembers<ImplClass>,
]>
> &
{ readonly [implSuperSymbol]: true }
)
: never
)
}
export type ImplStatic<
ImplClass extends AbstractConstructor<object> & { readonly [implSuperSymbol]: true }
> = (
Simplify<
Omit<StaticMembers<ImplClass>, typeof implSuperSymbol>
>
)
export function implStaticThis<
ImplClass extends AbstractConstructor<object> & { readonly [implSuperSymbol]: true },
This extends AbstractConstructor<object>,
>(
_Impl: ImplClass,
thisArg: This,
) {
return thisArg as unknown as (
AbstractConstructor<
InstanceType<ImplClass> & InstanceType<This>,
ConstructorParameters<This>
> &
ImplStatic<ImplClass> &
StaticMembers<This>
)
}
export function implStaticInstantiableThis<
ImplClass extends AbstractConstructor<object> & { readonly [implSuperSymbol]: true },
This extends Constructor<object>,
>(
_Impl: ImplClass,
thisArg: This,
) {
return thisArg as unknown as (
Constructor<
InstanceType<ImplClass> & InstanceType<This>,
ConstructorParameters<This>
> &
ImplStatic<ImplClass> &
StaticMembers<This>
)
}
export const trait = new TraitBuilder(
new TraitExpression(TraitExpression.NullSuperclass, []),
{} as {},
{} as {},
Super => class extends Super {} as AbstractConstructor<{}>,
)

View File

@@ -1,113 +1,176 @@
import { Fn, Pipe, Tuples } from "hotscript" import { AbstractConstructor, Constructor, Simplify } from "type-fest"
import { AbstractClass, Class, Opaque } from "type-fest" import { Trait, TraitTuple } from "./Trait"
import { RemoveAbstractFromImplClass, Trait, TraitApplierSuperTag } from "./Trait" import { TraitBuilder } from "./TraitBuilder"
import { AbstractTag } from "./abstract" import { Extend, StaticMembers } from "./util"
import { ExtendFn, SimplifyFn, StaticMembersFn } from "./util"
// type RemoveSupertraitsAbstractFromAbstract<Left, Right> = { export type TraitExpressionLike<
// [Key in Extract<keyof Left, keyof Right>]: Left[Key] Superclass extends AbstractConstructor<object>,
// } & { Traits extends readonly Trait<any, any, any, any>[],
// [Key in Exclude<keyof Left, keyof Right>]: Left[Key] > = {
// } readonly superclass: Superclass,
readonly traits: Traits,
}
export class TraitExpression< export class TraitExpression<
Superclass extends AbstractClass<{}>, Superclass extends AbstractConstructor<object>,
const OwnTraits extends Trait<any, any, any>[], const Traits extends readonly Trait<any, any, any, any>[],
const AllTraits extends Trait<any, any, any>[], >
> { implements TraitExpressionLike<Superclass, Traits> {
constructor( constructor(
readonly superclass: Superclass, readonly superclass: Superclass,
readonly ownTraits: OwnTraits, readonly traits: Traits,
readonly allTraits: AllTraits,
) {} ) {}
get extends(): ( get extends(): (
AbstractClass< AbstractConstructor<
Pipe<AllTraits, [ InstanceType<Superclass> & // Keep the instance of the superclass outside of any kind of type manipulation
Tuples.Map<Trait.OwnImplInstanceFn>, // Map all the traits to the instance of their implementation class // as it can accidentely remove abstract properties
Tuples.Prepend<InstanceType<Superclass>>, // Add the instance of the superclass at the top of the list Simplify<
ExtendFn, // Reduce to a single instance that extends all the instances in the list Extend<TraitTuple.MapImplInstance<Traits>>
SimplifyFn, // Make readable for IDEs >,
]>,
ConstructorParameters<Superclass> ConstructorParameters<Superclass>
> & > &
Pipe<AllTraits, [ Simplify<
Tuples.Map<Trait.OwnImplClassFn>, // Map all the traits to their implementation class Extend<[
Tuples.Prepend<Superclass>, // Add the superclass at the top of the list StaticMembers<Superclass>,
Tuples.Map<StaticMembersFn>, // Map all the classes to an object containing their static members ...TraitTuple.MapImplStaticMembers<Traits>,
ExtendFn, // Reduce to a single object that extends all the objects in the list
SimplifyFn, // Make readable for IDEs
]> ]>
>
) { ) {
return this.allTraits.reduce( return this.traits.reduce(
(previous, trait) => trait.apply(previous), (previous, trait) => trait.apply(previous),
this.superclass, this.superclass,
) as any ) as any
} }
staticImplements(_target: StaticImplements<typeof this>, _context: any) {}
get staticImplementsStage2() {
return (_target: StaticImplements<typeof this>) => {}
}
subtrait< subtrait<
This extends TraitExpression<typeof TraitExpression.NullSuperclass, any, any>, This extends TraitExpression<typeof TraitExpression.NullSuperclass, any>
SubtraitAbstract extends Implements<This>,
SubtraitImplClassWithAbstract extends Class<SubtraitAbstract, []> & { _tag: TraitApplierSuperTag },
>( >(
this: This, this: This
abstract: (expression: This) => Opaque<SubtraitAbstract, AbstractTag>,
apply: (Super: AbstractClass<SubtraitAbstract> & { _tag: TraitApplierSuperTag }) => SubtraitImplClassWithAbstract,
) { ) {
return new Trait( return new TraitBuilder<This,
Simplify<
Extend<TraitTuple.MapAbstract<Traits>>
>,
Simplify<
Extend<TraitTuple.MapStaticAbstract<Traits>>
>,
AbstractConstructor<
Simplify<
Extend<TraitTuple.MapImplInstance<Traits>>
>
> &
Simplify<
Extend<TraitTuple.MapImplStaticMembers<Traits>>
>
>(
this, this,
// {} as RemoveSupertraitsAbstractFromAbstract<SubtraitAbstract, Implements<typeof this>>, {} as any,
{} as SubtraitAbstract, // TODO: find a way to cleanly substract Implements<typeof this> from this. {} as any,
apply as any as (Super: AbstractClass<{}>) => RemoveAbstractFromImplClass<SubtraitImplClassWithAbstract, SubtraitAbstract>, Super => class extends Super {} as any,
) )
} }
} }
export namespace TraitExpression { export namespace TraitExpression {
const nullSuperclassSymbol = Symbol()
export class NullSuperclass { export class NullSuperclass {
static readonly _tag = "@thilawyn/traitify-ts/TraitExpression.NullSuperclass" static readonly [nullSuperclassSymbol]: true
constructor(..._args: any[]) {}
} }
export type Superclass<T> = ( export type Superclass<T> = (
T extends TraitExpression<infer Superclass, any, any> T extends TraitExpressionLike<infer Superclass, any>
? Superclass ? Superclass
: never : never
) )
export interface SuperclassFn extends Fn {
return: TraitExpression.Superclass<this["arg0"]>
}
export type OwnTraits<T> = ( export type Traits<T> = (
T extends TraitExpression<any, infer OwnTraits, any> T extends TraitExpressionLike<any, infer Traits>
? OwnTraits ? Traits
: never : never
) )
export interface OwnTraitsFn extends Fn {
return: TraitExpression.OwnTraits<this["arg0"]>
} }
export type AllTraits<T> = (
T extends TraitExpression<any, any, infer AllTraits> export type Implements<
? AllTraits Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
: never > = (
Simplify<
Extend<
TraitTuple.MapAbstract<
TraitExpression.Traits<Exp>
>
>
>
) )
export interface AllTraitsFn extends Fn {
return: TraitExpression.AllTraits<this["arg0"]>
}
}
export const emptyTraitExpression = new TraitExpression(TraitExpression.NullSuperclass, [], []) export type StaticImplements<
Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
> = (
Simplify<
Extend<
TraitTuple.MapStaticAbstract<
TraitExpression.Traits<Exp>
>
>
>
)
export type Implements<Exp extends TraitExpression<any, any, any>> = ( export type TraitExpressionClass<
Pipe<Exp, [ Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
TraitExpression.AllTraitsFn, > = (
Tuples.Map<Trait.OwnAbstractFn>, AbstractConstructor<
ExtendFn, TraitExpressionInstance<Exp>,
SimplifyFn, ConstructorParameters<TraitExpression.Superclass<Exp>>
> &
TraitExpressionStaticMembers<Exp>
)
export type TraitExpressionInstantiableClass<
Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
> = (
Constructor<
TraitExpressionInstance<Exp>,
ConstructorParameters<TraitExpression.Superclass<Exp>>
> &
TraitExpressionStaticMembers<Exp>
)
export type TraitExpressionInstance<
Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
> = (
InstanceType<TraitExpression.Superclass<Exp>> & // Keep the instance of the superclass outside of any kind of type manipulation
// as it can accidentely remove abstract properties
Simplify<
Extend<
TraitTuple.MapInstance<TraitExpression.Traits<Exp>>
>
>
)
export type TraitExpressionStaticMembers<
Exp extends TraitExpressionLike<any, readonly Trait<any, any, any, any>[]>
> = (
Simplify<
Extend<[
StaticMembers<TraitExpression.Superclass<Exp>>,
...TraitTuple.MapStaticMembers<TraitExpression.Traits<Exp>>,
]> ]>
>
) )

View File

@@ -1,129 +1,150 @@
import { Call, Fn, Pipe, Tuples } from "hotscript" import { AbstractConstructor } from "type-fest"
import { AbstractClass } from "type-fest" import { Trait, TraitTuple } from "./Trait"
import { Trait } from "./Trait" import { TraitExpression } from "./TraitExpression"
import { TraitExpression, emptyTraitExpression } from "./TraitExpression" import { SpreadSupertraits, spreadSupertraits } from "./spreadSupertraits"
import { ExtendableFn, StaticMembersFn } from "./util" import { TraitsUnique, traitsUnique } from "./traitsUnique"
import { Extendable, StaticMembers } from "./util"
type SpreadSupertraits<Traits extends Trait<any, any, any>[]> = ( export class TraitExpressionBuilder<
Call< Superclass extends AbstractConstructor<object>,
Tuples.FlatMap<PrependTraitSupertraitsFn>, const Traits extends readonly Trait<any, any, any, any>[],
Traits
>
)
interface PrependTraitSupertraitsFn extends Fn {
return: [...Trait.Supertraits<this["arg0"]>, this["arg0"]]
}
type AbstractMembersExtendable<
Superclass extends AbstractClass<{}>,
Traits extends Trait<any, any, any>[],
> = (
Pipe<Traits, [
Tuples.Map<Trait.OwnAbstractFn>,
Tuples.Prepend<InstanceType<Superclass>>,
]>
)
type ImplInstanceExtendable<
Superclass extends AbstractClass<{}>,
Traits extends Trait<any, any, any>[],
> = (
Pipe<Traits, [
Tuples.Map<Trait.OwnImplInstanceFn>,
Tuples.Prepend<InstanceType<Superclass>>,
]>
)
type ImplStaticMembersExtendable<
Superclass extends AbstractClass<{}>,
Traits extends Trait<any, any, any>[],
> = (
Pipe<Traits, [
Tuples.Map<Trait.OwnImplClassFn>,
Tuples.Prepend<Superclass>,
Tuples.Map<StaticMembersFn>,
ExtendableFn,
]>
)
type BuildTraitExpression<
Superclass extends AbstractClass<{}>,
OwnTraits extends Trait<any, any, any>[],
AllTraits extends Trait<any, any, any>[],
> = (
AbstractMembersExtendable<Superclass, AllTraits> extends false
? "Type conflict between the traits abstract members and/or the superclass instance."
: ImplInstanceExtendable<Superclass, AllTraits> extends false
? "Type conflict between the traits implementation instances and/or the superclass instance."
: ImplStaticMembersExtendable<Superclass, AllTraits> extends false
? "Type conflict between the traits implementation static members and/or the superclass static members."
: TraitExpression<Superclass, OwnTraits, AllTraits>
)
class TraitExpressionBuilder<
Superclass extends AbstractClass<{}>,
const OwnTraits extends Trait<any, any, any>[],
const AllTraits extends Trait<any, any, any>[],
> { > {
constructor(private expression: TraitExpression<Superclass, OwnTraits, AllTraits>) {} constructor(
readonly expressionSuperclass: Superclass,
readonly expressionTraits: Traits,
) {}
extends< extends<
Super extends AbstractClass<any> Super extends AbstractConstructor<object>
>( >(
superclass: Super superclass: Super
) { ) {
return new TraitExpressionBuilder( return new TraitExpressionBuilder(
new TraitExpression(
superclass, superclass,
this.expression.ownTraits, this.expressionTraits,
this.expression.allTraits,
)
) )
} }
expresses< expresses<
const Traits extends Trait<any, any, any>[] const T extends readonly Trait<
>( TraitExpression<
...traits: Traits typeof TraitExpression.NullSuperclass,
): TraitExpressionBuilder< readonly Trait<any, any, any, any>[]
Superclass, >,
[...OwnTraits, ...Traits], any,
[...AllTraits, ...SpreadSupertraits<Traits>]
> {
return new TraitExpressionBuilder(
new TraitExpression(
this.expression.superclass,
[...this.expression.ownTraits, ...traits],
[...this.expression.allTraits, ...this.spreadSupertraits(traits)],
)
)
}
private spreadSupertraits<
const Traits extends Trait<
TraitExpression<any, any, Trait<any, any, any>[]>,
any, any,
any any
>[] >[]
>( >(
traits: Traits ...traits: T
) { ): TraitExpressionBuilder<
return traits.flatMap(trait => [ Superclass,
...trait.supertraits.allTraits, TraitExpressionBuilder.ExpressesReturnTypeTraits<Traits, T>
trait, > {
]) as SpreadSupertraits<Traits> return new TraitExpressionBuilder(
this.expressionSuperclass,
traitsUnique([
...this.expressionTraits,
...spreadSupertraits(traits),
]),
)
} }
expressesFirst<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
...traits: T
): TraitExpressionBuilder<
Superclass,
TraitExpressionBuilder.ExpressesFirstReturnTypeTraits<Traits, T>
> {
return new TraitExpressionBuilder(
this.expressionSuperclass,
traitsUnique([
...spreadSupertraits(traits),
...this.expressionTraits,
]),
)
}
build() { build() {
return this.expression as BuildTraitExpression<Superclass, OwnTraits, AllTraits> return new TraitExpression(
this.expressionSuperclass,
this.expressionTraits,
) as TraitExpressionBuilder.BuildTraitExpression<Superclass, Traits>
} }
then<V>(fn: (expression: ReturnType<typeof this.build>) => V): V { then<V>(fn: (expression: ReturnType<typeof this.build>) => V): V {
return fn(this.build()) return fn(this.build())
} }
buildAnyway() {
return new TraitExpression(
this.expressionSuperclass,
this.expressionTraits,
)
} }
export const expression = new TraitExpressionBuilder(emptyTraitExpression) thenAnyway<V>(fn: (expression: ReturnType<typeof this.buildAnyway>) => V): V {
return fn(this.buildAnyway())
}
}
export namespace TraitExpressionBuilder {
export type ExpressesReturnTypeTraits<
Traits extends readonly Trait<any, any, any, any>[],
T extends readonly Trait<any, any, any, any>[],
> = (
TraitsUnique<readonly [
...Traits,
...SpreadSupertraits<T>,
]>
)
export type ExpressesFirstReturnTypeTraits<
Traits extends readonly Trait<any, any, any, any>[],
T extends readonly Trait<any, any, any, any>[],
> = (
TraitsUnique<readonly [
...SpreadSupertraits<T>,
...Traits,
]>
)
export type BuildTraitExpression<
Superclass extends AbstractConstructor<object>,
Traits extends readonly Trait<any, any, any, any>[],
> = (
Extendable<TraitTuple.MapAbstract<Traits>> extends false
? "Type conflict between the traits abstract definitions."
: Extendable<TraitTuple.MapStaticAbstract<Traits>> extends false
? "Type conflict between the traits static abstract definitions."
: Extendable<[
InstanceType<Superclass>,
...TraitTuple.MapImplInstance<Traits>,
]> extends false
? "Type conflict between the traits implementation instance and/or the superclass instance."
: Extendable<[
StaticMembers<Superclass>,
...TraitTuple.MapImplStaticMembers<Traits>,
]> extends false
? "Type conflict between the traits implementation static members and/or the superclass static members."
: TraitExpression<Superclass, Traits>
)
}
export const expression = new TraitExpressionBuilder(TraitExpression.NullSuperclass, [])

View File

@@ -1,10 +0,0 @@
import { Opaque } from "type-fest"
export type AbstractTag = "@thilawyn/traitify-ts/Abstract"
export function abstract<
Abstract extends {} = {}
>() {
return {} as Opaque<Abstract, AbstractTag>
}

View File

@@ -0,0 +1,83 @@
import { Schema as S } from "@effect/schema"
import { AbstractConstructor, Simplify } from "type-fest"
import { Trait, TraitTuple } from "../Trait"
import { StaticImplements, TraitExpressionLike } from "../TraitExpression"
import { Extend, StaticMembers } from "../util"
export class EffectSchemaTraitExpression<
Fields extends S.Struct.Fields,
I, R, C,
Inherited extends object,
Proto,
Static extends object,
const Traits extends readonly Trait<any, any, any, any>[],
const Mutability extends "Immutable" | "Mutable",
const EncodedMutability extends "Immutable" | "Mutable",
>
implements TraitExpressionLike<
S.Class<unknown, Fields, I, R, C, Inherited, Proto>,
Traits
> {
constructor(
readonly superclass: S.Class<unknown, Fields, I, R, C, Inherited, Proto>,
readonly superclassStatic: Static,
readonly traits: Traits,
readonly mutability: Mutability,
readonly encodedMutability: EncodedMutability,
) {}
extends<Self>(): (
AbstractConstructor<
Simplify<
ApplyMutability<S.Struct.Type<Fields>, Mutability> &
Extend<[
Omit<Inherited, keyof Fields>,
...TraitTuple.MapImplInstance<Traits>
]> &
Proto
>,
ConstructorParameters<S.Class<unknown, Fields, I, R, C, Inherited, Proto>>
> &
StaticMembers<
S.Class<
Self,
Fields,
ApplyMutability<I, EncodedMutability>,
R, C,
Inherited,
Proto
>
> &
Simplify<
Extend<[
Static,
...TraitTuple.MapImplStaticMembers<Traits>
]>
>
) {
return this.traits.reduce(
(previous, trait) => trait.apply(previous),
this.superclass,
) as any
}
staticImplements(_target: StaticImplements<typeof this>, _context: any) {}
get staticImplementsStage2() {
return (_target: StaticImplements<typeof this>) => {}
}
}
type ApplyMutability<T, Mutability extends "Immutable" | "Mutable"> = (
Mutability extends "Immutable"
? { +readonly [P in keyof T]: T[P] }
: { -readonly [P in keyof T]: T[P] }
)

View File

@@ -0,0 +1,206 @@
import { Schema as S } from "@effect/schema"
import { Simplify } from "type-fest"
import { Trait, TraitTuple } from "../Trait"
import { TraitExpression } from "../TraitExpression"
import { TraitExpressionBuilder } from "../TraitExpressionBuilder"
import { spreadSupertraits } from "../spreadSupertraits"
import { traitsUnique } from "../traitsUnique"
import { Extendable, StaticMembers } from "../util"
import { EffectSchemaTraitExpression } from "./EffectSchemaTraitExpression"
export class EffectSchemaInitialTraitExpressionBuilder {
class<
Fields extends S.Struct.Fields
>(
identifier: string,
fields: Fields,
annotations?: S.Annotations.Schema<unknown>,
) {
return new EffectSchemaTraitExpressionBuilder(
S.Class<unknown>(identifier)(fields, annotations),
{},
[],
"Immutable",
"Immutable",
)
}
taggedClass<
Tag extends string,
Fields extends S.Struct.Fields,
>(
tag: Tag,
fields: Fields,
annotations?: S.Annotations.Schema<unknown>,
) {
return new EffectSchemaTraitExpressionBuilder(
S.TaggedClass<unknown>()(tag, fields, annotations),
{},
[],
"Immutable",
"Immutable",
)
}
extends<
Super extends StaticMembers<S.Class<Self, Fields, I, R, C, Inherited, Proto>>,
Self extends object,
Fields extends S.Struct.Fields,
I, R, C,
Inherited extends object,
Proto,
NewFields extends S.Struct.Fields,
>(
superclass: Super | StaticMembers<S.Class<Self, Fields, I, R, C, Inherited, Proto>>,
identifier: string,
fields: NewFields,
annotations?: S.Annotations.Schema<unknown>,
) {
return new EffectSchemaTraitExpressionBuilder(
superclass.extend<unknown>(identifier)(fields, annotations),
{} as Simplify<
Omit<Super,
"prototype" | keyof S.Class<Self, Fields, I, R, C, Inherited, Proto>
>
>,
[],
"Immutable",
"Immutable",
)
}
}
export class EffectSchemaTraitExpressionBuilder<
Fields extends S.Struct.Fields,
I, R, C,
Inherited extends object,
Proto,
Static extends object,
const Traits extends readonly Trait<any, any, any, any>[],
const Mutability extends "Immutable" | "Mutable",
const EncodedMutability extends "Immutable" | "Mutable",
> {
constructor(
readonly expressionSuperclass: S.Class<unknown, Fields, I, R, C, Inherited, Proto>,
readonly expressionSuperclassStatic: Static,
readonly expressionTraits: Traits,
readonly expressionMutability: Mutability,
readonly expressionEncodedMutability: EncodedMutability,
) {}
mutable() {
return new EffectSchemaTraitExpressionBuilder(
this.expressionSuperclass,
this.expressionSuperclassStatic,
this.expressionTraits,
"Mutable",
this.expressionEncodedMutability,
)
}
immutable() {
return new EffectSchemaTraitExpressionBuilder(
this.expressionSuperclass,
this.expressionSuperclassStatic,
this.expressionTraits,
"Immutable",
this.expressionEncodedMutability,
)
}
mutableEncoded() {
return new EffectSchemaTraitExpressionBuilder(
this.expressionSuperclass,
this.expressionSuperclassStatic,
this.expressionTraits,
this.expressionMutability,
"Mutable",
)
}
immutableEncoded() {
return new EffectSchemaTraitExpressionBuilder(
this.expressionSuperclass,
this.expressionSuperclassStatic,
this.expressionTraits,
this.expressionMutability,
"Immutable",
)
}
expresses<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
...traits: T
) {
return new EffectSchemaTraitExpressionBuilder(
this.expressionSuperclass,
this.expressionSuperclassStatic,
traitsUnique([
...this.expressionTraits,
...spreadSupertraits(traits),
]) as TraitExpressionBuilder.ExpressesReturnTypeTraits<Traits, T>,
this.expressionMutability,
this.expressionEncodedMutability,
)
}
build(): (
Extendable<TraitTuple.MapAbstract<Traits>> extends false
? "Type conflict between the traits abstract definitions."
: Extendable<TraitTuple.MapStaticAbstract<Traits>> extends false
? "Type conflict between the traits static abstract definitions."
: Extendable<[
InstanceType<typeof this.expressionSuperclass>,
...TraitTuple.MapImplInstance<Traits>,
]> extends false
? "Type conflict between the traits implementation instance and/or the superclass instance."
: Extendable<[
Static,
...TraitTuple.MapImplStaticMembers<Traits>,
]> extends false
? "Type conflict between the traits implementation static members and/or the superclass static members."
: EffectSchemaTraitExpression<
Fields,
I, R, C,
Inherited,
Proto,
Static,
Traits,
Mutability,
EncodedMutability
>
) {
return new EffectSchemaTraitExpression(
this.expressionSuperclass,
this.expressionSuperclassStatic,
this.expressionTraits,
this.expressionMutability,
this.expressionEncodedMutability,
) as any
}
}
export const effectSchemaExpression = new EffectSchemaInitialTraitExpressionBuilder()

2
src/effect/lib.ts Normal file
View File

@@ -0,0 +1,2 @@
export { EffectSchemaTraitExpression } from "./EffectSchemaTraitExpression"
export { EffectSchemaInitialTraitExpressionBuilder, EffectSchemaTraitExpressionBuilder, effectSchemaExpression } from "./EffectSchemaTraitExpressionBuilder"

48
src/effect/tests.ts Normal file
View File

@@ -0,0 +1,48 @@
import { Schema as S } from "@effect/schema"
import { Implements } from "../TraitExpression"
import { effectSchemaExpression } from "./EffectSchemaTraitExpressionBuilder"
type RequiredKeys<T> = {
[K in keyof T]-?: {} extends Pick<T, K> ? never : K
}[keyof T]
type InspectSchemaClass<T> = T extends S.Class<infer Self, infer Fields, infer I, infer R, infer C, infer Inherited, infer Proto>
? Inherited
: never
const userExp = effectSchemaExpression
.class("User", {
id: S.BigIntFromSelf,
role: S.Union(S.Literal("User"), S.Literal("Admin")),
})
.mutable()
.mutableEncoded()
.build()
@userExp.staticImplements
export class User extends userExp.extends<User>() implements Implements<typeof userExp> {
aMethodThatShouldBeInherited() {}
static aStaticMethodThatShouldBeInherited() {}
}
User.Encoded
const user = new User({ id: 0n, role: "User" })
user.id = 0n
const adminExp = effectSchemaExpression
.extends(User, "User", {
role: S.Literal("Admin")
})
// .immutable()
.build()
@adminExp.staticImplements
export class Admin extends adminExp.extends<Admin>() implements Implements<typeof adminExp> {
}
const admin = new Admin({ id: 1n, role: "Admin" })
// admin.role = "Admin"

View File

@@ -1,4 +1,5 @@
export { trait, type Trait } from "./Trait" export { Trait, TraitClass, TraitConcreteClass, TraitInstance, TraitStaticMembers, TraitTuple } from "./Trait"
export { Implements, type TraitExpression } from "./TraitExpression" export { ImplStatic, TraitBuilder, implStaticInstantiableThis, implStaticThis, trait } from "./TraitBuilder"
export { expression } from "./TraitExpressionBuilder" export { Implements, StaticImplements, TraitExpression, TraitExpressionClass, TraitExpressionInstance, TraitExpressionInstantiableClass, TraitExpressionStaticMembers } from "./TraitExpression"
export { abstract } from "./abstract" export { TraitExpressionBuilder, expression } from "./TraitExpressionBuilder"
export { type } from "./util"

35
src/spreadSupertraits.ts Normal file
View File

@@ -0,0 +1,35 @@
import { Trait } from "./Trait"
import { TraitExpression } from "./TraitExpression"
export function spreadSupertraits<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
traits: T
) {
return traits.flatMap(trait => [
...trait.superExpression.traits,
trait,
]) as readonly Trait<any, any, any, any>[] as SpreadSupertraits<T>
}
export type SpreadSupertraits<Traits> = (
Traits extends readonly [
infer El extends Trait<any, any, any, any>,
...infer Rest,
]
? readonly [
...Trait.Supertraits<El>,
El,
...SpreadSupertraits<Rest>,
]
: readonly []
)

View File

@@ -1,67 +1,74 @@
import { Trait, trait } from "./Trait" import { TraitClass } from "./Trait"
import { Implements } from "./TraitExpression" import { trait } from "./TraitBuilder"
import { Implements, StaticImplements, TraitExpressionClass } from "./TraitExpression"
import { expression } from "./TraitExpressionBuilder" import { expression } from "./TraitExpressionBuilder"
import { abstract } from "./abstract" import { type } from "./util"
const PrintsHelloOnNew = trait( const PrintsHelloOnNew = trait
abstract(), .implement(Super => class PrintsHelloOnNew extends Super {
Super => class PrintsHelloOnNew extends Super {
static readonly isPrintsHelloOnNew = true static readonly isPrintsHelloOnNew = true
constructor(...args: any[]) { constructor(...args: any[]) {
super(...args) super(...args)
console.log("Hello!") console.log("Hello!")
} }
}, })
) .build()
type PrintsHelloOnNewClass = Trait.Class<typeof PrintsHelloOnNew>
const Identifiable = <ID>() => trait( type PrintsHelloOnNewClass = TraitClass<typeof PrintsHelloOnNew>
abstract<{ readonly id: ID }>(),
Super => class Identifiable extends Super { const Identifiable = <ID>() => trait
// .abstract(Super => class extends Super {
// declare readonly id: ID
// })
.abstractType(Super => type<typeof Super & {
readonly id: ID
}>)
.implement(Super => class Identifiable extends Super {
equals(el: Identifiable) { equals(el: Identifiable) {
return this.id === el.id return this.id === el.id
} }
}, })
) .build()
const StatefulSubscription = trait( const ImplementsIdentifiable = <ID>(defaultID: ID) => expression
abstract<{ .expresses(Identifiable<ID>())
readonly isStatefulSubscription: true .build()
readonly status: ( .subtrait()
.implement(Super => class ImplementsIdentifiable extends Super {
readonly id = defaultID
})
.build()
const StatefulSubscription = trait
.abstract(Super => class extends Super {
declare readonly isStatefulSubscription: true
declare readonly status: (
{ _tag: "awaitingPayment" } | { _tag: "awaitingPayment" } |
{ _tag: "active", activeSince: Date, expiresAt?: Date } | { _tag: "active", activeSince: Date, expiresAt?: Date } |
{ _tag: "expired", expiredSince: Date } { _tag: "expired", expiredSince: Date }
) )
}>(), })
.build()
Super => class StatefulSubscription extends Super {}, type StatefulSubscriptionClass = TraitClass<typeof StatefulSubscription>
)
type StatefulSubscriptionClass = Trait.Class<typeof StatefulSubscription>
const ActiveStatefulSubscription = expression const ActiveStatefulSubscription = expression
.expresses(StatefulSubscription) .expresses(StatefulSubscription)
.build() .build()
.subtrait( .subtrait()
exp => { .abstract(Super => class extends Super {
interface IActiveStatefulSubscription extends Implements<typeof exp> { declare readonly isActiveStatefulSubscription: true
readonly isActiveStatefulSubscription: true declare readonly status: { _tag: "active", activeSince: Date, expiresAt?: Date }
readonly status: { _tag: "active", activeSince: Date, expiresAt?: Date } })
} .build()
return abstract<IActiveStatefulSubscription>()
},
Super => class ActiveStatefulSubscription extends Super {},
)
type ActiveStatefulSubscriptionClass = Trait.Class<typeof ActiveStatefulSubscription>
type ActiveStatefulSubscriptionClass = TraitClass<typeof ActiveStatefulSubscription>
class TestSuperclass { class TestSuperclass {
// id: number = 69 // id: number = 69
// static test = 69 static test = 69
} }
const exp = expression const exp = expression
@@ -70,12 +77,16 @@ const exp = expression
PrintsHelloOnNew, PrintsHelloOnNew,
Identifiable<bigint>(), Identifiable<bigint>(),
// Identifiable<number>(), // Identifiable<number>(),
// StatefulSubscription,
ActiveStatefulSubscription, ActiveStatefulSubscription,
) )
.build() .build()
type Abs = Implements<typeof exp> type Abs = Implements<typeof exp>
type AbsStatic = StaticImplements<typeof exp>
type ExpClass = TraitExpressionClass<typeof exp>
@exp.staticImplements
class User extends exp.extends implements Implements<typeof exp> { class User extends exp.extends implements Implements<typeof exp> {
readonly isStatefulSubscription: true = true readonly isStatefulSubscription: true = true
readonly isActiveStatefulSubscription: true = true readonly isActiveStatefulSubscription: true = true

39
src/traitsUnique.ts Normal file
View File

@@ -0,0 +1,39 @@
import { unique } from "remeda"
import { IsEqual } from "type-fest"
import { Trait } from "./Trait"
import { TraitExpression } from "./TraitExpression"
export function traitsUnique<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
traits: T
) {
return unique(traits) as readonly Trait<any, any, any, any>[] as TraitsUnique<T>
}
export type TraitsUnique<Traits> = (
Traits extends readonly [
...infer Rest,
infer El extends Trait<any, any, any, any>,
]
? IsTraitInTupleFromRight<Rest, El> extends true
? TraitsUnique<Rest>
: readonly [...TraitsUnique<Rest>, El]
: readonly []
)
type IsTraitInTupleFromRight<Traits, T> = (
Traits extends readonly [...infer Rest, infer El]
? IsEqual<El, T> extends true
? true
: IsTraitInTupleFromRight<Rest, T>
: false
)

View File

@@ -1,25 +1,71 @@
import { Call, ComposeLeft, Fn, Match, Tuples } from "hotscript"
import { CommonKeys } from "." import { CommonKeys } from "."
type ExtendReducer<Super, Self> = ( // type ExtendReducer<Super, Self> = (
Pick<Self, CommonKeys<Self, Super>> extends Pick<Super, CommonKeys<Self, Super>> // Pick<Self, CommonKeys<Self, Super>> extends Pick<Super, CommonKeys<Self, Super>>
? Omit<Super, CommonKeys<Self, Super>> & Self // ? Omit<Super, CommonKeys<Self, Super>> & Self
// : never
// )
// interface ExtendReducerFn extends Fn {
// return: ExtendReducer<this["arg0"], this["arg1"]>
// }
// export type ExtendFn = Tuples.Reduce<ExtendReducerFn, {}>
// export type ExtendableFn = ComposeLeft<[
// ExtendFn,
// Match<[
// Match.With<never, false>,
// Match.With<any, true>,
// ]>
// ]>
// TODO: use OverrideProperties from type-fest?
export type Extend<T extends readonly object[]> = (
T extends readonly [
infer Super,
infer Self,
...infer Rest extends readonly object[],
]
? Pick<Self, CommonKeys<Self, Super>> extends Pick<Super, CommonKeys<Self, Super>>
? Extend<readonly [
Omit<Super, CommonKeys<Self, Super>> & Self,
...Rest,
]>
: never : never
: T extends readonly [infer Self]
? Self
: {}
) )
interface ExtendReducerFn extends Fn {
return: ExtendReducer<this["arg0"], this["arg1"]>
}
export type ExtendFn = Tuples.Reduce<ExtendReducerFn, {}> export type Extendable<T extends readonly object[]> = (
export type Extend<T extends {}[]> = Call<ExtendFn, T> T extends readonly [
infer Super,
infer Self,
export type ExtendableFn = ComposeLeft<[ ...infer Rest extends readonly object[],
ExtendFn, ]
Match<[ ? Pick<Self, CommonKeys<Self, Super>> extends Pick<Super, CommonKeys<Self, Super>>
Match.With<never, false>, ? Extendable<readonly [
Match.With<any, true>, Omit<Super, CommonKeys<Self, Super>> & Self,
...Rest,
]> ]>
: false
: true
)
export type NonExtendableKeys<T extends readonly object[]> = (
T extends readonly [
infer Super extends object,
infer Self extends object,
...infer Rest extends readonly object[],
]
? {[K in keyof Super & keyof Self]: Self[K] extends Super[K]
? never
: K
}[keyof Super & keyof Self]
| NonExtendableKeys<readonly [
Super & Self,
...Rest,
]> ]>
export type Extendable<T extends {}[]> = Call<ExtendableFn, T> : void
)

View File

@@ -1,5 +1,4 @@
import { Fn } from "hotscript" import { AbstractConstructor } from "type-fest"
import { AbstractClass, Simplify } from "type-fest"
/** /**
@@ -9,17 +8,10 @@ import { AbstractClass, Simplify } from "type-fest"
*/ */
export type CommonKeys<A, B> = Extract<keyof A, keyof B> export type CommonKeys<A, B> = Extract<keyof A, keyof B>
export interface SimplifyFn extends Fn {
return: Simplify<this["arg0"]>
}
/** /**
* Represents the static members of a class. * Represents the static members of a class.
* @template Class - A class extending AbstractClass. * @template Class - A class.
*/ */
export type StaticMembers<Class extends AbstractClass<any>> = ( export type StaticMembers<Class extends AbstractConstructor<any>> = Omit<Class, "prototype">
Omit<Class, "prototype">
) export function type<T>() { return {} as T }
export interface StaticMembersFn extends Fn {
return: StaticMembers<this["arg0"]>
}

View File

@@ -8,7 +8,7 @@
// "allowImportingTsExtensions": true, // "allowImportingTsExtensions": true,
// "noEmit": true, // "noEmit": true,
"declaration": true, "declaration": true,
"composite": true, // "composite": true,
"strict": true, "strict": true,
"downlevelIteration": true, "downlevelIteration": true,
"skipLibCheck": true, "skipLibCheck": true,

12
tsup.config.ts Normal file
View File

@@ -0,0 +1,12 @@
import { defineConfig } from "tsup"
export default defineConfig({
entry: ["./src/lib.ts", "./src/effect/lib.ts"],
format: ["esm", "cjs"],
skipNodeModulesBundle: true,
dts: true,
splitting: true,
sourcemap: true,
clean: true,
})