Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Last active November 3, 2023 04:14
Show Gist options
  • Save LayZeeDK/ab9b2603eb146e3f421a37c0bc78a81e to your computer and use it in GitHub Desktop.
Save LayZeeDK/ab9b2603eb146e3f421a37c0bc78a81e to your computer and use it in GitHub Desktop.
Nx generator wrapping jscodeshift transform: TypeScript private properties to ECMAScript private fields

Nx generator wrapping jscodeshift transform: TypeScript private properties to ECMAScript private fields

This library contains local Nx migration generators. To use them, run

nx generate @myorg/typescript-migrations:<migration-name> <project-name>

For example

nx generate @myorg/typescript-migrations:convert-typescript-private-class-properties-to-ecmascript-private-fields my-lib

License (MIT)

Copyright 2023 Lars Gyrup Brink Nielsen

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

{
"generators": {
"convert-typescript-private-class-properties-to-ecmascript-private-fields": {
"factory": "./src/generators/convert-typescript-private-class-properties-to-ecmascript-private-fields/generator",
"schema": "./src/generators/convert-typescript-private-class-properties-to-ecmascript-private-fields/schema.json",
"description": "Convert class properties with TypeScript's `private` access modifier to ECMAScript `#`-prefixed class properties"
}
}
}
{
"name": "@myorg/typescript-migrations",
"version": "0.0.1",
"type": "commonjs",
"generators": "./generators.json"
}
import {
ProjectConfiguration,
Tree,
formatFiles,
logger,
readProjectConfiguration,
visitNotIgnoredFiles,
} from '@nx/devkit';
import { applyTransform } from 'jscodeshift/src/testUtils';
import { ConvertTypescriptPrivateClassPropertiesToEcmascriptPrivateFieldsGeneratorSchema } from './schema';
import { transformTypescriptPrivateClassPropertiesToEcmascriptPrivateFields } from './transforms/transform-typescript-private-class-properties-to-ecmascript-private-fields';
export async function convertTypescriptPrivateClassPropertiesToEcmascriptPrivateFieldsGenerator(
tree: Tree,
options: ConvertTypescriptPrivateClassPropertiesToEcmascriptPrivateFieldsGeneratorSchema
) {
let project: ProjectConfiguration;
try {
project = readProjectConfiguration(tree, options.project);
} catch (error: unknown) {
throw new Error(
`Failed to read project configuration for "${options.project}": "${
(error as Error).message
}"`
);
}
logger.debug('Applying transform...');
visitNotIgnoredFiles(tree, project.sourceRoot, filePath => {
if (!filePath.endsWith('.ts')) {
return;
}
logger.debug(filePath);
let input: string;
try {
input = tree.read(filePath).toString();
} catch (error: unknown) {
throw new Error(
`Failed to read file "${filePath}": "${(error as Error).message}"`
);
}
const transformOptions = {};
let output: string;
try {
output = applyTransform(
{
default: transformTypescriptPrivateClassPropertiesToEcmascriptPrivateFields,
parser: 'ts',
},
transformOptions,
{ source: input, path: filePath }
);
} catch (error: unknown) {
throw new Error(
`Failed to transform file "${filePath}": "${(error as Error).message}"`
);
}
tree.write(filePath, output);
});
logger.debug('Formatting files after applying transform...');
await formatFiles(tree);
}
export default convertTypescriptPrivateClassPropertiesToEcmascriptPrivateFieldsGenerator;
export interface ConvertTypescriptPrivateClassPropertiesToEcmascriptPrivateFieldsGeneratorSchema {
readonly project: string;
}
{
"$schema": "http://json-schema.org/schema",
"$id": "ConvertTypescriptPrivateClassPropertiesToEcmascriptPrivateFields",
"title": "",
"type": "object",
"properties": {
"project": {
"type": "string",
"description": "",
"$default": {
"$source": "argv",
"index": 0
},
"x-prompt": "What is the name of the project you want to transform?"
}
},
"required": ["project"]
}
import {
ClassMethod,
ClassProperty,
Identifier,
MemberExpression,
Transform,
} from "jscodeshift";
function assertIdentifier(key: {
readonly type: string;
}): asserts key is Identifier {
if (key.type !== "Identifier") {
throw new Error(`Expected Identifier, got ${key.type}`);
}
}
function removePrivateAccessModifier(node: ClassProperty): void {
(node as unknown as ClassMethod).accessibility = null;
}
export const transformTypescriptPrivateClassPropertiesToEcmascriptPrivateFields: Transform = (file, { jscodeshift }) => {
const root = jscodeshift(file.source);
return root
.find(jscodeshift.ClassProperty, {
// A TypeScript `ClassProperty` node has `accessibility` instead of
// `access`
accessibility: "private",
static: false,
} as Omit<ClassProperty, "access"> & Pick<ClassMethod, "accessibility">)
.forEach((classPropertyPath) => {
removePrivateAccessModifier(classPropertyPath.node);
assertIdentifier(classPropertyPath.node.key);
// For example `store`
const from = classPropertyPath.node.key.name;
// For example `#store`
const to = "#" + classPropertyPath.node.key.name;
// For example `store` -> `#store`
classPropertyPath.node.key.name = to;
// For example `this.store` -> `this.#store`
root
.find(MemberExpression, {
object: { type: "ThisExpression" },
property: { name: from },
})
.forEach((thisExpressionPath) => {
assertIdentifier(thisExpressionPath.node.property);
thisExpressionPath.node.property.name = to;
});
})
.toSource();
};
export default transformTypescriptPrivateClassPropertiesToEcmascriptPrivateFields;
export const extensions = "ts";
export const parser = "ts";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment