-
Notifications
You must be signed in to change notification settings - Fork 85
[FSSDK-12933] Refactor message generator to use TS compiler API #1170
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
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| /** | ||
| * Copyright 2026, Optimizely | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| const ts = require('typescript'); | ||
| const fs = require('fs'); | ||
| const path = require('path'); | ||
|
|
||
| function extractMessages(filePath) { | ||
| const source = fs.readFileSync(filePath, 'utf-8'); | ||
| const sourceFile = ts.createSourceFile( | ||
| filePath, | ||
| source, | ||
| ts.ScriptTarget.Latest, | ||
| true, | ||
| ); | ||
|
|
||
| const exports = []; | ||
|
|
||
| for (const statement of sourceFile.statements) { | ||
| if (!ts.isVariableStatement(statement)) continue; | ||
|
|
||
| const hasExport = statement.modifiers?.some( | ||
| (m) => m.kind === ts.SyntaxKind.ExportKeyword, | ||
| ); | ||
| if (!hasExport) continue; | ||
|
|
||
| for (const decl of statement.declarationList.declarations) { | ||
| const name = decl.name.getText(sourceFile); | ||
| if (name === 'messages' || name === '__platforms') continue; | ||
| if (!decl.initializer || !ts.isStringLiteral(decl.initializer)) continue; | ||
|
|
||
| exports.push({ name, value: decl.initializer.text }); | ||
| } | ||
| } | ||
|
|
||
| return exports; | ||
| } | ||
|
|
||
| function buildOutputAst(exports) { | ||
| const { factory } = ts; | ||
| const statements = []; | ||
|
|
||
| exports.forEach((exp, i) => { | ||
| statements.push( | ||
| factory.createVariableStatement( | ||
| [factory.createModifier(ts.SyntaxKind.ExportKeyword)], | ||
| factory.createVariableDeclarationList( | ||
| [factory.createVariableDeclaration(exp.name, undefined, undefined, factory.createStringLiteral(String(i)))], | ||
| ts.NodeFlags.Const, | ||
| ), | ||
| ), | ||
| ); | ||
| }); | ||
|
|
||
| statements.push( | ||
| factory.createVariableStatement( | ||
| [factory.createModifier(ts.SyntaxKind.ExportKeyword)], | ||
| factory.createVariableDeclarationList( | ||
| [ | ||
| factory.createVariableDeclaration( | ||
| 'messages', | ||
| undefined, | ||
| undefined, | ||
| factory.createArrayLiteralExpression( | ||
| exports.map((exp) => factory.createStringLiteral(exp.value)), | ||
| true, | ||
| ), | ||
| ), | ||
| ], | ||
| ts.NodeFlags.Const, | ||
| ), | ||
| ), | ||
| ); | ||
|
|
||
| return factory.createSourceFile(statements, factory.createToken(ts.SyntaxKind.EndOfFileToken), ts.NodeFlags.None); | ||
| } | ||
|
|
||
| function generate(filePath) { | ||
| const absPath = path.resolve(filePath); | ||
| const parsed = path.parse(absPath); | ||
| const genPath = path.join(parsed.dir, `${parsed.name}.gen${parsed.ext}`); | ||
|
|
||
| console.log('generating messages for:', absPath); | ||
|
|
||
| const exports = extractMessages(absPath); | ||
| const outputAst = buildOutputAst(exports); | ||
|
|
||
| const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed }); | ||
| const output = printer.printFile(outputAst); | ||
|
|
||
| fs.writeFileSync(genPath, output, 'utf-8'); | ||
| console.log('generated file path:', genPath); | ||
| } | ||
|
|
||
| const files = process.argv.slice(2); | ||
|
|
||
| if (files.length === 0) { | ||
| console.error('Usage: generate-messages.js <file1.ts> [file2.ts] ...'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| for (const file of files) { | ||
| generate(file); | ||
| } | ||
|
|
||
| console.log('successfully generated messages'); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| const assert = require('node:assert/strict'); | ||
| const { execFileSync } = require('node:child_process'); | ||
| const fs = require('node:fs'); | ||
| const os = require('node:os'); | ||
| const path = require('node:path'); | ||
| const ts = require('typescript'); | ||
|
|
||
| const SCRIPT = path.resolve(__dirname, 'generate-messages.js'); | ||
|
|
||
| const FILE1_EXPECTED = [ | ||
| { name: 'HELLO', value: 'Hello, %s!' }, | ||
| { name: 'GOODBYE', value: 'Goodbye, %s!' }, | ||
| { name: 'WARNING', value: 'Warning: %s' }, | ||
| ]; | ||
|
|
||
| const FILE2_EXPECTED = [ | ||
| { name: 'ERR_NOT_FOUND', value: 'Resource %s not found' }, | ||
| { name: 'ERR_TIMEOUT', value: 'Request timed out after %s ms' }, | ||
| { name: 'ERR_INVALID', value: 'Invalid input: %s' }, | ||
| { name: 'ERR_PERMISSION', value: 'Permission denied for %s' }, | ||
| ]; | ||
|
|
||
| function buildFileContent(expected, { includeMessages = true, includePlatforms = false } = {}) { | ||
| let content = expected.map((e) => `export const ${e.name} = '${e.value}';`).join('\n'); | ||
| if (includeMessages) content += `\n\nexport const messages: string[] = [];`; | ||
| if (includePlatforms) content += `\nexport const __platforms: string[] = ['__universal__'];`; | ||
| return content; | ||
| } | ||
|
|
||
| function compileAndLoad(tsPath) { | ||
| const source = fs.readFileSync(tsPath, 'utf-8'); | ||
| const { outputText } = ts.transpileModule(source, { | ||
| compilerOptions: { module: ts.ModuleKind.CommonJS }, | ||
| }); | ||
| const jsPath = tsPath.replace(/\.ts$/, '.js'); | ||
| fs.writeFileSync(jsPath, outputText, 'utf-8'); | ||
| return require(jsPath); | ||
| } | ||
|
|
||
| function runTest() { | ||
| const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gen-msg-test-')); | ||
|
|
||
| try { | ||
| const file1 = path.join(tmpDir, 'file1.ts'); | ||
| const file2 = path.join(tmpDir, 'file2.ts'); | ||
| fs.writeFileSync(file1, buildFileContent(FILE1_EXPECTED, { includePlatforms: true }), 'utf-8'); | ||
| fs.writeFileSync(file2, buildFileContent(FILE2_EXPECTED), 'utf-8'); | ||
|
|
||
| execFileSync(process.execPath, [SCRIPT, file1, file2], { stdio: 'pipe' }); | ||
|
|
||
| const genFile1 = path.join(tmpDir, 'file1.gen.ts'); | ||
| const genFile2 = path.join(tmpDir, 'file2.gen.ts'); | ||
| assert.ok(fs.existsSync(genFile1), 'file1.gen.ts should be created'); | ||
| assert.ok(fs.existsSync(genFile2), 'file2.gen.ts should be created'); | ||
|
|
||
| for (const [expected, genPath, label] of [ | ||
| [FILE1_EXPECTED, genFile1, 'file1'], | ||
| [FILE2_EXPECTED, genFile2, 'file2'], | ||
| ]) { | ||
| const mod = compileAndLoad(genPath); | ||
|
|
||
| assert.ok(Array.isArray(mod.messages), `${label}: messages should be an array`); | ||
| assert.equal(mod.messages.length, expected.length, | ||
| `${label}: messages array length should be ${expected.length}, got ${mod.messages.length}`); | ||
|
|
||
| assert.equal(mod.__platforms, undefined, `${label}: __platforms should not be exported`); | ||
|
|
||
| const constantCount = Object.keys(mod).filter((k) => k !== 'messages').length; | ||
| assert.equal(constantCount, expected.length, | ||
| `${label}: should have ${expected.length} constants, got ${constantCount}`); | ||
|
|
||
| for (const exp of expected) { | ||
| assert.ok(exp.name in mod, | ||
| `${label}: constant "${exp.name}" should be present`); | ||
|
|
||
| const index = Number(mod[exp.name]); | ||
| assert.equal(mod.messages[index], exp.value, | ||
| `${label}: messages[${index}] should be "${exp.value}", got "${mod.messages[index]}"`); | ||
| } | ||
| } | ||
|
|
||
| console.log('All tests passed.'); | ||
| } finally { | ||
| fs.rmSync(tmpDir, { recursive: true, force: true }); | ||
| } | ||
| } | ||
|
|
||
| runTest(); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#!is UNIX only! Not that it matters a lot butbuild:wincould potentially be broken for this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah. But other scripts are also using this currently. Windows build is relevant only for devs' local machine, but we can use wsl nowadays. We can come back and fix the windows build later if needed