### Complete Localization Pipeline - Split Mode Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Processes individual JavaScript files in a split mode, applying localization patches. It reads a patch index, iterates through each file's configuration, parses the source JavaScript, applies translations and modifications from corresponding patch files, and generates modified output files. This function uses helper functions like `parseJsToAst`, `applyTranslations`, `applyModifications`, and `generateJsFromAst`. ```javascript const { main } = require('./scripts/ast-patcher.js'); const fs = require('fs-extra'); const path = require('path'); async function parseSplitedFile() { const patchIndexPath = './patch/index.json'; const patchIndex = await fs.readJson(patchIndexPath); const { infos } = patchIndex; for (const info of infos) { const { firstLine, scriptName, patch: patchFileName } = info; const patchPath = path.join('./patch', patchFileName); const sourcePath = path.join('./output', scriptName); const outputPath = path.join('./output', `modified_${scriptName}`); if (firstLine) { console.log(`处理文件: ${scriptName}`); } try { console.log('当前工作目录:', process.cwd()); console.log('源文件存在:', fs.existsSync(sourcePath)); console.log('补丁文件存在:', fs.existsSync(patchPath)); const patch = await fs.readJson(patchPath); const fileAst = parseJsToAst(sourcePath); console.log('AST解析成功,开始应用补丁...'); if (fileAst && typeof fileAst === 'object' && fileAst.program) { applyTranslations(fileAst, patch.translations || []); applyModifications(fileAst, patch.modifications || []); generateJsFromAst(fileAst, outputPath); console.log(`修改完成!输出路径:${outputPath}`); } else { throw new Error('无效的AST对象'); } } catch (err) { console.error('执行失败:', err.message); } } } // Run the split file processing // main('splited').catch(err => { // console.error('测试失败:', err); // }); ``` -------------------------------- ### Split Bundle Script - JavaScript File Splitting Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Splits the monolithic `Bundle.js` file into multiple readable JavaScript files. It uses 'use strict' markers as delimiters and matches the resulting code blocks with names defined in a configuration file (`patch/index.json`). This facilitates easier manipulation and translation of specific code segments. ```javascript const fs = require('fs-extra'); const path = require('path'); // Split the Bundle.js file const originalFilePath = './plutonium_origin/js/Bundle.js'; const outputDir = './output'; const patchIndexPath = './patch/index.json'; // Read and split the file const fileContent = fs.readFileSync(originalFilePath, 'utf8'); const lines = fileContent.split('\n'); const blocks = []; let currentBlock = []; // Split by "use strict" markers lines.forEach((line) => { const trimmedLine = line.trim(); if (trimmedLine === '"use strict";') { if (currentBlock.length > 0) { blocks.push(currentBlock); currentBlock = []; } currentBlock.push(line); } else { currentBlock.push(line); } }); // Match blocks with configuration and save const patchIndex = fs.readJsonSync(patchIndexPath); blocks.forEach((block, index) => { const contentLine = block.find(line => { const trimmed = line.trim(); return trimmed !== '' && trimmed !== '"use strict";'; }); const firstLine = contentLine ? contentLine.trim() : ''; const matchedInfo = patchIndex.infos.find(info => info.firstLine && firstLine.includes(info.firstLine.trim()) ); const fileName = matchedInfo?.scriptName || `part_${index + 1}.js`; const outputFilePath = path.join(outputDir, fileName); fs.writeFileSync(outputFilePath, block.join('\n')); console.log(`Created file: ${outputFilePath}`); }); ``` -------------------------------- ### Translation Configuration for String and Template Literal Replacement Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Defines translation rules for the parser, supporting both direct string replacements with optional context and advanced template literal translations. This structure allows for efficient localization of game terms and dynamic content. ```json { "translations": [ { "original": "Bestiary", "context": "Parser.CAT_ID_TO_FULL", "replacement": "怪物" }, { "original": "Spell", "context": "Parser.CAT_ID_TO_FULL", "replacement": "法术" }, { "type": "template", "quasis": ["https://5e.tools/", ""], "replacementPattern": "https://5e.kiwee.top/${expr0}" } ], "modifications": [ { "target": { "name": "pSerialAwaitMap", "params": ["additionType", "additionMeta"], "bodyStart": "switch (additionType) {" }, "replacement": "async ([additionType, additionMeta]) => {\n switch (additionType) {\n case \"innate\":\n case \"known\":\n case \"prepared\":\n case \"expanded\": {\n cpy[additionType] = await this._pGetMigratedBlock_pGetMigratedAdditionMeta({additionMeta});\n break;\n }\n case \"name\":\n case \"ENG_name\":\n case \"ability\":\n case \"resourceName\": break;\n default: throw new Error(`Unhandled spell addition type \"${additionType}\"`);\n }\n}" } ] } ``` -------------------------------- ### Complete Localization Pipeline - Bundle Mode Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Processes a single bundled JavaScript file for localization. It reads a patch index and applies all translation and modification patches sequentially to the entire bundle's AST. The function uses helper functions like `parseJsToAst`, `applyTranslations`, `applyModifications`, and `generateJsFromAst`. It handles file existence checks and error logging. ```javascript const { main } = require('./scripts/ast-patcher.js'); const fs = require('fs-extra'); const path = require('path'); async function parseBundleJs() { const patchIndexPath = './patch/index.json'; const patchIndex = await fs.readJson(patchIndexPath); const { infos } = patchIndex; const sourcePath = './plutonium_origin/js/Bundle.js'; const outputPath = './plutonium/js/Bundle.js'; console.log('当前工作目录:', process.cwd()); console.log('源文件存在:', fs.existsSync(sourcePath)); const fileAst = parseJsToAst(sourcePath); console.log('AST解析成功,开始应用补丁...'); console.log('AST类型:', typeof fileAst); if (!fileAst || typeof fileAst !== 'object' || !fileAst.program) { throw new Error('无效的AST对象'); } for (const info of infos) { const { scriptName, patch: patchFileName } = info; const patchPath = path.join('./patch', patchFileName); try { console.log('补丁文件存在:', fs.existsSync(patchPath)); const patch = await fs.readJson(patchPath); applyTranslations(fileAst, patch.translations || []); applyModifications(fileAst, patch.modifications || []); } catch (err) { console.error('执行失败:', err.message); } } generateJsFromAst(fileAst, outputPath); console.log(`修改完成!输出路径: ${outputPath}`); } // Run the bundle processing (default mode) // main().catch(err => { // console.error('执行失败:', err); // }); ``` -------------------------------- ### Update Plutonium Module Script Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Downloads the latest version of the Plutonium module from GitHub. It checks for version updates, downloads the module via proxy if necessary, and extracts it to a local directory. This script ensures the local copy of the module is up-to-date before localization. ```javascript const { execSync } = require('child_process'); // Download and extract the latest Plutonium module execSync('node scripts/update_plutonium.js', { stdio: 'inherit' }); // The script will: // 1. Download module.json from GitHub // 2. Compare versions with local copy // 3. Download the module ZIP file via proxy // 4. Extract to plutonium_origin/ directory // 5. Output: "版本 X.X.X 已经是最新的,无需更新。" if up-to-date ``` -------------------------------- ### Generate JavaScript from AST Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Converts a modified Abstract Syntax Tree (AST) back into JavaScript code and writes it to a specified output file. It uses '@babel/generator' for code generation and 'fs-extra' for file operations. The function expects a valid AST object and an output path, handling potential errors during the process. ```javascript const generate = require('@babel/generator').default; const fs = require('fs-extra'); function generateJsFromAst(fileAst, outputPath) { try { if (!fileAst || typeof fileAst !== 'object') { throw new Error('无效的AST对象'); } if (!fileAst.program) { throw new Error('AST对象缺少program属性'); } const result = generate(fileAst, { retainLines: true, comments: true, compact: false, minified: false, sourceMaps: false }); fs.writeFileSync(outputPath, result.code, 'utf8'); console.log(`代码生成成功,已写入:${outputPath}`); } catch (err) { console.error('代码生成失败:', err.message); throw err; } } // Usage example // const fileAst = parseJsToAst('./output/parser.js'); // applyTranslations(fileAst, translationConfig); // applyModifications(fileAst, modificationConfig); // generateJsFromAst(fileAst, './plutonium/js/Bundle.js'); ``` -------------------------------- ### Index Configuration for Mapping Script Segments to Patch Files Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Maps JavaScript file segments, identified by their first line, to their corresponding patch configuration files. This structure is used to manage and apply patches to specific parts of the codebase. ```json { "infos": [ { "firstLine": "globalThis.Parser = {};", "scriptName": "parser.js", "patch": "parser.json" }, { "firstLine": "globalThis.IS_DEPLOYED = undefined;", "scriptName": "utils.js", "patch": "utils.json" }, { "firstLine": "class _DataLoaderConst {", "scriptName": "fvtt.js", "patch": "fvtt.json" }, { "firstLine": "class UtilHandlebars {", "scriptName": "util-handlebars.js", "patch": "util-handlebars.json" } ] } ``` -------------------------------- ### AST Patcher - Parse JavaScript to AST Source: https://context7.com/5etools-plutonium-cn/plutonium-parser/llms.txt Parses JavaScript code into an Abstract Syntax Tree (AST) using Babel's parser. This allows for programmatic manipulation of the code's structure. It handles file reading, error checking, and supports various JavaScript features through Babel plugins. ```javascript const parser = require('@babel/parser'); const fs = require('fs-extra'); function parseJsToAst(filePath) { try { if (!fs.existsSync(filePath)) { throw new Error(`文件不存在: ${filePath}`); } const code = fs.readFileSync(filePath, 'utf8'); const fileAst = parser.parse(code, { sourceType: 'script', plugins: [ 'jsx', 'classProperties', 'optionalChaining', 'strictMode', 'deprecatedFeatures', 'es3-member-expression-literals', 'es3-property-literals', 'functionBind', 'objectRestSpread' ] }); if (!fileAst || !fileAst.program) { throw new Error('解析结果不包含Program节点'); } return fileAst; } catch (err) { console.error('解析失败:', err.message); throw err; } } // Usage example const sourcePath = './output/parser.js'; const fileAst = parseJsToAst(sourcePath); console.log('AST parsed successfully:', fileAst.program.body.length, 'nodes'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.