Skip to content

Replace ts keyof transformer usage with runtime code #3413

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

Merged
merged 6 commits into from
May 2, 2025
Merged
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
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@
"@nestjs/platform-fastify": "^11.1.0",
"@patarapolw/prettyprint": "^1.0.3",
"@seedcompany/cache": "^3.0.2",
"@seedcompany/common": ">=0.17 <1",
"@seedcompany/common": ">=0.19.1 <1",
"@seedcompany/data-loader": "^2.0.1",
"@seedcompany/nest": "^1.4.0",
"@seedcompany/nest": "^1.6.1",
"@seedcompany/nestjs-email": "^4.1.1",
"@seedcompany/scripture": ">=0.8.0",
"argon2": "^0.43.0",
Expand Down
3 changes: 3 additions & 0 deletions src/common/lazy-ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ export const lazyRef = <T extends object>(getter: () => T): T => {
getPrototypeOf() {
return Reflect.getPrototypeOf(getter());
},
getOwnPropertyDescriptor(target: T, p: string | symbol) {
return Object.getOwnPropertyDescriptor(getter(), p);
},
});
};

Expand Down
24 changes: 18 additions & 6 deletions src/components/authorization/policy/actions.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
import { EnumType, makeEnum } from '@seedcompany/nest';

/**
* Valid actions for resources
*/
export type ResourceAction = 'read' | 'edit' | 'create' | 'delete';
export type ResourceAction = EnumType<typeof ResourceAction>;
export const ResourceAction = makeEnum(['read', 'edit', 'create', 'delete']);

/**
* Valid actions for properties
*/
export type PropAction = 'read' | 'edit';
export type PropAction = EnumType<typeof PropAction>;
export const PropAction = makeEnum(['read', 'edit']);

/**
* Valid actions for child relationships
*/
export type ChildRelationshipAction = 'read' | 'create' | 'delete';
export type ChildRelationshipAction = EnumType<typeof ChildRelationshipAction>;
export const ChildRelationshipAction = makeEnum(['read', 'create', 'delete']);

/**
* Valid actions for child One-to-Many relationships
*/
export type ChildListAction = 'read' | 'create' | 'delete';
export type ChildListAction = EnumType<typeof ChildListAction>;
export const ChildListAction = makeEnum(['read', 'create', 'delete']);

/**
* Valid actions for child One-to-One relationships
*/
export type ChildSingleAction = 'read' | 'edit';
export type ChildSingleAction = EnumType<typeof ChildSingleAction>;
export const ChildSingleAction = makeEnum(['read', 'edit']);

