ts-const-value-transformer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## v0.1.0
4
+
5
+ Initial version.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 jet (ジェット)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,250 @@
1
+ # ts-const-value-transformer
2
+
3
+ Transforms constant variables with actual literals in TypeScript project.
4
+ Provides 'transformer' for TypeScript building ecosystems, 'loader' for webpack, and transform and print APIs.
5
+
6
+ - [Motivation](#motivation)
7
+ - [Usage](#usage)
8
+ - [Using transformer](#using-transformer)
9
+ - [Using webpack loader](#using-webpack-loader)
10
+ - [Transform options](#transform-options)
11
+ - [APIs](#apis)
12
+ - [Additional notes](#additional-notes)
13
+ - [License](#license)
14
+
15
+ ## Motivation
16
+
17
+ Usually, constant variables will be replaced with actual values by [terser](https://terser.org/), [swc](https://swc.rs/) or etc. ([swc example](https://play.swc.rs/?version=1.15.3&code=H4sIAAAAAAAAA9PXVygvyixJVcgvUihILAYykvNTUhUyUotSebl4uZLz84pLFBIVbBWqebkUFBKtFAx1QIwkKwUjMCPZSsGYl6vWGqI0PydVLyc%2FXSNRL1FHIVEvCUQkawIlAet2OZpnAAAA&config=H4sIAAAAAAAAA32US3LbMAyG9zmFR%2Bts20UPkF3PwKFJUKbDh4YAHWsyvnshSrLdGNJOwocfIAEQ32%2BHQ3dG0%2F05fPMn%2Fwy6IJT7P1twTKSvbOnARI2m%2BIG695WecUJOB4Rmus2kI116oKbCX4t7F3JGWN0XW%2FTJu%2FE5oclxKID4ZGMrx6sREuH%2F%2BoWV%2FDUBKvXZfsw5gE47RGlUPhH0UKTAJoegBwR10UWIMp1UF49ZSjHBSmDVUPIg8mQ9%2BZw45yu1oK0y2YKAfAFD%2FgKSjHOxLCFfT7hPwxaOte9bk3%2Bo4aJD1STkhGtrCZ9WiHrKHkm5mqQSznCjBjNcivtT6Z0qQLWkV905%2B7TRk08ArkDQiElHkOI2D8fztKV2u0qfHI8sjQLn%2BZZumaDnoirvnVDZqTJQyEvdLGCrgamyRjrOgjfKh96CAud4VoTQ%2BOXJnKSkNA6QnQC4v9pJUzUDdX%2BFG3x6EDv4g29J8oAtHlHTaZviGI857CSIQKdsdxy4FZS3ceEtcR22eU0WeDTAii4VG3hdAvwAKKvQluXLbPDz4IiqD%2Fn4WBOLw%2B2%2BhKNO%2FeO9z3v4bXHoYra1wWXDT%2F2d9%2FLv7uG0buH1BJ3Hv6uw5bz9A1EN%2Bh8sBgAA)), but if the variables are exported, the variables are not replaced ([swc example](https://play.swc.rs/?version=1.15.3&code=H4sIAAAAAAAAAyXKwQqAIBCE4bvgO8yxQIzqZvQwmy0VRBsqFETvXtZl%2BGD%2BqsIRlsSQgJ3iCy8jY%2BbAWmnlZYsJhB6XVgA51CZjcGg%2BeIdWq7v7U1nZrjIVZMmA7JDHl%2B%2FJ5y4h4aJcPrXX%2FP90AAAA&config=H4sIAAAAAAAAA32US3LbMAyG9zmFR%2Bts20UPkF3PwKFJUKbDh4YAHWsyvnshSrLdGNJOwocfIAEQ32%2BHQ3dG0%2F05fPMn%2Fwy6IJT7P1twTKSvbOnARI2m%2BIG695WecUJOB4Rmus2kI116oKbCX4t7F3JGWN0XW%2FTJu%2FE5oclxKID4ZGMrx6sREuH%2F%2BoWV%2FDUBKvXZfsw5gE47RGlUPhH0UKTAJoegBwR10UWIMp1UF49ZSjHBSmDVUPIg8mQ9%2BZw45yu1oK0y2YKAfAFD%2FgKSjHOxLCFfT7hPwxaOte9bk3%2Bo4aJD1STkhGtrCZ9WiHrKHkm5mqQSznCjBjNcivtT6Z0qQLWkV905%2B7TRk08ArkDQiElHkOI2D8fztKV2u0qfHI8sjQLn%2BZZumaDnoirvnVDZqTJQyEvdLGCrgamyRjrOgjfKh96CAud4VoTQ%2BOXJnKSkNA6QnQC4v9pJUzUDdX%2BFG3x6EDv4g29J8oAtHlHTaZviGI857CSIQKdsdxy4FZS3ceEtcR22eU0WeDTAii4VG3hdAvwAKKvQluXLbPDz4IiqD%2Fn4WBOLw%2B2%2BhKNO%2FeO9z3v4bXHoYra1wWXDT%2F2d9%2FLv7uG0buH1BJ3Hv6uw5bz9A1EN%2Bh8sBgAA)). But if the variables are strictly typed, the variables should be replaced probably safely.
18
+ This package aims to replace those variables/property references/enum values with actual values, to reduce code side (and, perhaps, to increase execution speed).
19
+
20
+ ## Usage
21
+
22
+ First, install with:
23
+
24
+ ```sh
25
+ npm install --save-dev ts-const-value-transformer
26
+ ```
27
+
28
+ ### Using transformer
29
+
30
+ Transformer is a feature for TypeScript build system to convert parsed source code (AST) to another AST.
31
+ TypeScript compiler `tsc` does not accept transformers, but some TypeScript-related ecosystems such as
32
+ [ts-loader](https://www.npmjs.com/package/ts-loader) and [ts-patch](https://www.npmjs.com/package/ts-patch) accept transformers to intercept builds.
33
+
34
+ To use with ts-loader, write webpack configuration as follows:
35
+
36
+ ```js
37
+ import { createTransformer } from 'ts-const-value-transformer';
38
+ // or: const { createTransformer } = require('ts-const-value-transformer');
39
+ // (you can use 'require' for ES modules starting from Node.js v20.19.0; see https://nodejs.org/api/modules.html#loading-ecmascript-modules-using-require)
40
+
41
+ const yourWebpackConfiguration = {
42
+ module: {
43
+ rules: [
44
+ {
45
+ test: /\.ts$/,
46
+ use: [
47
+ {
48
+ loader: 'ts-loader',
49
+ options: {
50
+ getCustomTransformers: (program) => ({
51
+ before: [
52
+ createTransformer(program, {
53
+ options: {
54
+ /* ts-const-value-transformer options (see below) */
55
+ },
56
+ }),
57
+ ],
58
+ }),
59
+ // ...other configurations
60
+ },
61
+ },
62
+ ],
63
+ },
64
+ ],
65
+ },
66
+ // ...other configurations
67
+ };
68
+ ```
69
+
70
+ or:
71
+
72
+ ```js
73
+ const yourWebpackConfiguration = {
74
+ module: {
75
+ rules: [
76
+ {
77
+ test: /\.ts$/,
78
+ use: [
79
+ {
80
+ loader: 'ts-loader',
81
+ options: {
82
+ // If you specify only one transformer, you can use 'ts-const-value-transformer/getCustomTransformers' module
83
+ getCustomTransformers:
84
+ 'ts-const-value-transformer/getCustomTransformers',
85
+ // ...other configurations
86
+ },
87
+ },
88
+ ],
89
+ },
90
+ ],
91
+ },
92
+ // ...other configurations
93
+ };
94
+ ```
95
+
96
+ To use with ts-patch, write tsconfig.json as follows:
97
+
98
+ ```jsonc
99
+ "compilerOptions": {
100
+ // ...
101
+ "plugins": [
102
+ { "transform": "ts-const-value-transformer", "options": { /* ts-const-value-transformer options (see below) */ } }
103
+ ]
104
+ }
105
+ ```
106
+
107
+ ### Using webpack loader
108
+
109
+ You can use webpack loader for transformation. If you use loaders to transpile TS files other than ts-loader, `ts-const-value-transformer/loader` is a choice.
110
+ Note that this may increase the build time because of parsing processes.
111
+
112
+ > If you are using ts-loader, you should use the transformer described above for performance reason.
113
+
114
+ ```js
115
+ const yourWebpackConfiguration = {
116
+ module: {
117
+ rules: [
118
+ {
119
+ test: /\.ts$/,
120
+ use: [
121
+ {
122
+ loader: 'babel-loader',
123
+ options: {
124
+ presets: ['@babel/preset-typescript'],
125
+ },
126
+ },
127
+ {
128
+ loader: 'ts-const-value-transformer/loader',
129
+ options; {
130
+ project: 'tsconfig.json', // your tsconfig.json
131
+ // typescript: 'typescript', // if you are using another 'typescript' package, you can specify the module name here
132
+ // ... other options from `TransformOptions` fields
133
+ // hoistProperty: false,
134
+ // ...
135
+ }
136
+ },
137
+ ],
138
+ },
139
+ ],
140
+ },
141
+ // ...other configurations
142
+ };
143
+ ```
144
+
145
+ ### Transform options
146
+
147
+ ```ts
148
+ export interface TransformOptions {
149
+ /** `typescript` namespace object */
150
+ ts?: typeof ts;
151
+ /** Hoist property expressions (`x.prop`) which the value is constant. Default is true, but if the property getter has side effects (not recommended), set false explicitly. */
152
+ hoistProperty?: boolean | undefined;
153
+ /** Hoist function calls which the return value is constant. Default is false because function calls may have side effects. */
154
+ unsafeHoistFunctionCall?: boolean | undefined;
155
+ /** Hoist expressions with `as XXX`. Default is false because the base (non-`as`) value may be non-constant. */
156
+ unsafeHoistAsExpresion?: boolean | undefined;
157
+ }
158
+ ```
159
+
160
+ Note that you must pass `options` field to `createTransformer` function or `"plugins"` specifier.
161
+
162
+ ### APIs
163
+
164
+ ```ts
165
+ import {
166
+ createTransformer,
167
+ printSource,
168
+ printSourceWithMap,
169
+ transformSource,
170
+ version,
171
+ type TransformOptions,
172
+ } from 'ts-const-value-transformer';
173
+ ```
174
+
175
+ #### createTransformer: (program: ts.Program, config?: { options?: TransformOptions }, extras?: { ts?: typeof ts }) => ts.TransformerFactory<ts.SourceFile>
176
+
177
+ Used with TypeScript API or ts-loader.
178
+
179
+ Call example:
180
+
181
+ ```js
182
+ import * as path from 'path';
183
+ import * as ts from 'typescript';
184
+ import { createTransformer } from 'ts-const-value-transformer';
185
+
186
+ const PROJECT_DIR = path.resolve('.');
187
+
188
+ // Load tsconfig.json file
189
+ const configFile = ts.readJsonConfigFile(
190
+ path.resolve(PROJECT_DIR, 'tsconfig.json'),
191
+ ts.sys.readFile
192
+ );
193
+ const config = ts.parseJsonSourceFileConfigFileContent(
194
+ configFile,
195
+ ts.sys,
196
+ PROJECT_DIR
197
+ );
198
+
199
+ // Initialize the program
200
+ const program = ts.createProgram({
201
+ options: config.options,
202
+ rootNames: config.fileNames,
203
+ });
204
+
205
+ // Load the source file to transform
206
+ const fileName = path.resolve(PROJECT_DIR, 'index.mts');
207
+ const sourceFile = program.getSourceFile(fileName)!;
208
+
209
+ // Do transform
210
+ const transformer = createTransformer(program);
211
+ const result = ts.transform(
212
+ sourceFile,
213
+ [transformer],
214
+ program.getCompilerOptions()
215
+ );
216
+ const transformedSource = result.transformed[0]!;
217
+ // You can emit the transformed code by using `printSource` (see below):
218
+ // console.log(printSource(transformedSource));
219
+ ```
220
+
221
+ #### printSource: (sourceFile: ts.SourceFile) => string
222
+
223
+ Prints (generates) source code from `SourceFile`. The source file must be one generated by `transformSource` or existing in the TS project (available with `getSourceFile()` in `ts.Program`).
224
+
225
+ #### printSourceWithMap: (sourceFile: ts.SourceFile, originalSourceName: string, startOfSourceMap?: RawSourceMap) => [string, RawSourceMap]
226
+
227
+ Prints (generates) source code from `SourceFile`, along with raw source-map data. The source file must be one generated by `transformSource` or existing in the TS project (available with `getSourceFile()` in `ts.Program`).
228
+
229
+ - `originalSourceName` would be the file name of `sourceFile`, but you can specify another name.
230
+ - `startOfSourceMap` is a base source map (if original source file is a generated-content) if available.
231
+
232
+ #### transformSource: (sourceFile: ts.SourceFile, program: ts.Program, context: ts.TransformationContext, options?: TransformOptions) => ts.SourceFile
233
+
234
+ Transforms the source file with TypeScript project. You don't need to call this function directly; use `createTransformer` instead.
235
+
236
+ #### version: string
237
+
238
+ The version string of this package.
239
+
240
+ #### type TransformOptions
241
+
242
+ See [Transform options](#transform-options).
243
+
244
+ ## Additional notes
245
+
246
+ I think there should be more optimization methods by using strictly-typed information, like other programming languages.
247
+
248
+ ## License
249
+
250
+ [MIT License](./LICENSE)
@@ -0,0 +1,9 @@
1
+ import type * as ts from 'typescript';
2
+ import { type TransformOptions } from './transform.mjs';
3
+ interface Config {
4
+ options?: TransformOptions;
5
+ }
6
+ export default function createTransformer(program: ts.Program, config?: Config, extras?: {
7
+ ts?: typeof ts;
8
+ }): ts.TransformerFactory<ts.SourceFile>;
9
+ export {};
@@ -0,0 +1,15 @@
1
+ import { transformSource } from './transform.mjs';
2
+ export default function createTransformer(program,
3
+ // for ttypescript and ts-patch
4
+ config,
5
+ // for ts-patch
6
+ extras) {
7
+ return (context) => {
8
+ return (sourceFile) => {
9
+ return transformSource(sourceFile, program, context, {
10
+ ...config?.options,
11
+ ...(extras?.ts && { ts: extras?.ts }),
12
+ });
13
+ };
14
+ };
15
+ }
@@ -0,0 +1,6 @@
1
+ import type * as ts from 'typescript';
2
+ export default function getCustomTransformers(program: ts.Program, _getProgram: () => ts.Program): {
3
+ before?: Array<ts.TransformerFactory<ts.SourceFile>>;
4
+ after?: Array<ts.TransformerFactory<ts.SourceFile>>;
5
+ afterDeclarations?: Array<ts.TransformerFactory<ts.SourceFile>>;
6
+ };
@@ -0,0 +1,7 @@
1
+ // for ts-loader
2
+ import createTransformer from './createTransformer.mjs';
3
+ export default function getCustomTransformers(program, _getProgram) {
4
+ return { before: [createTransformer(program)] };
5
+ }
6
+
7
+ export { getCustomTransformers as 'module.exports' };
@@ -0,0 +1,4 @@
1
+ import createTransformer from './createTransformer.mjs';
2
+ import version from './version.mjs';
3
+ export { printSource, printSourceWithMap, transformSource, type TransformOptions, } from './transform.mjs';
4
+ export { createTransformer, version };
package/dist/index.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import createTransformer from './createTransformer.mjs';
2
+ import version from './version.mjs';
3
+ export { printSource, printSourceWithMap, transformSource, } from './transform.mjs';
4
+ export { createTransformer, version };
@@ -0,0 +1,9 @@
1
+ import type * as tsNamespace from 'typescript';
2
+ import type * as webpack from 'webpack';
3
+ import { type TransformOptions } from './transform.mjs';
4
+ export interface TsConstValueTransformerLoaderOptions extends TransformOptions {
5
+ project?: string;
6
+ typescript?: string | typeof tsNamespace;
7
+ }
8
+ declare const loader: webpack.LoaderDefinitionFunction<TsConstValueTransformerLoaderOptions | undefined>;
9
+ export default loader;
@@ -0,0 +1,78 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import createTransformer from './createTransformer.mjs';
4
+ import { printSourceWithMap } from './transform.mjs';
5
+ const programMap = new Map();
6
+ const loader = function (content, sourceMap) {
7
+ this.async();
8
+ void (async () => {
9
+ try {
10
+ const options = this.getOptions() || {};
11
+ let ts;
12
+ if (options.typescript != null) {
13
+ if (typeof options.typescript === 'string') {
14
+ ts = (await import(options.typescript));
15
+ }
16
+ else {
17
+ ts = options.typescript;
18
+ }
19
+ }
20
+ else if (options.ts != null) {
21
+ ts = options.ts;
22
+ }
23
+ else {
24
+ ts = await import('typescript');
25
+ }
26
+ const project = options.project ?? 'tsconfig.json';
27
+ let program = programMap.get(project);
28
+ if (!program) {
29
+ const getCurrentDirectory = () => path.dirname(this.resourcePath);
30
+ const config = ts.getParsedCommandLineOfConfigFile(project, void 0, {
31
+ fileExists: fs.existsSync,
32
+ getCurrentDirectory,
33
+ // eslint-disable-next-line @typescript-eslint/unbound-method
34
+ readDirectory: ts.sys.readDirectory,
35
+ readFile: (file) => fs.readFileSync(path.isAbsolute(file)
36
+ ? file
37
+ : path.join(getCurrentDirectory(), file), 'utf-8'),
38
+ useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
39
+ onUnRecoverableConfigFileDiagnostic: (diag) => {
40
+ throw new Error(ts.formatDiagnostics([diag], {
41
+ getCanonicalFileName: (f) => f,
42
+ getCurrentDirectory,
43
+ getNewLine: () => '\n',
44
+ }));
45
+ },
46
+ });
47
+ if (!config) {
48
+ throw new Error(`[ts-const-value-transformer-loader] Unable to load tsconfig file (effective name = '${project}')`);
49
+ }
50
+ program = ts.createProgram({
51
+ options: config.options,
52
+ rootNames: config.fileNames,
53
+ });
54
+ programMap.set(project, program);
55
+ }
56
+ const sourceFile = program.getSourceFile(this.resource);
57
+ if (!sourceFile) {
58
+ throw new Error(`'${this.resource}' is not in the TypeScript project.`);
59
+ }
60
+ sourceFile.update(content, {
61
+ span: { start: 0, length: sourceFile.end },
62
+ newLength: content.length,
63
+ });
64
+ const transformer = createTransformer(program, {
65
+ options: { ...options, ts },
66
+ });
67
+ const result = ts.transform(sourceFile, [transformer], program.getCompilerOptions());
68
+ const printed = printSourceWithMap(result.transformed[0], this.resource,
69
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
70
+ typeof sourceMap === 'string' ? JSON.parse(sourceMap) : sourceMap);
71
+ this.callback(null, printed[0], printed[1]);
72
+ }
73
+ catch (e) {
74
+ this.callback(e);
75
+ }
76
+ })();
77
+ };
78
+ export default loader;
@@ -0,0 +1,15 @@
1
+ import * as sourceMap from 'source-map';
2
+ import * as ts from 'typescript';
3
+ export interface TransformOptions {
4
+ /** `typescript` namespace object */
5
+ ts?: typeof ts;
6
+ /** Hoist property expressions (`x.prop`) which the value is constant. Default is true, but if the property getter has side effects (not recommended), set false explicitly. */
7
+ hoistProperty?: boolean | undefined;
8
+ /** Hoist function calls which the return value is constant. Default is false because function calls may have side effects. */
9
+ unsafeHoistFunctionCall?: boolean | undefined;
10
+ /** Hoist expressions with `as XXX`. Default is false because the base (non-`as`) value may be non-constant. */
11
+ unsafeHoistAsExpresion?: boolean | undefined;
12
+ }
13
+ export declare function transformSource(sourceFile: ts.SourceFile, program: ts.Program, context: ts.TransformationContext, options?: TransformOptions): ts.SourceFile;
14
+ export declare function printSource(sourceFile: ts.SourceFile): string;
15
+ export declare function printSourceWithMap(sourceFile: ts.SourceFile, originalSourceName: string, startOfSourceMap?: sourceMap.RawSourceMap): [string, sourceMap.RawSourceMap];
@@ -0,0 +1,267 @@
1
+ import * as sourceMap from 'source-map';
2
+ import * as ts from 'typescript';
3
+ const SYMBOL_ORIGINAL_NODE = Symbol('originalNode');
4
+ function assignDefaultValues(options) {
5
+ return {
6
+ ts,
7
+ hoistProperty: true,
8
+ unsafeHoistAsExpresion: false,
9
+ unsafeHoistFunctionCall: false,
10
+ ...options,
11
+ };
12
+ }
13
+ ////////////////////////////////////////////////////////////////////////////////
14
+ export function transformSource(sourceFile, program, context, options) {
15
+ return visitNodeChildren(sourceFile, sourceFile, program, context, assignDefaultValues(options));
16
+ }
17
+ function visitNodeChildren(node, sourceFile, program, context, options) {
18
+ const newNode = visitNodeAndReplaceIfNeeded(node, sourceFile, program, context, options);
19
+ if (newNode[SYMBOL_ORIGINAL_NODE]) {
20
+ return newNode;
21
+ }
22
+ return ts.visitEachChild(newNode, (node) => visitNodeChildren(node, sourceFile, program, context, options), context);
23
+ }
24
+ function visitNodeAndReplaceIfNeeded(node, sourceFile, program, context, options) {
25
+ const ts = options.ts;
26
+ if (!ts.isExpression(node) && !ts.isIdentifier(node)) {
27
+ return node;
28
+ }
29
+ if (ts.isLiteralExpression(node) ||
30
+ ts.isObjectLiteralExpression(node) ||
31
+ ts.isPrefixUnaryExpression(node) ||
32
+ ts.isPostfixUnaryExpression(node) ||
33
+ ts.isBinaryExpression(node) ||
34
+ ts.isConditionalExpression(node) ||
35
+ ts.isVoidExpression(node) ||
36
+ ts.isSpreadElement(node) ||
37
+ (!options.hoistProperty &&
38
+ ts.isPropertyAccessExpression(node) &&
39
+ !isEnumAccess(node, program, ts)) ||
40
+ (!options.unsafeHoistFunctionCall && ts.isCallLikeExpression(node)) ||
41
+ node.kind === ts.SyntaxKind.TrueKeyword ||
42
+ node.kind === ts.SyntaxKind.FalseKeyword ||
43
+ node.kind === ts.SyntaxKind.NullKeyword) {
44
+ return node;
45
+ }
46
+ if (ts.isIdentifier(node)) {
47
+ if (
48
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
49
+ !node.parent ||
50
+ (!ts.isExpression(node.parent) &&
51
+ (!('initializer' in node.parent) ||
52
+ node !== node.parent.initializer)) ||
53
+ (!options.hoistProperty &&
54
+ ts.isPropertyAccessExpression(node.parent) &&
55
+ node === node.parent.name)) {
56
+ return node;
57
+ }
58
+ }
59
+ if (!options.unsafeHoistAsExpresion &&
60
+ (hasAsExpression(node, context, ts) ||
61
+ hasParentAsExpression(node.parent, context, ts))) {
62
+ return node;
63
+ }
64
+ try {
65
+ const typeChecker = program.getTypeChecker();
66
+ const type = typeChecker.getTypeAtLocation(node);
67
+ const flags = type.getFlags();
68
+ let newNode;
69
+ if (type.isStringLiteral()) {
70
+ newNode = context.factory.createStringLiteral(type.value);
71
+ }
72
+ else if (type.isNumberLiteral()) {
73
+ if (type.value < 0) {
74
+ newNode = context.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, context.factory.createNumericLiteral(-type.value));
75
+ }
76
+ else {
77
+ newNode = context.factory.createNumericLiteral(type.value);
78
+ }
79
+ }
80
+ else if (flags & ts.TypeFlags.BigIntLiteral) {
81
+ newNode = context.factory.createBigIntLiteral(typeChecker.typeToString(type));
82
+ }
83
+ else if (flags & ts.TypeFlags.BooleanLiteral) {
84
+ const text = typeChecker.typeToString(type);
85
+ newNode =
86
+ text === 'true'
87
+ ? context.factory.createTrue()
88
+ : context.factory.createFalse();
89
+ }
90
+ else if (flags & ts.TypeFlags.Null) {
91
+ newNode = context.factory.createNull();
92
+ }
93
+ else if (flags & ts.TypeFlags.Undefined) {
94
+ newNode = context.factory.createVoidZero();
95
+ }
96
+ else {
97
+ return node;
98
+ }
99
+ const result = ts.addSyntheticTrailingComment(newNode, ts.SyntaxKind.MultiLineCommentTrivia, ` ${node.getText(sourceFile)} `);
100
+ ts.setTextRange(result, node);
101
+ result[SYMBOL_ORIGINAL_NODE] = node;
102
+ return result;
103
+ }
104
+ catch {
105
+ return node;
106
+ }
107
+ }
108
+ function isEnumAccess(node, program, tsInstance) {
109
+ const ts = tsInstance;
110
+ const typeChecker = program.getTypeChecker();
111
+ const type = typeChecker.getTypeAtLocation(node);
112
+ return (type.getFlags() & ts.TypeFlags.EnumLiteral) !== 0;
113
+ }
114
+ function isAsConstExpression(node) {
115
+ return node.type.getText() === 'const';
116
+ }
117
+ function hasAsExpression(node, context, tsInstance) {
118
+ const ts = tsInstance;
119
+ // including 'as const'
120
+ if (ts.isAsExpression(node)) {
121
+ return true;
122
+ }
123
+ let found = false;
124
+ ts.visitEachChild(node, (node) => {
125
+ if (!found) {
126
+ found = hasAsExpression(node, context, ts);
127
+ }
128
+ return node;
129
+ }, context);
130
+ return found;
131
+ }
132
+ function hasParentAsExpression(node, context, tsInstance) {
133
+ const ts = tsInstance;
134
+ if (node == null) {
135
+ return false;
136
+ }
137
+ // excluding 'as const'
138
+ if (ts.isAsExpression(node) && !isAsConstExpression(node)) {
139
+ return true;
140
+ }
141
+ if (ts.isPropertyAccessExpression(node)) {
142
+ if (hasAsExpression(node.expression, context, ts)) {
143
+ return true;
144
+ }
145
+ }
146
+ return hasParentAsExpression(node.parent, context, ts);
147
+ }
148
+ ////////////////////////////////////////////////////////////////////////////////
149
+ export function printSource(sourceFile) {
150
+ return printSourceImpl(sourceFile)[0];
151
+ }
152
+ export function printSourceWithMap(sourceFile, originalSourceName, startOfSourceMap) {
153
+ const generator = new sourceMap.SourceMapGenerator(startOfSourceMap);
154
+ generator.setSourceContent(originalSourceName, sourceFile.getFullText());
155
+ return printSourceImpl(sourceFile, originalSourceName, generator);
156
+ }
157
+ function positionToLineAndColumn(sourceFile, pos, generatedDiff) {
158
+ let line = 0;
159
+ let lastLinePos = 0;
160
+ for (const linePos of sourceFile.getLineStarts()) {
161
+ if (pos < linePos) {
162
+ break;
163
+ }
164
+ lastLinePos = linePos;
165
+ ++line;
166
+ }
167
+ return { line, column: pos - lastLinePos + generatedDiff };
168
+ }
169
+ function printSourceImpl(sourceFile, originalSourceName, mapGenerator) {
170
+ const printer = ts.createPrinter({ removeComments: true });
171
+ const r = printNode(printer, sourceFile.getFullText(), sourceFile, sourceFile, { pos: 0, diff: 0, lastLine: 0 }, originalSourceName, mapGenerator);
172
+ return [r, mapGenerator?.toJSON()];
173
+ }
174
+ function printNode(printer, baseSource, sourceFile, node, posContext, originalSourceName, mapGenerator) {
175
+ const originalNode = node[SYMBOL_ORIGINAL_NODE];
176
+ if (originalNode) {
177
+ let result = printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);
178
+ const comments = ts.getSyntheticTrailingComments(node);
179
+ if (comments) {
180
+ for (const comment of comments) {
181
+ result += ` /*${comment.text}*/`;
182
+ }
183
+ }
184
+ const old = originalNode.getText(sourceFile);
185
+ const oldFull = baseSource.substring(originalNode.pos, originalNode.end);
186
+ const i = oldFull.lastIndexOf(old);
187
+ const leadingUnchanged = i < 0 ? 0 : i;
188
+ const newText = i < 0
189
+ ? result
190
+ : oldFull.substring(0, i) + result + oldFull.substring(i + old.length);
191
+ if (mapGenerator) {
192
+ if (posContext.pos < node.pos) {
193
+ addMappingForCurrent();
194
+ }
195
+ posContext.pos = node.pos;
196
+ if (leadingUnchanged > 0) {
197
+ addMappingForCurrent();
198
+ }
199
+ posContext.pos = node.pos + leadingUnchanged;
200
+ addMappingForCurrent(old);
201
+ }
202
+ posContext.diff += result.length - old.length;
203
+ posContext.pos += old.length;
204
+ addMappingForCurrent();
205
+ posContext.pos = node.end;
206
+ addMappingForCurrent();
207
+ return newText;
208
+ }
209
+ let output = '';
210
+ let headPrinted = false;
211
+ let lastChildPos = 0;
212
+ ts.visitEachChild(node, (child) => {
213
+ if (!headPrinted) {
214
+ headPrinted = true;
215
+ if (child.pos > node.pos) {
216
+ const text = baseSource.substring(node.pos, child.pos);
217
+ output += text;
218
+ addMappingForCurrent();
219
+ posContext.pos = child.pos;
220
+ }
221
+ }
222
+ else if (child.pos > lastChildPos) {
223
+ const text = baseSource.substring(lastChildPos, child.pos);
224
+ output += text;
225
+ addMappingForCurrent();
226
+ posContext.pos = child.pos;
227
+ }
228
+ output += printNode(printer, baseSource, sourceFile, child, posContext, originalSourceName, mapGenerator);
229
+ lastChildPos = child.end;
230
+ return child;
231
+ }, void 0);
232
+ if (!headPrinted) {
233
+ output = baseSource.substring(node.pos, node.end);
234
+ addMappingForCurrent();
235
+ posContext.pos = node.end;
236
+ }
237
+ else if (lastChildPos < node.end) {
238
+ const text = baseSource.substring(lastChildPos, node.end);
239
+ output += text;
240
+ addMappingForCurrent();
241
+ posContext.pos = node.end;
242
+ }
243
+ addMappingForCurrent();
244
+ return output;
245
+ function addMappingForCurrent(name) {
246
+ const original = positionToLineAndColumn(sourceFile, posContext.pos, 0);
247
+ if (original.line !== posContext.lastLine) {
248
+ posContext.diff = 0;
249
+ posContext.lastLine = original.line;
250
+ if (mapGenerator && original.column > 0) {
251
+ mapGenerator.addMapping({
252
+ original: { line: original.line, column: 0 },
253
+ generated: { line: original.line, column: 0 },
254
+ source: originalSourceName,
255
+ });
256
+ }
257
+ }
258
+ if (mapGenerator) {
259
+ mapGenerator.addMapping({
260
+ original,
261
+ generated: positionToLineAndColumn(sourceFile, posContext.pos, posContext.diff),
262
+ source: originalSourceName,
263
+ name,
264
+ });
265
+ }
266
+ }
267
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: "0.1.0";
2
+ export default _default;
@@ -0,0 +1 @@
1
+ export default '0.1.0';
package/package.json ADDED
@@ -0,0 +1,99 @@
1
+ {
2
+ "name": "ts-const-value-transformer",
3
+ "version": "0.1.0",
4
+ "engines": {
5
+ "node": ">=20.19.3"
6
+ },
7
+ "description": "Transforms constant variables with actual literals in TypeScript project.",
8
+ "type": "module",
9
+ "module": "./dist/index.mjs",
10
+ "exports": {
11
+ ".": {
12
+ "default": "./dist/index.mjs",
13
+ "import": "./dist/index.mjs",
14
+ "types": "./dist/index.d.mts"
15
+ },
16
+ "./getCustomTransformers": {
17
+ "default": "./dist/getCustomTransformers.mjs",
18
+ "import": "./dist/getCustomTransformers.mjs",
19
+ "types": "./dist/getCustomTransformers.d.mts"
20
+ },
21
+ "./getCustomTransformers.mjs": {
22
+ "default": "./dist/getCustomTransformers.mjs",
23
+ "import": "./dist/getCustomTransformers.mjs",
24
+ "types": "./dist/getCustomTransformers.d.mts"
25
+ },
26
+ "./loader": {
27
+ "default": "./dist/loader.mjs",
28
+ "import": "./dist/loader.mjs",
29
+ "types": "./dist/loader.d.mts"
30
+ },
31
+ "./loader.mjs": {
32
+ "default": "./dist/loader.mjs",
33
+ "import": "./dist/loader.mjs",
34
+ "types": "./dist/loader.d.mts"
35
+ }
36
+ },
37
+ "types": "./dist/index.d.mts",
38
+ "author": "jet (ジェット)",
39
+ "license": "MIT",
40
+ "homepage": "https://github.com/jet2jet/ts-const-value-transformer",
41
+ "keywords": [
42
+ "typescript",
43
+ "transformer",
44
+ "optimize",
45
+ "optimizer",
46
+ "optimization",
47
+ "webpack-loader"
48
+ ],
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/jet2jet/ts-const-value-transformer.git"
52
+ },
53
+ "funding": {
54
+ "type": "github",
55
+ "url": "https://github.com/sponsors/jet2jet"
56
+ },
57
+ "scripts": {
58
+ "build": "npm run build:esm",
59
+ "build:esm": "tsc -p ./tsconfig.app.json && npm run build:esm:addModuleExports",
60
+ "build:esm:addModuleExports": "node ./tools/addModuleExports.mjs ./dist/getCustomTransformers.mjs",
61
+ "lint": "npm run lint:eslint && npm run lint:prettier",
62
+ "lint:eslint": "eslint -c eslint.config.mjs --ext .mjs,.mts .",
63
+ "lint:eslint:fix": "eslint -c eslint.config.mjs --fix --ext .mjs,.mts .",
64
+ "lint:fix": "npm run lint:eslint:fix && npm run lint:prettier:fix",
65
+ "lint:prettier": "prettier --config ./.prettierrc.yml --check \"**/*.{js,jsx,ts,tsx,yml,json,md}\"",
66
+ "lint:prettier:fix": "prettier --config ./.prettierrc.yml --write \"**/*.{js,jsx,ts,tsx,yml,json,md}\"",
67
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config ./jest.config.mjs",
68
+ "test:update": "node --experimental-vm-modules node_modules/jest/bin/jest.js --config ./jest.config.mjs -u",
69
+ "typecheck": "tsc --project tsconfig.json --noEmit && echo \"Done\".",
70
+ "version": "node ./tools/updateVersion.mjs ./src/main/version.mts && git add -A ./src/main/version.mts"
71
+ },
72
+ "devDependencies": {
73
+ "@types/jest": "^30.0.0",
74
+ "@types/node": "~20.19.22",
75
+ "@typescript-eslint/eslint-plugin": "^8.48.0",
76
+ "@typescript-eslint/parser": "^8.48.0",
77
+ "eslint": "^9.39.1",
78
+ "eslint-config-prettier": "^10.1.8",
79
+ "eslint-plugin-import-x": "^4.16.1",
80
+ "eslint-plugin-n": "^17.23.1",
81
+ "eslint-plugin-promise": "^7.2.1",
82
+ "jest": "^30.2.0",
83
+ "memfs": "^4.51.0",
84
+ "neostandard": "^0.12.2",
85
+ "prettier": "^3.6.2",
86
+ "ts-jest": "^29.4.5",
87
+ "ts-loader": "^9.5.4",
88
+ "ts-patch": "^3.3.0",
89
+ "tslib": "^2.8.1",
90
+ "typescript": "~5.5.4",
91
+ "webpack": "^5.103.0"
92
+ },
93
+ "peerDependencies": {
94
+ "typescript": ">=5.5"
95
+ },
96
+ "dependencies": {
97
+ "source-map": "^0.7.6"
98
+ }
99
+ }