/**
* Probably don't use directly
* @internal
*/
export type AnyAction = ResourceAction | PropAction | ChildRelationshipAction;
export type AnyAction = EnumType<typeof AnyAction>;
export const AnyAction = makeEnum([
...ResourceAction,
...PropAction,
...ChildRelationshipAction,
]);
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mapValues } from '@seedcompany/common';
import { EnumType, makeEnum } from '@seedcompany/nest';
import { startCase } from 'lodash';
import { keys as keysOf } from 'ts-transformer-keys';
import { PascalCase } from 'type-fest';
import {
ChildListsKey,
Expand Down Expand Up @@ -40,7 +40,7 @@ export const createAllPermissionsView = <
getKeys: () => [...resource.securedPropsPlusExtra, ...resource.childKeys],
calculate: (propName) =>
createLazyRecord<Record<CompatAction, boolean>>({
getKeys: () => keysOf<Record<CompatAction, boolean>>(),
getKeys: () => CompatAction.values,
calculate: (actionInput, propPerms) => {
const action =
actionInput === 'canEdit' &&
Expand Down Expand Up @@ -74,22 +74,26 @@ export const createAllPermissionsOfEdgeView = <
calculate: (action) => privileges.can(action),
});

type CompatAction = AnyAction | `can${PascalCase<AnyAction>}`;
const asLegacyAction = (action: AnyAction) =>
`can${startCase(action)}` as `can${PascalCase<AnyAction>}`;

type CompatAction = EnumType<typeof CompatAction>;
const CompatAction = makeEnum([
...AnyAction,
...[...AnyAction].map(asLegacyAction),
]);

const compatMap = {
forward: {
...mapValues.fromList(
keysOf<Record<CompatAction, boolean>>(),
CompatAction,
(action) =>
(action.startsWith('can')
? action.slice(3).toLowerCase()
: action) as AnyAction,
).asRecord,
},
backward: {
...mapValues.fromList(
keysOf<Record<AnyAction, boolean>>(),
(action) => `can${startCase(action)}` as CompatAction,
).asRecord,
...mapValues.fromList(AnyAction, asLegacyAction).asRecord,
},
};
13 changes: 5 additions & 8 deletions src/components/authorization/policy/executor/policy-dumper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import { Command, Option } from 'clipanion';
import { startCase } from 'lodash';
import { DateTime } from 'luxon';
import fs from 'node:fs/promises';
import { keys as keysOf } from 'ts-transformer-keys';
import { LiteralUnion } from 'type-fest';
import { inspect } from 'util';
import xlsx from 'xlsx';
Expand Down Expand Up @@ -188,16 +187,14 @@ export class PolicyDumper {
role,
resource,
edge: undefined,
...mapValues.fromList(
keysOf<Record<ResourceAction, boolean>>(),
(action) => resolve(action),
).asRecord,
...mapValues.fromList(ResourceAction, (action) => resolve(action))
.asRecord,
},
...(options.props !== false
? ([
[resource.securedPropsPlusExtra, keysOf<Record<PropAction, ''>>()],
[resource.childSingleKeys, keysOf<Record<ChildSingleAction, ''>>()],
[resource.childListKeys, keysOf<Record<ChildListAction, ''>>()],
[resource.securedPropsPlusExtra, PropAction],
[resource.childSingleKeys, ChildSingleAction],
[resource.childListKeys, ChildListAction],
] as const)
: []
).flatMap(([set, actions]) =>
Expand Down
7 changes: 2 additions & 5 deletions src/components/authorization/policy/policy.factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { Injectable, OnModuleInit } from '@nestjs/common';
import { entries, mapEntries, mapValues } from '@seedcompany/common';
import { pick, startCase } from 'lodash';
import { DeepWritable, Writable } from 'ts-essentials';
import { keys as keysOf } from 'ts-transformer-keys';
import { EnhancedResource, many, Role } from '~/common';
import { ResourcesHost } from '~/core/resources';
import { Power } from '../dto';
Expand Down Expand Up @@ -314,13 +313,11 @@ export class PolicyFactory implements OnModuleInit {
continue;
}

const childActions = rel.list
? keysOf<Record<ChildListAction, any>>()
: keysOf<Record<ChildSingleAction, any>>();
const childActions = rel.list ? ChildListAction : ChildSingleAction;

this.mergePermissions(
(childRelations[rel.name] ??= {}),
pick(grants.get(type)!.objectLevel, childActions),
pick(grants.get(type)!.objectLevel, [...childActions]),
);
}
}
Expand Down
20 changes: 13 additions & 7 deletions src/components/engagement/dto/create-engagement.dto.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Field, InputType, ObjectType } from '@nestjs/graphql';
import { entries } from '@seedcompany/common';
import { Type } from 'class-transformer';
import { ValidateNested } from 'class-validator';
import { stripIndent } from 'common-tags';
import { keys as keysOf } from 'ts-transformer-keys';
import { CalendarDate, DateField, ID, IdField } from '~/common';
import { CalendarDate, DataObject, DateField, ID, IdField } from '~/common';
import { ChangesetIdField } from '../../changeset';
import { CreateDefinedFileVersionInput } from '../../file/dto';
import { LanguageMilestone } from '../../language/dto';
Expand All @@ -16,7 +16,7 @@ import { EngagementStatus } from './status.enum';
@InputType({
isAbstract: true,
})
export abstract class CreateEngagement {
export abstract class CreateEngagement extends DataObject {
@IdField()
readonly projectId: ID;

Expand All @@ -37,8 +37,11 @@ export abstract class CreateEngagement {
}

@InputType()
export abstract class CreateLanguageEngagement extends CreateEngagement {
static readonly Props = keysOf<CreateLanguageEngagement>();
export class CreateLanguageEngagement extends CreateEngagement {
// Warning: this only works if not doing inheritance type mapping
static readonly Props = entries(
CreateLanguageEngagement.defaultValue(CreateLanguageEngagement),
).map(([k]) => k);

@IdField()
readonly languageId: ID;
Expand Down Expand Up @@ -81,8 +84,11 @@ export abstract class CreateLanguageEngagement extends CreateEngagement {
}

@InputType()
export abstract class CreateInternshipEngagement extends CreateEngagement {
static readonly Props = keysOf<CreateInternshipEngagement>();
export class CreateInternshipEngagement extends CreateEngagement {
// Warning: this only works if not doing inheritance type mapping
static readonly Props = entries(
CreateInternshipEngagement.defaultValue(CreateInternshipEngagement),
).map(([k]) => k);

@IdField()
readonly internId: ID;
Expand Down
6 changes: 5 additions & 1 deletion src/components/ethno-art/dto/ethno-art.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import {
} from '~/common';
import { e } from '~/core/gel';
import { RegisterResource } from '~/core/resources';
import { Producible } from '../../product/dto/producible.dto';
import {
Producible,
ProducibleTypeEntries,
} from '../../product/dto/producible.dto';

ProducibleTypeEntries.add('EthnoArt');
declare module '../../product/dto/producible.dto' {
interface ProducibleTypeEntries {
EthnoArt: true;
Expand Down
6 changes: 5 additions & 1 deletion src/components/film/dto/film.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ import {
} from '~/common';
import { e } from '~/core/gel';
import { RegisterResource } from '~/core/resources';
import { Producible } from '../../product/dto/producible.dto';
import {
Producible,
ProducibleTypeEntries,
} from '../../product/dto/producible.dto';

ProducibleTypeEntries.add('Film');
declare module '../../product/dto/producible.dto' {
interface ProducibleTypeEntries {
Film: true;
Expand Down
27 changes: 20 additions & 7 deletions src/components/product/dto/producible.dto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { Field, InterfaceType, ObjectType } from '@nestjs/graphql';
import {
Field,
InterfaceType,
ObjectType,
registerEnumType,
} from '@nestjs/graphql';
import { MadeEnum } from '@seedcompany/nest';
import { stripIndent } from 'common-tags';
import { keys as keysOf } from 'ts-transformer-keys';
import {
EnumType,
lazyRef,
makeEnum,
Resource,
SecuredProperty,
Expand Down Expand Up @@ -39,15 +46,21 @@ export abstract class Producible extends Resource {
SetChangeType<'scriptureReferences', readonly ScriptureRangeInput[]>;
}

export type ProducibleType = EnumType<typeof ProducibleType>;
export const ProducibleType = makeEnum({
name: 'ProducibleType',
values: keysOf<ProducibleTypeEntries>(),
});

// Augment this with each implementation of Producible via declaration merging
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface ProducibleTypeEntries {}
export const ProducibleTypeEntries = new Set<string>();

export type ProducibleType = EnumType<typeof ProducibleType>;
export const ProducibleType = lazyRef(
(): MadeEnum<keyof ProducibleTypeEntries> =>
(realProducibleType ??= makeEnum({
values: ProducibleTypeEntries as Iterable<keyof ProducibleTypeEntries>,
})),
);
let realProducibleType: MadeEnum<keyof ProducibleTypeEntries> | undefined;
// Register proxy eagerly to GQL schema
registerEnumType(ProducibleType, { name: 'ProducibleType' });

export type ProducibleRef = UnsecuredDto<Producible> & {
__typename: ProducibleType;
Expand Down
10 changes: 9 additions & 1 deletion src/components/product/dto/product.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,12 @@ import {
SecuredScriptureRangesOverride,
SecuredUnspecifiedScripturePortion,
} from '../../scripture/dto';
import { Producible, ProducibleRef, SecuredProducible } from './producible.dto';
import {
Producible,
ProducibleRef,
ProducibleTypeEntries,
SecuredProducible,
} from './producible.dto';
import { SecuredProductMediums } from './product-medium.enum';
import { SecuredMethodology } from './product-methodology.enum';
import { SecuredProductPurposes } from './product-purpose.enum';
Expand Down Expand Up @@ -261,6 +266,9 @@ export const asProductType =
return product as any;
};

ProducibleTypeEntries.add('DirectScriptureProduct');
ProducibleTypeEntries.add('DerivativeScriptureProduct');
ProducibleTypeEntries.add('OtherProduct');
declare module '../dto/producible.dto' {
interface ProducibleTypeEntries {
DirectScriptureProduct: true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Field, ObjectType } from '@nestjs/graphql';
import { ID, IdField } from '~/common';
import { TransitionType } from '../../../workflow/dto';
import { ProgressReportStatus } from '../../dto';
import { ProgressReportStatus } from '../../dto/progress-report-status.enum';

@ObjectType()
export abstract class ProgressReportWorkflowTransition {
Expand Down
10 changes: 6 additions & 4 deletions src/components/progress-report/workflow/transitions.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { mapValues } from '@seedcompany/common';
import { entries, mapValues } from '@seedcompany/common';
import { EnumType, makeEnum } from '@seedcompany/nest';
import { createHash } from 'crypto';
import { ID, Many, maybeMany, Role } from '~/common';
import { TransitionType as Type } from '../../workflow/dto';
import { ProgressReportStatus as Status } from '../dto';
import { TransitionType as Type } from '../../workflow/dto/workflow-transition.dto';
import { ProgressReportStatus as Status } from '../dto/progress-report-status.enum';
import { ProgressReportWorkflowTransition as PublicTransition } from './dto/workflow-transition.dto';

// This also controls the order shown in the UI.
Expand Down Expand Up @@ -90,7 +91,8 @@ type TransitionInput = Omit<PublicTransition, 'id'> & {
};
};

export type TransitionName = keyof typeof Transitions;
export type TransitionName = EnumType<typeof TransitionName>;
export const TransitionName = makeEnum(entries(Transitions).map(([k]) => k));

export interface InternalTransition extends PublicTransition {
id: ID;
Expand Down
3 changes: 2 additions & 1 deletion src/components/story/dto/story.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@ import {
} from '~/common';
import { e } from '~/core/gel';
import { RegisterResource } from '~/core/resources';
import { Producible } from '../../product/dto';
import { Producible, ProducibleTypeEntries } from '../../product/dto';

ProducibleTypeEntries.add('Story');
declare module '../../product/dto/producible.dto' {
interface ProducibleTypeEntries {
Story: true;
Expand Down
5 changes: 2 additions & 3 deletions src/core/config/config.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ import { Duration, DurationLike } from 'luxon';
import { nanoid } from 'nanoid';
import { Config as Neo4JDriverConfig } from 'neo4j-driver';
import { BehaviorSubject } from 'rxjs';
import { keys as keysOf } from 'ts-transformer-keys';
import { Class, Merge, ReadonlyDeep } from 'type-fest';
import { ID } from '~/common';
import { parseUri } from '../../components/file/bucket/parse-uri';
import { ProgressReportStatus } from '../../components/progress-report/dto/progress-report-status.enum';
import type { TransitionName as ProgressReportTransitionName } from '../../components/progress-report/workflow/transitions';
import { TransitionName as ProgressReportTransitionName } from '../../components/progress-report/workflow/transitions';
import { DefaultTimezoneWrapper } from '../email/templates/formatted-date-time';
import { FrontendUrlWrapper } from '../email/templates/frontend-url';
import type { CookieOptions, CorsOptions, IRequest } from '../http';
Expand Down Expand Up @@ -133,7 +132,7 @@ export const makeConfig = (env: EnvironmentService) =>
notifyExtraEmails: {
forTransitions: env
.map('PROGRESS_REPORT_EMAILS_FOR_TRANSITIONS', {
parseKey: keysOf<Record<ProgressReportTransitionName, ''>>(),
parseKey: ProgressReportTransitionName,
parseValue: csv,
})
.optional({}),
Expand Down
Loading