jsii-rosetta 5.9.21-dev.0 → 5.9.22
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/README.md +25 -231
- package/lib/commands/extract.d.ts +2 -1
- package/lib/commands/extract.js +5 -3
- package/lib/commands/extract.js.map +1 -1
- package/lib/commands/infuse.js +3 -3
- package/lib/commands/infuse.js.map +1 -1
- package/lib/commands/trim-cache.js +1 -1
- package/lib/commands/trim-cache.js.map +1 -1
- package/lib/jsii/fingerprinting.d.ts +4 -0
- package/lib/jsii/fingerprinting.js +9 -0
- package/lib/jsii/fingerprinting.js.map +1 -1
- package/lib/main.js +4 -0
- package/lib/main.js.map +1 -1
- package/lib/rosetta-reader.js +2 -2
- package/lib/rosetta-reader.js.map +1 -1
- package/lib/rosetta-translator.js +8 -4
- package/lib/rosetta-translator.js.map +1 -1
- package/lib/tablets/tablets.d.ts +14 -8
- package/lib/tablets/tablets.js +23 -13
- package/lib/tablets/tablets.js.map +1 -1
- package/lib/translate.d.ts +15 -0
- package/lib/translate.js +46 -7
- package/lib/translate.js.map +1 -1
- package/lib/translate_all.d.ts +2 -1
- package/lib/translate_all.js +10 -3
- package/lib/translate_all.js.map +1 -1
- package/lib/translate_all_worker.js +16 -1
- package/lib/translate_all_worker.js.map +1 -1
- package/package.json +2 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.js","sourceRoot":"","sources":["../../src/commands/extract.ts"],"names":[],"mappings":";;AA8GA,4CAQC;AAKD,0CAkHC;AA7OD,kCAAkC;AAElC,qCAAkC;AAClC,mDAK4B;AAC5B,sCAAsC;AACtC,8DAAoF;AACpF,wCAAkE;AAClE,wCAA4C;AAC5C,gDAAyG;AAEzG,kCAA6C;AA+FtC,KAAK,UAAU,gBAAgB,CAAC,iBAA2B,EAAE,OAAuB;IACzF,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACjE,MA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AAmB,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;AACpD,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAAC,EAAuB,EAAE,UAAoB;IACnE,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAA,gBAAU,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAqB;IAC7C,MAAM,GAAG,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC,2BAAiB,CAAC,kBAAkB,CAAC,CAAC;IAClE,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACxG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as path from 'node:path';\n\nimport { infuse } from './infuse';\nimport {\n loadAssemblies,\n allTypeScriptSnippets,\n loadAllDefaultTablets,\n compressedTabletExists,\n} from '../jsii/assemblies';\nimport * as logging from '../logging';\nimport { RosettaTranslator, RosettaTranslatorOptions } from '../rosetta-translator';\nimport { TypeScriptSnippet, SnippetParameters } from '../snippet';\nimport { snippetKey } from '../tablets/key';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { RosettaDiagnostic } from '../translate';\nimport { groupBy, isDefined } from '../util';\n\nexport interface ExtractResult {\n diagnostics: RosettaDiagnostic[];\n tablet: LanguageTablet;\n}\n\nexport interface ExtractOptions {\n readonly includeCompilerDiagnostics?: boolean;\n readonly validateAssemblies?: boolean;\n readonly only?: string[];\n\n /**\n * A tablet file to be loaded and used as a source for caching\n */\n readonly cacheFromFile?: string;\n\n /**\n * A tablet file to append translated snippets to\n */\n readonly cacheToFile?: string;\n\n /**\n * Trim cache to only contain translations found in the current assemblies\n *\n * @default false\n */\n readonly trimCache?: boolean;\n\n /**\n * Write translations to implicit tablets (`.jsii.tabl.json`)\n *\n * @default true\n */\n readonly writeToImplicitTablets?: boolean;\n\n /**\n * What directory to compile the samples in\n *\n * @default - Rosetta manages the compilation directory\n * @deprecated Samples declare their own dependencies instead\n */\n readonly compilationDirectory?: string;\n\n /**\n * Make a translator (just for testing)\n */\n readonly translatorFactory?: (opts: RosettaTranslatorOptions) => RosettaTranslator;\n\n /**\n * Turn on 'loose mode' or not\n *\n * Loose mode ignores failures during fixturizing, and undoes 'strict mode' for\n * diagnostics.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Accept dirty translations from the cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n\n /**\n * Compress the implicit tablet files.\n *\n * @default - preserves the original compression status of each individual implicit tablet file.\n */\n readonly compressTablet?: boolean;\n\n /**\n * Compress the cacheToFile tablet.\n *\n * @default false\n */\n readonly compressCacheToFile?: boolean;\n\n /**\n * Cleanup temporary directories\n *\n * @default true\n */\n readonly cleanup?: boolean;\n\n /**\n * Batch size for compiling snippets together\n *\n * @default undefined (no batching)\n */\n readonly batchSize?: number;\n}\n\nexport async function extractAndInfuse(assemblyLocations: string[], options: ExtractOptions): Promise<ExtractResult> {\n const result = await extractSnippets(assemblyLocations, options);\n await infuse(assemblyLocations, {\n cacheFromFile: options.cacheFromFile,\n cacheToFile: options.cacheToFile,\n compressCacheToFile: options.compressCacheToFile,\n });\n return result;\n}\n\n/**\n * Extract all samples from the given assemblies into a tablet\n */\nexport async function extractSnippets(\n assemblyLocations: readonly string[],\n options: ExtractOptions = {},\n): Promise<ExtractResult> {\n const only = options.only ?? [];\n\n logging.info(`Loading ${assemblyLocations.length} assemblies`);\n const assemblies = loadAssemblies(assemblyLocations, options.validateAssemblies ?? false);\n\n let snippets = Array.from(await allTypeScriptSnippets(assemblies, options.loose));\n if (only.length > 0) {\n snippets = filterSnippets(snippets, only);\n }\n\n // Map every assembly to a list of snippets, so that we know what implicit\n // tablet to write the translations to later on.\n const snippetsPerAssembly = groupBy(\n snippets.map((s) => ({ key: snippetKey(s), location: projectDirectory(s) })),\n (x) => x.location,\n );\n\n const translatorOptions: RosettaTranslatorOptions = {\n includeCompilerDiagnostics: options.includeCompilerDiagnostics ?? false,\n assemblies: assemblies.map((a) => a.assembly),\n allowDirtyTranslations: options.allowDirtyTranslations,\n };\n\n const translator = options.translatorFactory\n ? options.translatorFactory(translatorOptions)\n : new RosettaTranslator(translatorOptions);\n\n // Prime the snippet cache with:\n // - Cache source file\n // - Default tablets found next to each assembly\n if (options.cacheFromFile) {\n await translator.addToCache(options.cacheFromFile);\n }\n translator.addTabletsToCache(...Object.values(await loadAllDefaultTablets(assemblies)));\n\n if (translator.hasCache()) {\n const cache = translator.readFromCache(snippets, true, options.includeCompilerDiagnostics);\n logging.info(`Reused ${cache.dirtyCount === 0 ? 'all ' : ''}${cache.translations.length} translations from cache`);\n if (cache.dirtyCount) {\n const dirt = {\n 'non-compiling': cache.dirtyDidntCompile,\n 'changed sources': cache.dirtySourceCount,\n 'changed translator version': cache.dirtyTranslatorCount,\n 'changed types': cache.dirtyTypesCount,\n };\n logging.info(\n `Dropped ${cache.dirtyCount} translations (${Object.entries(dirt)\n .filter(([_, count]) => !!count)\n .map(([desc, count]) => `${count} ${desc}`)\n .join(', ')})`,\n );\n }\n\n snippets = cache.remaining;\n }\n\n const diagnostics = [];\n if (snippets.length > 0) {\n logging.info('Translating');\n const startTime = Date.now();\n\n const result = await translator.translateAll(snippets, {\n compilationDirectory: options.compilationDirectory,\n cleanup: options.cleanup,\n batchSize: options.batchSize,\n });\n\n const delta = (Date.now() - startTime) / 1000;\n logging.info(\n `Translated ${snippets.length} snippets in ${delta} seconds (${(delta / snippets.length).toPrecision(\n 3,\n )}s/snippet)`,\n );\n diagnostics.push(...result.diagnostics);\n } else {\n logging.info('Nothing left to translate');\n }\n\n // Save to individual tablet files\n if (options.writeToImplicitTablets ?? true) {\n await Promise.all(\n Object.entries(snippetsPerAssembly).map(async ([location, snips]) => {\n // Compress the implicit tablet if explicitly asked to, otherwise compress only if the original tablet was compressed.\n const compressedTablet = options.compressTablet ?? compressedTabletExists(location);\n\n const asmTabletFile = path.join(\n location,\n compressedTablet ? DEFAULT_TABLET_NAME_COMPRESSED : DEFAULT_TABLET_NAME,\n );\n logging.debug(`Writing ${snips.length} translations to ${asmTabletFile}`);\n const translations = snips.map(({ key }) => translator.tablet.tryGetSnippet(key)).filter(isDefined);\n\n const asmTablet = new LanguageTablet();\n asmTablet.addSnippets(...translations);\n await asmTablet.save(asmTabletFile, compressedTablet);\n }),\n );\n }\n\n // optionally append to the output file\n if (options.cacheToFile) {\n logging.info(`Adding translations to ${options.cacheToFile}`);\n const output = options.trimCache\n ? new LanguageTablet()\n : await LanguageTablet.fromOptionalFile(options.cacheToFile);\n output.addTablets(translator.tablet);\n await output.save(options.cacheToFile, options.compressCacheToFile);\n }\n\n return { diagnostics, tablet: translator.tablet };\n}\n\n/**\n * Only yield the snippets whose id exists in a whitelist\n */\nfunction filterSnippets(ts: TypeScriptSnippet[], includeIds: string[]) {\n return ts.filter((t) => includeIds.includes(snippetKey(t)));\n}\n\nfunction projectDirectory(ts: TypeScriptSnippet) {\n const dir = ts.parameters?.[SnippetParameters.$PROJECT_DIRECTORY];\n if (!dir) {\n throw new Error(`Snippet does not have associated project directory: ${JSON.stringify(ts.location)}`);\n }\n return dir;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"extract.js","sourceRoot":"","sources":["../../src/commands/extract.ts"],"names":[],"mappings":";;AA+GA,4CAQC;AAKD,0CAoHC;AAhPD,kCAAkC;AAElC,qCAAkC;AAClC,mDAK4B;AAC5B,sCAAsC;AACtC,8DAAoF;AACpF,wCAAkE;AAClE,wCAA4C;AAC5C,gDAAyG;AAEzG,kCAA6C;AAgGtC,KAAK,UAAU,gBAAgB,CAAC,i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,wBAAc,EAAE;YACtB,CAAC,CAAC,MAAM,wBAAc,CAAC,gBAAgB,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;QAC/D,MAAM,CAAC,sBAAsB,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;QACjD,MAAM,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACtE,CAAC;IAED,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;AAC7D,CAAC;AAED;;GAEG;AACH,SAAS,cAAc,CAAC,EAAuB,EAAE,UAAoB;IACnE,OAAO,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAA,gBAAU,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,gBAAgB,CAAC,EAAqB;IAC7C,MAAM,GAAG,GAAG,EAAE,CAAC,UAAU,EAAE,CAAC,2BAAiB,CAAC,kBAAkB,CAAC,CAAC;IAClE,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,MAAM,IAAI,KAAK,CAAC,uDAAuD,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACxG,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as path from 'node:path';\n\nimport { infuse } from './infuse';\nimport {\n loadAssemblies,\n allTypeScriptSnippets,\n loadAllDefaultTablets,\n compressedTabletExists,\n} from '../jsii/assemblies';\nimport * as logging from '../logging';\nimport { RosettaTranslator, RosettaTranslatorOptions } from '../rosetta-translator';\nimport { TypeScriptSnippet, SnippetParameters } from '../snippet';\nimport { snippetKey } from '../tablets/key';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { RosettaDiagnostic, SnippetTimingInfo } from '../translate';\nimport { groupBy, isDefined } from '../util';\n\nexport interface ExtractResult {\n diagnostics: RosettaDiagnostic[];\n tablet: LanguageTablet;\n timings?: SnippetTimingInfo[];\n}\n\nexport interface ExtractOptions {\n readonly includeCompilerDiagnostics?: boolean;\n readonly validateAssemblies?: boolean;\n readonly only?: string[];\n\n /**\n * A tablet file to be loaded and used as a source for caching\n */\n readonly cacheFromFile?: string;\n\n /**\n * A tablet file to append translated snippets to\n */\n readonly cacheToFile?: string;\n\n /**\n * Trim cache to only contain translations found in the current assemblies\n *\n * @default false\n */\n readonly trimCache?: boolean;\n\n /**\n * Write translations to implicit tablets (`.jsii.tabl.json`)\n *\n * @default true\n */\n readonly writeToImplicitTablets?: boolean;\n\n /**\n * What directory to compile the samples in\n *\n * @default - Rosetta manages the compilation directory\n * @deprecated Samples declare their own dependencies instead\n */\n readonly compilationDirectory?: string;\n\n /**\n * Make a translator (just for testing)\n */\n readonly translatorFactory?: (opts: RosettaTranslatorOptions) => RosettaTranslator;\n\n /**\n * Turn on 'loose mode' or not\n *\n * Loose mode ignores failures during fixturizing, and undoes 'strict mode' for\n * diagnostics.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Accept dirty translations from the cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n\n /**\n * Compress the implicit tablet files.\n *\n * @default - preserves the original compression status of each individual implicit tablet file.\n */\n readonly compressTablet?: boolean;\n\n /**\n * Compress the cacheToFile tablet.\n *\n * @default false\n */\n readonly compressCacheToFile?: boolean;\n\n /**\n * Cleanup temporary directories\n *\n * @default true\n */\n readonly cleanup?: boolean;\n\n /**\n * Batch size for compiling snippets together\n *\n * @default undefined (no batching)\n */\n readonly batchSize?: number;\n}\n\nexport async function extractAndInfuse(assemblyLocations: string[], options: ExtractOptions): Promise<ExtractResult> {\n const result = await extractSnippets(assemblyLocations, options);\n await infuse(assemblyLocations, {\n cacheFromFile: options.cacheFromFile,\n cacheToFile: options.cacheToFile,\n compressCacheToFile: options.compressCacheToFile,\n });\n return result;\n}\n\n/**\n * Extract all samples from the given assemblies into a tablet\n */\nexport async function extractSnippets(\n assemblyLocations: readonly string[],\n options: ExtractOptions = {},\n): Promise<ExtractResult> {\n const only = options.only ?? [];\n\n logging.info(`Loading ${assemblyLocations.length} assemblies`);\n const assemblies = loadAssemblies(assemblyLocations, options.validateAssemblies ?? false);\n\n let snippets = Array.from(await allTypeScriptSnippets(assemblies, options.loose));\n if (only.length > 0) {\n snippets = filterSnippets(snippets, only);\n }\n\n // Map every assembly to a list of snippets, so that we know what implicit\n // tablet to write the translations to later on.\n const snippetsPerAssembly = groupBy(\n snippets.map((s) => ({ key: snippetKey(s), location: projectDirectory(s) })),\n (x) => x.location,\n );\n\n const translatorOptions: RosettaTranslatorOptions = {\n includeCompilerDiagnostics: options.includeCompilerDiagnostics ?? false,\n assemblies: assemblies.map((a) => a.assembly),\n allowDirtyTranslations: options.allowDirtyTranslations,\n };\n\n const translator = options.translatorFactory\n ? options.translatorFactory(translatorOptions)\n : new RosettaTranslator(translatorOptions);\n\n // Prime the snippet cache with:\n // - Cache source file\n // - Default tablets found next to each assembly\n if (options.cacheFromFile) {\n await translator.addToCache(options.cacheFromFile);\n }\n translator.addTabletsToCache(...Object.values(await loadAllDefaultTablets(assemblies)));\n\n if (translator.hasCache()) {\n const cache = translator.readFromCache(snippets, true, options.includeCompilerDiagnostics);\n logging.info(`Reused ${cache.dirtyCount === 0 ? 'all ' : ''}${cache.translations.length} translations from cache`);\n if (cache.dirtyCount) {\n const dirt = {\n 'non-compiling': cache.dirtyDidntCompile,\n 'changed sources': cache.dirtySourceCount,\n 'changed translator version': cache.dirtyTranslatorCount,\n 'changed types': cache.dirtyTypesCount,\n };\n logging.info(\n `Dropped ${cache.dirtyCount} translations (${Object.entries(dirt)\n .filter(([_, count]) => !!count)\n .map(([desc, count]) => `${count} ${desc}`)\n .join(', ')})`,\n );\n }\n\n snippets = cache.remaining;\n }\n\n const diagnostics = [];\n const timings: SnippetTimingInfo[] = [];\n if (snippets.length > 0) {\n logging.info('Translating');\n const startTime = Date.now();\n\n const result = await translator.translateAll(snippets, {\n compilationDirectory: options.compilationDirectory,\n cleanup: options.cleanup,\n batchSize: options.batchSize,\n });\n\n const delta = (Date.now() - startTime) / 1000;\n logging.info(\n `Translated ${snippets.length} snippets in ${delta} seconds (${(delta / snippets.length).toPrecision(\n 3,\n )}s/snippet)`,\n );\n diagnostics.push(...result.diagnostics);\n timings.push(...(result.timings ?? []));\n } else {\n logging.info('Nothing left to translate');\n }\n\n // Save to individual tablet files\n if (options.writeToImplicitTablets ?? true) {\n await Promise.all(\n Object.entries(snippetsPerAssembly).map(async ([location, snips]) => {\n // Compress the implicit tablet if explicitly asked to, otherwise compress only if the original tablet was compressed.\n const compressedTablet = options.compressTablet ?? compressedTabletExists(location);\n\n const asmTabletFile = path.join(\n location,\n compressedTablet ? DEFAULT_TABLET_NAME_COMPRESSED : DEFAULT_TABLET_NAME,\n );\n logging.debug(`Writing ${snips.length} translations to ${asmTabletFile}`);\n const translations = snips.map(({ key }) => translator.tablet.tryGetSnippet(key)).filter(isDefined);\n\n const asmTablet = new LanguageTablet();\n asmTablet.addTranslations(...translations);\n await asmTablet.save(asmTabletFile, compressedTablet);\n }),\n );\n }\n\n // optionally append to the output file\n if (options.cacheToFile) {\n logging.info(`Adding translations to ${options.cacheToFile}`);\n const output = options.trimCache\n ? new LanguageTablet()\n : await LanguageTablet.fromOptionalFile(options.cacheToFile);\n output.addSnippetsFromTablets(translator.tablet);\n await output.save(options.cacheToFile, options.compressCacheToFile);\n }\n\n return { diagnostics, tablet: translator.tablet, timings };\n}\n\n/**\n * Only yield the snippets whose id exists in a whitelist\n */\nfunction filterSnippets(ts: TypeScriptSnippet[], includeIds: string[]) {\n return ts.filter((t) => includeIds.includes(snippetKey(t)));\n}\n\nfunction projectDirectory(ts: TypeScriptSnippet) {\n const dir = ts.parameters?.[SnippetParameters.$PROJECT_DIRECTORY];\n if (!dir) {\n throw new Error(`Snippet does not have associated project directory: ${JSON.stringify(ts.location)}`);\n }\n return dir;\n}\n"]}
|
package/lib/commands/infuse.js
CHANGED
|
@@ -41,9 +41,9 @@ async function infuse(assemblyLocations, options) {
|
|
|
41
41
|
const defaultTablets = await (0, assemblies_1.loadAllDefaultTablets)(assemblies);
|
|
42
42
|
const availableTranslations = new tablets_1.LanguageTablet();
|
|
43
43
|
if (options?.cacheFromFile) {
|
|
44
|
-
availableTranslations.
|
|
44
|
+
availableTranslations.addTranslationsFromTablet(await tablets_1.LanguageTablet.fromOptionalFile(options.cacheFromFile));
|
|
45
45
|
}
|
|
46
|
-
availableTranslations.
|
|
46
|
+
availableTranslations.addTranslationsFromTablets(...Object.values(defaultTablets));
|
|
47
47
|
const { translationsByFqn, originalsByKey } = await availableSnippetsPerFqn(assemblies, availableTranslations);
|
|
48
48
|
const additionalOutputTablet = options?.cacheToFile
|
|
49
49
|
? await tablets_1.LanguageTablet.fromOptionalFile(options?.cacheToFile)
|
|
@@ -165,7 +165,7 @@ function insertExample(example, original, type, tablets) {
|
|
|
165
165
|
};
|
|
166
166
|
}
|
|
167
167
|
for (const tablet of tablets) {
|
|
168
|
-
tablet.
|
|
168
|
+
tablet.addTranslations(example.withLocation({
|
|
169
169
|
api: { api: 'type', fqn: type.fqn },
|
|
170
170
|
field: { field: 'example' },
|
|
171
171
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"infuse.js","sourceRoot":"","sources":["../../src/commands/infuse.ts"],"names":[],"mappings":";;;AAgEA,wBAmFC;AAnJD,8BAA8B;AAC9B,kCAAkC;AAClC,mCAAmC;AACnC,qCAA6C;AAE7C,mDAAkH;AAClH,wCAAmE;AACnE,4DAA4F;AAC5F,wCAA4C;AAC5C,gDAK4B;AAC5B,kCAAqD;AA8BxC,QAAA,6BAA6B,GAAG,uBAAuB,CAAC;AAErE,MAAM,oBAAoB,GAAoC,EAAE,UAAU,EAAV,8BAAU,EAAE,QAAQ,EAAR,4B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E,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACf,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as spec from '@jsii/spec';\nimport { replaceAssembly } from '@jsii/spec';\n\nimport { loadAssemblies, loadAllDefaultTablets, LoadedAssembly, allTypeScriptSnippets } from '../jsii/assemblies';\nimport { renderMetadataline, TypeScriptSnippet } from '../snippet';\nimport { SnippetSelector, mean, meanLength, shortest, longest } from '../snippet-selectors';\nimport { snippetKey } from '../tablets/key';\nimport {\n LanguageTablet,\n TranslatedSnippet,\n DEFAULT_TABLET_NAME,\n DEFAULT_TABLET_NAME_COMPRESSED,\n} from '../tablets/tablets';\nimport { isDefined, mkDict, indexBy } from '../util';\n\nexport interface InfuseResult {\n readonly coverageResults: Record<string, InfuseTypes>;\n}\n\nexport interface InfuseTypes {\n readonly types: number;\n readonly typesWithInsertedExamples: number;\n}\n\nexport interface InfuseOptions {\n readonly logFile?: string;\n\n /**\n * Where to read additional translations\n */\n readonly cacheFromFile?: string;\n\n /**\n * In addition to the implicit tablets, also write all added examples to this additional output tablet\n */\n readonly cacheToFile?: string;\n\n /**\n * Compress the cacheToFile\n */\n readonly compressCacheToFile?: boolean;\n}\n\nexport const DEFAULT_INFUSION_RESULTS_NAME = 'infusion-results.html';\n\nconst ADDITIONAL_SELECTORS: Record<string, SnippetSelector> = { meanLength, shortest, longest };\n\nclass DefaultRecord<A> {\n public readonly index: Record<string, A[]> = {};\n\n public add(key: string, value: A) {\n if (!this.index[key]) {\n this.index[key] = [];\n }\n this.index[key].push(value);\n }\n}\n\n/**\n * Infuse will analyze the snippets in a set of tablets, and update the assembly to add\n * examples to types that don't have any yet, based on snippets that use the given type.\n */\nexport async function infuse(assemblyLocations: string[], options?: InfuseOptions): Promise<InfuseResult> {\n let stream: fs.WriteStream | undefined = undefined;\n if (options?.logFile) {\n // Create stream for html file and insert some styling\n stream = fs.createWriteStream(options.logFile, { encoding: 'utf-8' });\n startFile(stream);\n }\n\n // Load tablet file and assemblies\n const assemblies = loadAssemblies(assemblyLocations, false);\n const defaultTablets = await loadAllDefaultTablets(assemblies);\n\n const availableTranslations = new LanguageTablet();\n if (options?.cacheFromFile) {\n availableTranslations.addTablet(await LanguageTablet.fromOptionalFile(options.cacheFromFile));\n }\n availableTranslations.addTablets(...Object.values(defaultTablets));\n\n const { translationsByFqn, originalsByKey } = await availableSnippetsPerFqn(assemblies, availableTranslations);\n\n const additionalOutputTablet = options?.cacheToFile\n ? await LanguageTablet.fromOptionalFile(options?.cacheToFile)\n : new LanguageTablet();\n\n const coverageResults = mkDict(\n await Promise.all(\n assemblies.map(async ({ assembly, directory }) => {\n stream?.write(`<h1>${assembly.name}</h1>\\n`);\n\n const implicitTablet = defaultTablets[directory];\n const implicitTabletFile = path.join(\n directory,\n implicitTablet.compressedSource ? DEFAULT_TABLET_NAME_COMPRESSED : DEFAULT_TABLET_NAME,\n );\n if (!implicitTablet) {\n throw new Error(`No tablet found for ${directory}`);\n }\n\n let insertedExamples = 0;\n const filteredTypes = filterForTypesWithoutExamples(assembly.types ?? {});\n for (const [typeFqn, type] of Object.entries(filteredTypes)) {\n const available = translationsByFqn[typeFqn];\n if (!available) {\n continue;\n }\n\n const example = pickBestExample(typeFqn, available, stream);\n const original = originalsByKey[example.key];\n insertExample(example, original, type, [implicitTablet, additionalOutputTablet]);\n insertedExamples++;\n }\n\n if (insertedExamples > 0) {\n // Save the updated assembly and implicit tablets\n // eslint-disable-next-line no-await-in-loop\n await Promise.all([\n replaceAssembly(assembly, directory),\n implicitTablet.save(implicitTabletFile, implicitTablet.compressedSource),\n ]);\n }\n\n return [\n directory,\n {\n types: Object.keys(filteredTypes).length,\n typesWithInsertedExamples: insertedExamples,\n } as InfuseTypes,\n ] as const;\n }),\n ),\n );\n\n stream?.close();\n\n // If we copied examples onto different types, we'll also have inserted new snippets\n // with different keys into the tablet. We must now write the updated tablet somewhere.\n if (options?.cacheToFile) {\n await additionalOutputTablet.save(options.cacheToFile, options.compressCacheToFile);\n }\n\n return {\n coverageResults: coverageResults,\n };\n}\n\nfunction pickBestExample(typeFqn: string, choices: TranslatedSnippet[], logStream?: fs.WriteStream) {\n const meanResult = mean(choices);\n if (logStream) {\n const selected = Object.entries(ADDITIONAL_SELECTORS).map(([name, fn]) => [name, fn(choices)] as const);\n const selectedFromSelector = {\n ...makeDict(selected),\n mean: meanResult,\n };\n logOutput(logStream, typeFqn, createHtmlEntry(selectedFromSelector));\n }\n return meanResult;\n}\n\nfunction startFile(stream: fs.WriteStream) {\n stream.write('<style>\\n');\n stream.write('h2 { color: blue; clear: both; }\\n');\n stream.write('h1 { color: red; clear: both; }\\n');\n stream.write(\n 'div { float: left; height: 31em; width: 22em; overflow: auto; margin: 1em; background-color: #ddd; }\\n',\n );\n stream.write(\n 'pre { float: left; height: 30em; width: 25em; overflow: auto; padding: 0.5em; background-color: #ddd; }\\n',\n );\n stream.write('</style>\\n');\n}\n\nfunction createHtmlEntry(results: Record<string, TranslatedSnippet>): Record<string, string[]> {\n const entry = new DefaultRecord<string>();\n for (const [key, value] of Object.entries(results)) {\n entry.add(value.originalSource.source, key);\n }\n return entry.index;\n}\n\nfunction logOutput(stream: fs.WriteStream | undefined, typeFqn: string, algorithmMap: Record<string, string[]>) {\n stream?.write(`<h2>${typeFqn}</h2>\\n`);\n for (const [key, value] of Object.entries(algorithmMap)) {\n stream?.write(`<div class=\"snippet\"><h3>${value.toString()}</h3>\\n<pre>${key}</pre>\\n</div>\\n`);\n }\n for (let i = 0; i < 4 - Object.keys(algorithmMap).length; i++) {\n stream?.write('<div class=\"padding\"></div>\\n');\n }\n}\n\nfunction filterForTypesWithoutExamples(types: { [fqn: string]: spec.Type }): Record<string, spec.Type> {\n const filteredTypes: Record<string, spec.Type> = {};\n for (const [typeFqn, type] of Object.entries(types)) {\n // Ignore Interfaces that contain only properties\n if (type.kind === spec.TypeKind.Interface && !type.datatype) {\n continue;\n }\n // Already has example\n if (type.docs?.example !== undefined) {\n continue;\n }\n filteredTypes[typeFqn] = type;\n }\n return filteredTypes;\n}\n\n/**\n * Insert an example into the docs of a type, and insert it back into the tablet under a new key\n */\nfunction insertExample(\n example: TranslatedSnippet,\n original: TypeScriptSnippet | undefined,\n type: spec.Type,\n tablets: LanguageTablet[],\n): void {\n const parameters = {\n ...original?.parameters,\n infused: '',\n };\n // exampleMetadata should always be nonempty since we always have a parameter.\n const exampleMetadata = renderMetadataline(parameters) ?? '';\n\n if (type.docs) {\n type.docs.example = example.originalSource.source;\n type.docs.custom = { ...type.docs.custom, exampleMetadata };\n } else {\n type.docs = {\n example: example.originalSource.source,\n custom: { exampleMetadata },\n };\n }\n\n for (const tablet of tablets) {\n tablet.addSnippets(\n example.withLocation({\n api: { api: 'type', fqn: type.fqn },\n field: { field: 'example' },\n }),\n );\n }\n}\n\n/**\n * Return a map of FQN -> snippet keys that exercise that FQN.\n *\n * For a snippet to qualify, it must both:\n *\n * a) be current (i.e.: exist in the input assemblies)\n * b) have been analyzed (i.e.: exist in one of the translated tablets)\n *\n * Returns a map of fqns to a list of keys that represent snippets that include the fqn.\n */\nasync function availableSnippetsPerFqn(asms: readonly LoadedAssembly[], translationsTablet: LanguageTablet) {\n const ret = new DefaultRecord<TranslatedSnippet>();\n\n const originalsByKey = indexBy(await allTypeScriptSnippets(asms), snippetKey);\n\n const translations = Object.keys(originalsByKey)\n .map((key) => translationsTablet.tryGetSnippet(key))\n .filter(isDefined);\n\n for (const trans of translations) {\n for (const fqn of trans.snippet.fqnsReferenced ?? []) {\n ret.add(fqn, trans);\n }\n }\n\n return { originalsByKey, translationsByFqn: ret.index };\n}\n\nfunction makeDict<A>(xs: Array<readonly [string, A]>): Record<string, A> {\n const ret: Record<string, A> = {};\n for (const [str, a] of xs) {\n ret[str] = a;\n }\n return ret;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"infuse.js","sourceRoot":"","sources":["../../src/commands/infuse.ts"],"names":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YACrD,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;AAC1D,CAAC;AAED,SAAS,QAAQ,CAAI,EAA+B;IAClD,MAAM,GAAG,GAAsB,EAAE,CAAC;IAClC,KAAK,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACf,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as spec from '@jsii/spec';\nimport { replaceAssembly } from '@jsii/spec';\n\nimport { loadAssemblies, loadAllDefaultTablets, LoadedAssembly, allTypeScriptSnippets } from '../jsii/assemblies';\nimport { renderMetadataline, TypeScriptSnippet } from '../snippet';\nimport { SnippetSelector, mean, meanLength, shortest, longest } from '../snippet-selectors';\nimport { snippetKey } from '../tablets/key';\nimport {\n LanguageTablet,\n TranslatedSnippet,\n DEFAULT_TABLET_NAME,\n DEFAULT_TABLET_NAME_COMPRESSED,\n} from '../tablets/tablets';\nimport { isDefined, mkDict, indexBy } from '../util';\n\nexport interface InfuseResult {\n readonly coverageResults: Record<string, InfuseTypes>;\n}\n\nexport interface InfuseTypes {\n readonly types: number;\n readonly typesWithInsertedExamples: number;\n}\n\nexport interface InfuseOptions {\n readonly logFile?: string;\n\n /**\n * Where to read additional translations\n */\n readonly cacheFromFile?: string;\n\n /**\n * In addition to the implicit tablets, also write all added examples to this additional output tablet\n */\n readonly cacheToFile?: string;\n\n /**\n * Compress the cacheToFile\n */\n readonly compressCacheToFile?: boolean;\n}\n\nexport const DEFAULT_INFUSION_RESULTS_NAME = 'infusion-results.html';\n\nconst ADDITIONAL_SELECTORS: Record<string, SnippetSelector> = { meanLength, shortest, longest };\n\nclass DefaultRecord<A> {\n public readonly index: Record<string, A[]> = {};\n\n public add(key: string, value: A) {\n if (!this.index[key]) {\n this.index[key] = [];\n }\n this.index[key].push(value);\n }\n}\n\n/**\n * Infuse will analyze the snippets in a set of tablets, and update the assembly to add\n * examples to types that don't have any yet, based on snippets that use the given type.\n */\nexport async function infuse(assemblyLocations: string[], options?: InfuseOptions): Promise<InfuseResult> {\n let stream: fs.WriteStream | undefined = undefined;\n if (options?.logFile) {\n // Create stream for html file and insert some styling\n stream = fs.createWriteStream(options.logFile, { encoding: 'utf-8' });\n startFile(stream);\n }\n\n // Load tablet file and assemblies\n const assemblies = loadAssemblies(assemblyLocations, false);\n const defaultTablets = await loadAllDefaultTablets(assemblies);\n\n const availableTranslations = new LanguageTablet();\n if (options?.cacheFromFile) {\n availableTranslations.addTranslationsFromTablet(await LanguageTablet.fromOptionalFile(options.cacheFromFile));\n }\n availableTranslations.addTranslationsFromTablets(...Object.values(defaultTablets));\n\n const { translationsByFqn, originalsByKey } = await availableSnippetsPerFqn(assemblies, availableTranslations);\n\n const additionalOutputTablet = options?.cacheToFile\n ? await LanguageTablet.fromOptionalFile(options?.cacheToFile)\n : new LanguageTablet();\n\n const coverageResults = mkDict(\n await Promise.all(\n assemblies.map(async ({ assembly, directory }) => {\n stream?.write(`<h1>${assembly.name}</h1>\\n`);\n\n const implicitTablet = defaultTablets[directory];\n const implicitTabletFile = path.join(\n directory,\n implicitTablet.compressedSource ? DEFAULT_TABLET_NAME_COMPRESSED : DEFAULT_TABLET_NAME,\n );\n if (!implicitTablet) {\n throw new Error(`No tablet found for ${directory}`);\n }\n\n let insertedExamples = 0;\n const filteredTypes = filterForTypesWithoutExamples(assembly.types ?? {});\n for (const [typeFqn, type] of Object.entries(filteredTypes)) {\n const available = translationsByFqn[typeFqn];\n if (!available) {\n continue;\n }\n\n const example = pickBestExample(typeFqn, available, stream);\n const original = originalsByKey[example.key];\n insertExample(example, original, type, [implicitTablet, additionalOutputTablet]);\n insertedExamples++;\n }\n\n if (insertedExamples > 0) {\n // Save the updated assembly and implicit tablets\n // eslint-disable-next-line no-await-in-loop\n await Promise.all([\n replaceAssembly(assembly, directory),\n implicitTablet.save(implicitTabletFile, implicitTablet.compressedSource),\n ]);\n }\n\n return [\n directory,\n {\n types: Object.keys(filteredTypes).length,\n typesWithInsertedExamples: insertedExamples,\n } as InfuseTypes,\n ] as const;\n }),\n ),\n );\n\n stream?.close();\n\n // If we copied examples onto different types, we'll also have inserted new snippets\n // with different keys into the tablet. We must now write the updated tablet somewhere.\n if (options?.cacheToFile) {\n await additionalOutputTablet.save(options.cacheToFile, options.compressCacheToFile);\n }\n\n return {\n coverageResults: coverageResults,\n };\n}\n\nfunction pickBestExample(typeFqn: string, choices: TranslatedSnippet[], logStream?: fs.WriteStream) {\n const meanResult = mean(choices);\n if (logStream) {\n const selected = Object.entries(ADDITIONAL_SELECTORS).map(([name, fn]) => [name, fn(choices)] as const);\n const selectedFromSelector = {\n ...makeDict(selected),\n mean: meanResult,\n };\n logOutput(logStream, typeFqn, createHtmlEntry(selectedFromSelector));\n }\n return meanResult;\n}\n\nfunction startFile(stream: fs.WriteStream) {\n stream.write('<style>\\n');\n stream.write('h2 { color: blue; clear: both; }\\n');\n stream.write('h1 { color: red; clear: both; }\\n');\n stream.write(\n 'div { float: left; height: 31em; width: 22em; overflow: auto; margin: 1em; background-color: #ddd; }\\n',\n );\n stream.write(\n 'pre { float: left; height: 30em; width: 25em; overflow: auto; padding: 0.5em; background-color: #ddd; }\\n',\n );\n stream.write('</style>\\n');\n}\n\nfunction createHtmlEntry(results: Record<string, TranslatedSnippet>): Record<string, string[]> {\n const entry = new DefaultRecord<string>();\n for (const [key, value] of Object.entries(results)) {\n entry.add(value.originalSource.source, key);\n }\n return entry.index;\n}\n\nfunction logOutput(stream: fs.WriteStream | undefined, typeFqn: string, algorithmMap: Record<string, string[]>) {\n stream?.write(`<h2>${typeFqn}</h2>\\n`);\n for (const [key, value] of Object.entries(algorithmMap)) {\n stream?.write(`<div class=\"snippet\"><h3>${value.toString()}</h3>\\n<pre>${key}</pre>\\n</div>\\n`);\n }\n for (let i = 0; i < 4 - Object.keys(algorithmMap).length; i++) {\n stream?.write('<div class=\"padding\"></div>\\n');\n }\n}\n\nfunction filterForTypesWithoutExamples(types: { [fqn: string]: spec.Type }): Record<string, spec.Type> {\n const filteredTypes: Record<string, spec.Type> = {};\n for (const [typeFqn, type] of Object.entries(types)) {\n // Ignore Interfaces that contain only properties\n if (type.kind === spec.TypeKind.Interface && !type.datatype) {\n continue;\n }\n // Already has example\n if (type.docs?.example !== undefined) {\n continue;\n }\n filteredTypes[typeFqn] = type;\n }\n return filteredTypes;\n}\n\n/**\n * Insert an example into the docs of a type, and insert it back into the tablet under a new key\n */\nfunction insertExample(\n example: TranslatedSnippet,\n original: TypeScriptSnippet | undefined,\n type: spec.Type,\n tablets: LanguageTablet[],\n): void {\n const parameters = {\n ...original?.parameters,\n infused: '',\n };\n // exampleMetadata should always be nonempty since we always have a parameter.\n const exampleMetadata = renderMetadataline(parameters) ?? '';\n\n if (type.docs) {\n type.docs.example = example.originalSource.source;\n type.docs.custom = { ...type.docs.custom, exampleMetadata };\n } else {\n type.docs = {\n example: example.originalSource.source,\n custom: { exampleMetadata },\n };\n }\n\n for (const tablet of tablets) {\n tablet.addTranslations(\n example.withLocation({\n api: { api: 'type', fqn: type.fqn },\n field: { field: 'example' },\n }),\n );\n }\n}\n\n/**\n * Return a map of FQN -> snippet keys that exercise that FQN.\n *\n * For a snippet to qualify, it must both:\n *\n * a) be current (i.e.: exist in the input assemblies)\n * b) have been analyzed (i.e.: exist in one of the translated tablets)\n *\n * Returns a map of fqns to a list of keys that represent snippets that include the fqn.\n */\nasync function availableSnippetsPerFqn(asms: readonly LoadedAssembly[], translationsTablet: LanguageTablet) {\n const ret = new DefaultRecord<TranslatedSnippet>();\n\n const originalsByKey = indexBy(await allTypeScriptSnippets(asms), snippetKey);\n\n const translations = Object.keys(originalsByKey)\n .map((key) => translationsTablet.tryGetSnippet(key))\n .filter(isDefined);\n\n for (const trans of translations) {\n for (const fqn of trans.snippet.fqnsReferenced ?? []) {\n ret.add(fqn, trans);\n }\n }\n\n return { originalsByKey, translationsByFqn: ret.index };\n}\n\nfunction makeDict<A>(xs: Array<readonly [string, A]>): Record<string, A> {\n const ret: Record<string, A> = {};\n for (const [str, a] of xs) {\n ret[str] = a;\n }\n return ret;\n}\n"]}
|
|
@@ -12,7 +12,7 @@ async function trimCache(options) {
|
|
|
12
12
|
const snippets = Array.from(await (0, assemblies_1.allTypeScriptSnippets)(assemblies));
|
|
13
13
|
const original = await tablets_1.LanguageTablet.fromFile(options.cacheFile);
|
|
14
14
|
const updated = new tablets_1.LanguageTablet();
|
|
15
|
-
updated.
|
|
15
|
+
updated.addTranslations(...snippets.map((snip) => original.tryGetSnippet((0, key_1.snippetKey)(snip))).filter(util_1.isDefined));
|
|
16
16
|
// if the original file was compressed, then compress the updated file too
|
|
17
17
|
await updated.save(options.cacheFile, original.compressedSource);
|
|
18
18
|
// eslint-disable-next-line prettier/prettier
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trim-cache.js","sourceRoot":"","sources":["../../src/commands/trim-cache.ts"],"names":[],"mappings":";;AAkBA,8BAcC;AAhCD,mDAA2E;AAC3E,sCAAsC;AACtC,wCAA4C;AAC5C,gDAAoD;AACpD,kCAAoC;AAc7B,KAAK,UAAU,SAAS,CAAC,OAAyB;IACvD,OAAO,CAAC,IAAI,CAAC,WAAW,OAAO,CAAC,iBAAiB,CAAC,MAAM,aAAa,CAAC,CAAC;IACvE,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,OAAO,CAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAEpE,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,IAAA,kCAAqB,EAAC,UAAU,CAAC,CAAC,CAAC;IAErE,MAAM,QAAQ,GAAG,MAAM,wBAAc,CAAC,QAAQ,CAAC,OAAO,CAAC,SAA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nippets } from '../jsii/assemblies';\nimport * as logging from '../logging';\nimport { snippetKey } from '../tablets/key';\nimport { LanguageTablet } from '../tablets/tablets';\nimport { isDefined } from '../util';\n\nexport interface TrimCacheOptions {\n /**\n * Locations of assemblies to search for snippets\n */\n readonly assemblyLocations: string[];\n\n /**\n * Cache to trim\n */\n readonly cacheFile: string;\n}\n\nexport async function trimCache(options: TrimCacheOptions): Promise<void> {\n logging.info(`Loading ${options.assemblyLocations.length} assemblies`);\n const assemblies = loadAssemblies(options.assemblyLocations, false);\n\n const snippets = Array.from(await allTypeScriptSnippets(assemblies));\n\n const original = await LanguageTablet.fromFile(options.cacheFile);\n const updated = new LanguageTablet();\n updated.addTranslations(...snippets.map((snip) => original.tryGetSnippet(snippetKey(snip))).filter(isDefined));\n // if the original file was compressed, then compress the updated file too\n await updated.save(options.cacheFile, original.compressedSource);\n\n // eslint-disable-next-line prettier/prettier\n logging.info(`${options.cacheFile}: ${updated.count} snippets remaining (${original.count} - ${updated.count} trimmed)`);\n}\n"]}
|
|
@@ -23,6 +23,10 @@ export declare class TypeFingerprinter {
|
|
|
23
23
|
* in this assembly.
|
|
24
24
|
*/
|
|
25
25
|
fingerprintType(fqn: string): string;
|
|
26
|
+
/**
|
|
27
|
+
* Write the fingerprint cache to a debug file
|
|
28
|
+
*/
|
|
29
|
+
writeDebugFile(filename: string): void;
|
|
26
30
|
private doFingerprint;
|
|
27
31
|
private findType;
|
|
28
32
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.TypeFingerprinter = void 0;
|
|
4
4
|
const crypto = require("node:crypto");
|
|
5
|
+
const fs = require("node:fs");
|
|
5
6
|
const spec = require("@jsii/spec");
|
|
6
7
|
/**
|
|
7
8
|
* Return a fingerprint for a type.
|
|
@@ -39,6 +40,14 @@ class TypeFingerprinter {
|
|
|
39
40
|
fingerprintType(fqn) {
|
|
40
41
|
return this.doFingerprint(fqn, new Set([fqn]));
|
|
41
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* Write the fingerprint cache to a debug file
|
|
45
|
+
*/
|
|
46
|
+
writeDebugFile(filename) {
|
|
47
|
+
const entries = Array.from(this.cache.entries()).sort(([a], [b]) => a.localeCompare(b));
|
|
48
|
+
const lines = entries.map(([fqn, hash]) => `${fqn}: ${hash}`);
|
|
49
|
+
fs.writeFileSync(filename, lines.join('\n') + '\n');
|
|
50
|
+
}
|
|
42
51
|
doFingerprint(fqn, recursionBreaker) {
|
|
43
52
|
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
44
53
|
const self = this;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fingerprinting.js","sourceRoot":"","sources":["../../src/jsii/fingerprinting.ts"],"names":[],"mappings":";;;AAAA,sCAAsC;AACtC,mCAAmC;AAEnC;;;;;;;;GAQG;AACH,MAAa,iBAAiB;IAI5B,YAAmB,UAA2B;QAH7B,UAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;QAClC,eAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;QAG7D,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE,CAAC;YAClC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IAED;;OAEG;IACI,cAAc,CAAC,IAAc;QAClC,MAAM,IAAI,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;QACzC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;QACzC,CAAC;QACD,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC5B,CAAC;IAED;;;;;OAKG;IACI,eAAe,CAAC,GAAW;QAChC,OAAO,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,IAA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AI,CAAC,CAAC,CAAC;IAChD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import * as crypto from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as spec from '@jsii/spec';\n\n/**\n * Return a fingerprint for a type.\n *\n * The fingerprint will change if the API of the given type changes.\n *\n * The fingerprint is an approximation, it's not exhaustive. It will not trace\n * into types from assemblies it can't see, for example. For the purposes of Rosetta,\n * we'll assume this is Good Enough™.\n */\nexport class TypeFingerprinter {\n private readonly cache = new Map<string, string>();\n private readonly assemblies = new Map<string, spec.Assembly>();\n\n public constructor(assemblies: spec.Assembly[]) {\n for (const assembly of assemblies) {\n this.assemblies.set(assembly.name, assembly);\n }\n }\n\n /**\n * Return a single fingerprint that encompasses all fqns in the list\n */\n public fingerprintAll(fqns: string[]) {\n const hash = crypto.createHash('sha256');\n for (const fqn of fqns) {\n hash.update(this.fingerprintType(fqn));\n }\n return hash.digest('hex');\n }\n\n /**\n * Return the fingerprint for the given FQN in the assembly of this fingerprinter\n *\n * The fingerprint is always going to contain the FQN, even if the type doesn't exist\n * in this assembly.\n */\n public fingerprintType(fqn: string) {\n return this.doFingerprint(fqn, new Set([fqn]));\n }\n\n /**\n * Write the fingerprint cache to a debug file\n */\n public writeDebugFile(filename: string) {\n const entries = Array.from(this.cache.entries()).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([fqn, hash]) => `${fqn}: ${hash}`);\n fs.writeFileSync(filename, lines.join('\\n') + '\\n');\n }\n\n private doFingerprint(fqn: string, recursionBreaker: Set<string>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n const existing = this.cache.get(fqn);\n if (existing) {\n return existing;\n }\n\n const hash = crypto.createHash('sha256');\n hash.update(fqn);\n\n const type = this.findType(fqn);\n if (type) {\n hash.update(type.kind);\n switch (type.kind) {\n case spec.TypeKind.Enum:\n for (const member of sortedByName(type.members)) {\n hash.update(member.name);\n }\n break;\n case spec.TypeKind.Class:\n case spec.TypeKind.Interface:\n if (type.kind === spec.TypeKind.Class) {\n visitType(type.base);\n visitCallable(type.initializer);\n }\n\n for (const prop of sortedByName(type.properties ?? [])) {\n hash.update(prop.name);\n visitBools(prop.immutable, prop.static, prop.optional, prop.protected);\n visitTypeReference(prop.type);\n }\n for (const method of sortedByName(type.methods ?? [])) {\n hash.update(method.name);\n visitCallable(method);\n visitBools(method.returns?.optional);\n visitTypeReference(method.returns?.type);\n }\n for (const implint of type.interfaces ?? []) {\n visitType(implint);\n }\n\n break;\n }\n }\n\n const ret = hash.digest('hex');\n this.cache.set(fqn, ret);\n return ret;\n\n function visitType(fqnStr?: string) {\n if (!fqnStr) {\n return;\n }\n\n if (recursionBreaker.has(fqnStr)) {\n hash.update('$RECURSION$');\n return;\n }\n\n recursionBreaker.add(fqnStr);\n hash.update(self.doFingerprint(fqnStr, recursionBreaker));\n recursionBreaker.delete(fqnStr);\n }\n\n function visitCallable(callable?: spec.Callable) {\n if (!callable) {\n return;\n }\n\n visitBools(callable.protected);\n for (const param of callable.parameters ?? []) {\n visitBools(param.optional, param.variadic);\n visitTypeReference(param.type);\n }\n }\n\n function visitTypeReference(typeRef?: spec.TypeReference) {\n if (!typeRef) {\n return;\n }\n\n if (spec.isPrimitiveTypeReference(typeRef)) {\n hash.update(typeRef.primitive);\n }\n if (spec.isNamedTypeReference(typeRef)) {\n visitType(typeRef.fqn);\n }\n if (spec.isCollectionTypeReference(typeRef)) {\n hash.update(typeRef.collection.kind);\n visitTypeReference(typeRef.collection.elementtype);\n }\n if (spec.isUnionTypeReference(typeRef)) {\n for (const t of typeRef.union.types) {\n visitTypeReference(t);\n }\n }\n }\n\n function visitBools(...vs: Array<boolean | undefined>) {\n hash.update(vs.map((v) => (v ? '1' : '0')).join(''));\n }\n }\n\n private findType(fqn: string) {\n const assemblyName = fqn.split('.')[0];\n return this.assemblies.get(assemblyName)?.types?.[fqn];\n }\n}\n\nfunction sortedByName<A extends { name: string }>(xs: A[]): A[] {\n xs.sort((a, b) => a.name.localeCompare(b.name));\n return xs;\n}\n"]}
|
package/lib/main.js
CHANGED
|
@@ -263,6 +263,10 @@ async function main() {
|
|
|
263
263
|
? await (0, extract_1.extractAndInfuse)(absAssemblies, extractOptions)
|
|
264
264
|
: await (0, extract_1.extractSnippets)(absAssemblies, extractOptions);
|
|
265
265
|
handleDiagnostics(result.diagnostics, args.fail, result.tablet.count);
|
|
266
|
+
// Print timing table at the very end
|
|
267
|
+
if (result.timings && result.timings.length > 0) {
|
|
268
|
+
logging.warn((0, index_1.formatTimingTable)(result.timings));
|
|
269
|
+
}
|
|
266
270
|
}))
|
|
267
271
|
.command('transliterate [ASSEMBLY..]', '(EXPERIMENTAL) Transliterates the designated assemblies', (command) => command
|
|
268
272
|
.positional('ASSEMBLY', {
|
package/lib/main.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;AAAA,gCAA8B;AAE9B,qCAAyC;AACzC,kCAAkC;AAClC,+BAA+B;AAE/B,gDAAuD;AACvD,kDAAoD;AACpD,gDAAuF;AACvF,8CAA0E;AAC1E,0CAA6C;AAC7C,4DAAiE;AACjE,sDAAkD;AAClD,mCAAkF;AAClF,2CAAqE;AACrE,qCAAqC;AACrC,uCAAyD;AACzD,iCAAsD;AAEtD,KAAK,UAAU,IAAI;IACjB,MAAM,IAAA,sCAA4B,GAAE,CAAC;IAErC,MAAM,IAAI,GAAG,KAAK;SACf,KAAK,CAAC,iBAAiB,CAAC;SACxB,MAAM,CAAC,SAAS,EAAE;QACjB,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,4BAA4B;QAClC,KAAK,EAAE,IAAI;QACX,OAAO,EAAE,CAAC;KACX,CAAC;SACD,OAAO,CACN,cAAc,EACd,4BAA4B,EAC5B,CAAC,OAAO,EAAE,EAAE,CACV,OAAO;SACJ,UAAU,CAAC,MAAM,EAAE;QAClB,IAAI,EAAE,QAA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AW,CAAC,MAAM,GAAG,iBAAiB,CAAC,MAAM,CAAC;QAChE,OAAO,CAAC,IAAI,CACV;YACE,GAAG,iBAAiB,CAAC,MAAM,oDAAoD;YAC/E,GAAG,CAAC,SAAS,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,SAAS,+BAA+B,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;SAC7E,CAAC,IAAI,CAAC,GAAG,CAAC,CACZ,CAAC;QACF,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;QACrB,OAAO;IACT,CAAC;IAED,IAAI,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC3B,IAAA,uBAAgB,EAAC,WAAW,EAAE,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACpE,OAAO,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,MAAM,+BAA+B,YAAY,WAAW,CAAC,CAAC;IAC5F,CAAC;AACH,CAAC;AAED;;;GAGG;AACH,SAAS,eAAe,CAAC,GAAW;IAClC,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AACvC,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACrB,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC;AACxB,CAAC,CAAC,CAAC","sourcesContent":["import '@jsii/check-node/run';\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport * as yargs from 'yargs';\n\nimport { translateMarkdown } from './commands/convert';\nimport { checkCoverage } from './commands/coverage';\nimport { extractAndInfuse, extractSnippets, ExtractOptions } from './commands/extract';\nimport { infuse, DEFAULT_INFUSION_RESULTS_NAME } from './commands/infuse';\nimport { readTablet } from './commands/read';\nimport { transliterateAssembly } from './commands/transliterate';\nimport { trimCache } from './commands/trim-cache';\nimport { TranslateResult, translateTypeScript, RosettaDiagnostic } from './index';\nimport { getVisitorFromLanguage, TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { emitSupportPolicyInformation } from './support';\nimport { File, fmap, printDiagnostics } from './util';\n\nasync function main() {\n await emitSupportPolicyInformation();\n\n const argv = yargs\n .usage('$0 <cmd> [args]')\n .option('verbose', {\n alias: 'v',\n type: 'boolean',\n desc: 'Increase logging verbosity',\n count: true,\n default: 0,\n })\n .command(\n 'snippet FILE',\n 'Translate a single snippet',\n (command) =>\n command\n .positional('FILE', {\n type: 'string',\n describe: 'The file to translate (leave out for stdin)',\n })\n .option('language', {\n type: 'string',\n describe: 'Language ID to transliterate to',\n choices: Array.from(new Set(Object.values(TargetLanguage))),\n })\n .option('python', {\n alias: 'p',\n boolean: true,\n deprecated: true,\n description: 'Translate snippets to Python. Use --language python instead.',\n }),\n wrapHandler(async (args) => {\n const result = translateTypeScript(await makeFileSource(args.FILE ?? '-', 'stdin.ts'), makeVisitor(args));\n handleSingleResult(result);\n }),\n )\n .command(\n 'markdown FILE',\n 'Translate a MarkDown file',\n (command) =>\n command\n .positional('FILE', {\n type: 'string',\n describe: 'The file to translate (leave out for stdin)',\n })\n .option('language', {\n type: 'string',\n describe: 'Language ID to transliterate to',\n choices: Array.from(new Set(Object.values(TargetLanguage))),\n })\n .option('python', {\n alias: 'p',\n boolean: true,\n deprecated: true,\n description: 'Translate snippets to Python. Use --language python instead.',\n }),\n wrapHandler(async (args) => {\n const result = translateMarkdown(await makeFileSource(args.FILE ?? '-', 'stdin.md'), makeVisitor(args));\n handleSingleResult(result);\n }),\n )\n .command(\n 'infuse [ASSEMBLY..]',\n '(EXPERIMENTAL) mutates one or more assemblies by adding documentation examples to top-level types',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to mutate',\n })\n .option('log-file', {\n alias: 'l',\n type: 'string',\n describe: 'Output file to store logging results. Ignored if -log is not true',\n default: DEFAULT_INFUSION_RESULTS_NAME,\n })\n .option('cache-from', {\n alias: 'C',\n type: 'string',\n // eslint-disable-next-line prettier/prettier\n describe:\n 'Reuse translations from the given tablet file if the snippet and type definitions did not change',\n requiresArg: true,\n default: undefined,\n })\n .option('cache-to', {\n alias: 'o',\n type: 'string',\n describe: 'Append all translated snippets to the given tablet file',\n requiresArg: true,\n default: undefined,\n })\n .option('cache', {\n alias: 'k',\n type: 'string',\n describe: 'Alias for --cache-from and --cache-to together',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache', 'cache-from')\n .conflicts('cache', 'cache-to'),\n wrapHandler(async (args) => {\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n const absCacheFrom = fmap(args.cache ?? args['cache-from'], path.resolve);\n const absCacheTo = fmap(args.cache ?? args['cache-to'], path.resolve);\n const result = await infuse(absAssemblies, {\n logFile: args['log-file'],\n cacheToFile: absCacheTo,\n cacheFromFile: absCacheFrom,\n });\n\n let totalTypes = 0;\n let insertedExamples = 0;\n for (const [directory, map] of Object.entries(result.coverageResults)) {\n const commonName = directory.split('/').pop()!;\n const newCoverage = roundPercentage(map.typesWithInsertedExamples / map.types);\n process.stdout.write(\n `${commonName}: Added ${map.typesWithInsertedExamples} examples to ${map.types} types.\\n`,\n );\n process.stdout.write(`${commonName}: New coverage: ${newCoverage}%.\\n`);\n\n insertedExamples += map.typesWithInsertedExamples;\n totalTypes += map.types;\n }\n const newCoverage = roundPercentage(insertedExamples / totalTypes);\n process.stdout.write(`\\n\\nFinal Stats:\\nNew coverage: ${newCoverage}%.\\n`);\n }),\n )\n .command(\n ['extract [ASSEMBLY..]', '$0 [ASSEMBLY..]'],\n 'Extract code snippets from one or more assemblies into language tablets',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to extract from',\n })\n .option('output', {\n type: 'string',\n describe: 'Additional output file where to store translated samples (deprecated, alias for --cache-to)',\n requiresArg: true,\n default: undefined,\n })\n .option('compile', {\n alias: 'c',\n type: 'boolean',\n describe: 'Try compiling (on by default, use --no-compile to switch off)',\n default: true,\n })\n .option('directory', {\n alias: 'd',\n type: 'string',\n describe: 'Working directory (for require() etc)',\n })\n .option('include', {\n alias: 'i',\n type: 'string',\n array: true,\n describe: 'Extract only snippets with given ids',\n default: [],\n })\n .option('infuse', {\n type: 'boolean',\n describe: 'bundle this command with the infuse command',\n default: false,\n })\n .option('fail', {\n alias: 'f',\n type: 'boolean',\n describe: 'Fail if there are compilation errors',\n default: false,\n })\n .option('validate-assemblies', {\n type: 'boolean',\n describe: 'Whether to validate loaded assemblies or not (this can be slow)',\n default: false,\n })\n .option('cache-from', {\n alias: 'C',\n type: 'string',\n // eslint-disable-next-line prettier/prettier\n describe:\n 'Reuse translations from the given tablet file if the snippet and type definitions did not change',\n requiresArg: true,\n default: undefined,\n })\n .option('cache-to', {\n alias: 'o',\n type: 'string',\n describe: 'Append all translated snippets to the given tablet file',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache-to', 'output')\n .option('cache', {\n alias: 'k',\n type: 'string',\n describe: 'Alias for --cache-from and --cache-to together',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache', 'cache-from')\n .conflicts('cache', 'cache-to')\n .option('trim-cache', {\n alias: 'T',\n type: 'boolean',\n describe: 'Remove translations that are not referenced by any of the assemblies anymore from the cache',\n })\n .option('strict', {\n alias: 'S',\n type: 'boolean',\n describe:\n 'Require all code samples compile, and fail if one does not. Strict mode always enables --compile and --fail',\n default: false,\n })\n .options('loose', {\n alias: 'l',\n describe: 'Ignore missing fixtures and literate markdown files instead of failing',\n type: 'boolean',\n })\n .options('compress-tablet', {\n alias: 'z',\n type: 'boolean',\n describe: 'Compress the implicit tablet file',\n default: false,\n })\n .options('compress-cache', {\n type: 'boolean',\n describe: 'Compress the cache-to file',\n default: false,\n })\n .options('cleanup', {\n type: 'boolean',\n describe: 'Clean up temporary directories',\n default: true,\n })\n .option('batch', {\n alias: 'b',\n type: 'number',\n describe: 'Batch size for compiling snippets together (default: 1000 if -b provided, no batching if not)',\n // coerce is only called if the option is present\n coerce: (value) => (value == null ? 1000 : value),\n })\n .conflicts('loose', 'strict')\n .conflicts('loose', 'fail'),\n wrapHandler(async (args) => {\n // `--strict` is short for `--compile --fail`, and we'll override those even if they're set to `false`, such as\n // using `--no-(compile|fail)`, because yargs does not quite give us a better option that does not hurt CX.\n if (args.strict) {\n args.compile = args.c = true;\n args.fail = args.f = true;\n }\n\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n\n const absCacheFrom = fmap(args.cache ?? args['cache-from'], path.resolve);\n const absCacheTo = fmap(args.cache ?? args['cache-to'] ?? args.output, path.resolve);\n\n const extractOptions: ExtractOptions = {\n compilationDirectory: args.directory,\n includeCompilerDiagnostics: !!args.compile,\n validateAssemblies: args['validate-assemblies'],\n only: args.include,\n cacheFromFile: absCacheFrom,\n cacheToFile: absCacheTo,\n trimCache: args['trim-cache'],\n loose: args.loose,\n compressTablet: args['compress-tablet'],\n compressCacheToFile: args['compress-cache'],\n cleanup: args.cleanup,\n batchSize: args.batch,\n };\n\n const result = args.infuse\n ? await extractAndInfuse(absAssemblies, extractOptions)\n : await extractSnippets(absAssemblies, extractOptions);\n\n handleDiagnostics(result.diagnostics, args.fail, result.tablet.count);\n }),\n )\n .command(\n 'transliterate [ASSEMBLY..]',\n '(EXPERIMENTAL) Transliterates the designated assemblies',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n required: true,\n describe: 'Assembly to transliterate',\n })\n .option('language', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Language ID to transliterate to',\n })\n .options('strict', {\n alias: 's',\n conflicts: 'loose',\n describe:\n 'Fail if an example that needs live transliteration fails to compile (which could cause incorrect transpilation results)',\n type: 'boolean',\n })\n .options('loose', {\n alias: 'l',\n conflicts: 'strict',\n describe: 'Ignore missing fixtures and literate markdown files instead of failing',\n type: 'boolean',\n })\n .option('tablet', {\n alias: 't',\n type: 'string',\n describe:\n 'Language tablet containing pre-translated code examples to use (these are generated by the `extract` command)',\n })\n .option('batch', {\n alias: 'b',\n type: 'number',\n describe: 'Batch size for compiling snippets together (default: 1000 if -b provided, no batching if not)',\n // coerce is only called if the option is present\n coerce: (value) => (value == null ? 1000 : value),\n }),\n wrapHandler((args) => {\n const assemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((dir) =>\n path.resolve(process.cwd(), dir),\n );\n const languages =\n args.language.length > 0\n ? args.language\n .map((lang) => lang.toUpperCase())\n .map((lang) => {\n const target = Object.entries(TargetLanguage).find(([k]) => k === lang)?.[1];\n if (target == null) {\n throw new Error(\n `Unknown target language: ${lang}. Expected one of ${Object.keys(TargetLanguage).join(', ')}`,\n );\n }\n return target;\n })\n : Object.values(TargetLanguage);\n return transliterateAssembly(assemblies, languages, args);\n }),\n )\n .command(\n 'trim-cache <TABLET> [ASSEMBLY..]',\n 'Retain only those snippets in the cache which occur in one of the given assemblies',\n (command) =>\n command\n .positional('TABLET', {\n type: 'string',\n required: true,\n describe: 'Language tablet to trim',\n })\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to search',\n })\n .demandOption('TABLET'),\n wrapHandler(async (args) => {\n await trimCache({\n cacheFile: args.TABLET,\n assemblyLocations: args.ASSEMBLY,\n });\n }),\n )\n .command(\n 'coverage [ASSEMBLY..]',\n 'Check the translation coverage of implicit tablets for the given assemblies',\n (command) =>\n command.positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: ['.'],\n describe: 'Assembly or directory to search',\n }),\n wrapHandler(async (args) => {\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n await checkCoverage(absAssemblies);\n }),\n )\n .command(\n 'read <TABLET> [KEY] [LANGUAGE]',\n 'Display snippets in a language tablet file',\n (command) =>\n command\n .positional('TABLET', {\n type: 'string',\n required: true,\n describe: 'Language tablet to read',\n })\n .positional('KEY', {\n type: 'string',\n describe: 'Snippet key to read',\n })\n .positional('LANGUAGE', {\n type: 'string',\n describe: 'Language ID to read',\n })\n .demandOption('TABLET'),\n wrapHandler(async (args) => {\n await readTablet(args.TABLET, args.KEY, args.LANGUAGE);\n }),\n )\n .command(\n 'configure-strict [PACKAGE]',\n \"Enables strict mode for a package's assembly\",\n (command) =>\n command.positional('PACKAGE', {\n type: 'string',\n describe: 'The path to the package to configure',\n required: false,\n default: '.',\n normalize: true,\n }),\n wrapHandler(async (args) => {\n const packageJsonPath = (await fs.stat(args.PACKAGE)).isDirectory()\n ? path.join(args.PACKAGE, 'package.json')\n : args.PACKAGE;\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));\n if (packageJson.jsii == null) {\n console.error(\n `The package in ${args.PACKAGE} does not have a jsii configuration! You can set it up using jsii-config.`,\n );\n process.exitCode = 1;\n return Promise.resolve();\n }\n if (packageJson.jsii.metadata?.jsii?.rosetta?.strict) {\n // Nothing to do - it's already configured, so we assert idempotent success!\n return Promise.resolve();\n }\n const md = (packageJson.jsii.metadata = packageJson.jsii.metadata ?? {});\n const mdJsii = (md.jsii = md.jsii ?? {});\n const mdRosetta = (mdJsii.rosetta = mdJsii.rosetta ?? {});\n mdRosetta.strict = true;\n\n return fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));\n }),\n )\n .demandCommand()\n .help()\n .strict() // Error on wrong command\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n .version(require('../package.json').version)\n .showHelpOnFail(false).argv;\n\n // Evaluating .argv triggers the parsing but the command gets implicitly executed,\n // so we don't need the output.\n Array.isArray(argv);\n}\n\n/**\n * Wrap a command's handler with standard pre- and post-work\n */\nfunction wrapHandler<A extends { verbose?: number }, R>(handler: (x: A) => Promise<R>) {\n return (argv: A) => {\n logging.configure({ level: argv.verbose !== undefined ? argv.verbose : 0 });\n handler(argv).catch((e) => {\n logging.error(e.message);\n logging.error(e.stack);\n process.exitCode = 1;\n });\n };\n}\n\nfunction makeVisitor(args: { python?: boolean; language?: string }) {\n if (args.python != null && args.language == null) {\n args.language = 'python';\n }\n return getVisitorFromLanguage(args.language);\n}\n\nasync function makeFileSource(fileName: string, stdinName: string): Promise<File> {\n if (fileName === '-') {\n return {\n contents: await readStdin(),\n fileName: stdinName,\n };\n }\n return {\n contents: await fs.readFile(fileName, { encoding: 'utf-8' }),\n fileName: fileName,\n };\n}\n\nasync function readStdin(): Promise<string> {\n process.stdin.setEncoding('utf8');\n\n const parts: Buffer[] = [];\n\n return new Promise((resolve, reject) => {\n process.stdin.on('readable', () => {\n const chunk = process.stdin.read();\n if (chunk !== null) {\n parts.push(Buffer.from(chunk));\n }\n });\n\n process.stdin.on('error', reject);\n process.stdin.on('end', () => resolve(Buffer.concat(parts).toString('utf-8')));\n });\n}\n\nfunction handleSingleResult(result: TranslateResult) {\n process.stdout.write(`${result.translation}\\n`);\n\n // For a single result, we always request implicit failure.\n handleDiagnostics(result.diagnostics, 'implicit');\n}\n\n/**\n * Print diagnostics and set exit code\n *\n * 'fail' is whether or not the user passed '--fail' for commands that accept\n * it, or 'implicit' for commands that should always fail. 'implicit' will be\n * treated as 'fail=true, but will not print to the user that the '--fail' is\n * set (because for this particular command that switch does not exist and so it\n * would be confusing).\n */\nfunction handleDiagnostics(diagnostics: readonly RosettaDiagnostic[], fail: boolean | 'implicit', snippetCount = 1) {\n if (fail !== false) {\n // Fail on any diagnostic\n if (diagnostics.length > 0) {\n printDiagnostics(diagnostics, process.stderr, process.stderr.isTTY);\n logging.error(\n [\n `${diagnostics.length} diagnostics encountered in ${snippetCount} snippets`,\n ...(fail === true ? [\"(running with '--fail')\"] : []),\n ].join(' '),\n );\n process.exitCode = 1;\n }\n\n return;\n }\n\n // Otherwise fail only on strict diagnostics. If we have strict diagnostics, print only those\n // (so it's very clear what is failing the build), otherwise print everything.\n const strictDiagnostics = diagnostics.filter((diag) => diag.isFromStrictAssembly);\n if (strictDiagnostics.length > 0) {\n printDiagnostics(strictDiagnostics, process.stderr, process.stderr.isTTY);\n const remaining = diagnostics.length - strictDiagnostics.length;\n logging.warn(\n [\n `${strictDiagnostics.length} diagnostics from assemblies with 'strict' mode on`,\n ...(remaining > 0 ? [`(and ${remaining} more non-strict diagnostics)`] : []),\n ].join(' '),\n );\n process.exitCode = 1;\n return;\n }\n\n if (diagnostics.length > 0) {\n printDiagnostics(diagnostics, process.stderr, process.stderr.isTTY);\n logging.warn(`${diagnostics.length} diagnostics encountered in ${snippetCount} snippets`);\n }\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(10000 * num) / 100;\n}\n\nmain().catch((cause) => {\n console.error(cause);\n process.exitCode = -1;\n});\n"]}
|
|
1
|
+
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";;AAAA,gCAA8B;AAE9B,qCAAyC;AACzC,kCAAkC;AAClC,+BAA+B;AAE/B,gDAAuD;AACvD,kDAAoD;AACpD,gDAAuF;AACvF,8CAA0E;AAC1E,0CAA6C;AAC7C,4DAAiE;AACjE,sDAAkD;AAClD,mCAAqG;AACrG,2CAAqE;AACrE,qCAAqC;AACrC,uCAAyD;AACzD,iCAAsD;AAEtD,KAAK,UAAU,IAAI;IACjB,MAAM,IAAA,sCAA4B,GAAE,CAAC;IAErC,MAAM,IAAI,GAAG,KAAK;SACf,KAAK,CAAC,iBAAiB,CAAC;SACxB,MAAM,CAAC,SAAS,EAAE;QACjB,KAAK,EAAE,GAAG;QACV,IAAI,EAAE,SAAS;QACf,IAAI,EAAE,4BAA4B;QAClC,KAAK,EAAE,IAAI;QACX,OAAO,EAAE,CAAC;KACX,CAAC;SACD,OAAO,CACN,cAAc,EACd,4BAA4B,EAC5B,CAAC,OAAO,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/run';\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport * as yargs from 'yargs';\n\nimport { translateMarkdown } from './commands/convert';\nimport { checkCoverage } from './commands/coverage';\nimport { extractAndInfuse, extractSnippets, ExtractOptions } from './commands/extract';\nimport { infuse, DEFAULT_INFUSION_RESULTS_NAME } from './commands/infuse';\nimport { readTablet } from './commands/read';\nimport { transliterateAssembly } from './commands/transliterate';\nimport { trimCache } from './commands/trim-cache';\nimport { TranslateResult, translateTypeScript, RosettaDiagnostic, formatTimingTable } from './index';\nimport { getVisitorFromLanguage, TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { emitSupportPolicyInformation } from './support';\nimport { File, fmap, printDiagnostics } from './util';\n\nasync function main() {\n await emitSupportPolicyInformation();\n\n const argv = yargs\n .usage('$0 <cmd> [args]')\n .option('verbose', {\n alias: 'v',\n type: 'boolean',\n desc: 'Increase logging verbosity',\n count: true,\n default: 0,\n })\n .command(\n 'snippet FILE',\n 'Translate a single snippet',\n (command) =>\n command\n .positional('FILE', {\n type: 'string',\n describe: 'The file to translate (leave out for stdin)',\n })\n .option('language', {\n type: 'string',\n describe: 'Language ID to transliterate to',\n choices: Array.from(new Set(Object.values(TargetLanguage))),\n })\n .option('python', {\n alias: 'p',\n boolean: true,\n deprecated: true,\n description: 'Translate snippets to Python. Use --language python instead.',\n }),\n wrapHandler(async (args) => {\n const result = translateTypeScript(await makeFileSource(args.FILE ?? '-', 'stdin.ts'), makeVisitor(args));\n handleSingleResult(result);\n }),\n )\n .command(\n 'markdown FILE',\n 'Translate a MarkDown file',\n (command) =>\n command\n .positional('FILE', {\n type: 'string',\n describe: 'The file to translate (leave out for stdin)',\n })\n .option('language', {\n type: 'string',\n describe: 'Language ID to transliterate to',\n choices: Array.from(new Set(Object.values(TargetLanguage))),\n })\n .option('python', {\n alias: 'p',\n boolean: true,\n deprecated: true,\n description: 'Translate snippets to Python. Use --language python instead.',\n }),\n wrapHandler(async (args) => {\n const result = translateMarkdown(await makeFileSource(args.FILE ?? '-', 'stdin.md'), makeVisitor(args));\n handleSingleResult(result);\n }),\n )\n .command(\n 'infuse [ASSEMBLY..]',\n '(EXPERIMENTAL) mutates one or more assemblies by adding documentation examples to top-level types',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to mutate',\n })\n .option('log-file', {\n alias: 'l',\n type: 'string',\n describe: 'Output file to store logging results. Ignored if -log is not true',\n default: DEFAULT_INFUSION_RESULTS_NAME,\n })\n .option('cache-from', {\n alias: 'C',\n type: 'string',\n // eslint-disable-next-line prettier/prettier\n describe:\n 'Reuse translations from the given tablet file if the snippet and type definitions did not change',\n requiresArg: true,\n default: undefined,\n })\n .option('cache-to', {\n alias: 'o',\n type: 'string',\n describe: 'Append all translated snippets to the given tablet file',\n requiresArg: true,\n default: undefined,\n })\n .option('cache', {\n alias: 'k',\n type: 'string',\n describe: 'Alias for --cache-from and --cache-to together',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache', 'cache-from')\n .conflicts('cache', 'cache-to'),\n wrapHandler(async (args) => {\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n const absCacheFrom = fmap(args.cache ?? args['cache-from'], path.resolve);\n const absCacheTo = fmap(args.cache ?? args['cache-to'], path.resolve);\n const result = await infuse(absAssemblies, {\n logFile: args['log-file'],\n cacheToFile: absCacheTo,\n cacheFromFile: absCacheFrom,\n });\n\n let totalTypes = 0;\n let insertedExamples = 0;\n for (const [directory, map] of Object.entries(result.coverageResults)) {\n const commonName = directory.split('/').pop()!;\n const newCoverage = roundPercentage(map.typesWithInsertedExamples / map.types);\n process.stdout.write(\n `${commonName}: Added ${map.typesWithInsertedExamples} examples to ${map.types} types.\\n`,\n );\n process.stdout.write(`${commonName}: New coverage: ${newCoverage}%.\\n`);\n\n insertedExamples += map.typesWithInsertedExamples;\n totalTypes += map.types;\n }\n const newCoverage = roundPercentage(insertedExamples / totalTypes);\n process.stdout.write(`\\n\\nFinal Stats:\\nNew coverage: ${newCoverage}%.\\n`);\n }),\n )\n .command(\n ['extract [ASSEMBLY..]', '$0 [ASSEMBLY..]'],\n 'Extract code snippets from one or more assemblies into language tablets',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to extract from',\n })\n .option('output', {\n type: 'string',\n describe: 'Additional output file where to store translated samples (deprecated, alias for --cache-to)',\n requiresArg: true,\n default: undefined,\n })\n .option('compile', {\n alias: 'c',\n type: 'boolean',\n describe: 'Try compiling (on by default, use --no-compile to switch off)',\n default: true,\n })\n .option('directory', {\n alias: 'd',\n type: 'string',\n describe: 'Working directory (for require() etc)',\n })\n .option('include', {\n alias: 'i',\n type: 'string',\n array: true,\n describe: 'Extract only snippets with given ids',\n default: [],\n })\n .option('infuse', {\n type: 'boolean',\n describe: 'bundle this command with the infuse command',\n default: false,\n })\n .option('fail', {\n alias: 'f',\n type: 'boolean',\n describe: 'Fail if there are compilation errors',\n default: false,\n })\n .option('validate-assemblies', {\n type: 'boolean',\n describe: 'Whether to validate loaded assemblies or not (this can be slow)',\n default: false,\n })\n .option('cache-from', {\n alias: 'C',\n type: 'string',\n // eslint-disable-next-line prettier/prettier\n describe:\n 'Reuse translations from the given tablet file if the snippet and type definitions did not change',\n requiresArg: true,\n default: undefined,\n })\n .option('cache-to', {\n alias: 'o',\n type: 'string',\n describe: 'Append all translated snippets to the given tablet file',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache-to', 'output')\n .option('cache', {\n alias: 'k',\n type: 'string',\n describe: 'Alias for --cache-from and --cache-to together',\n requiresArg: true,\n default: undefined,\n })\n .conflicts('cache', 'cache-from')\n .conflicts('cache', 'cache-to')\n .option('trim-cache', {\n alias: 'T',\n type: 'boolean',\n describe: 'Remove translations that are not referenced by any of the assemblies anymore from the cache',\n })\n .option('strict', {\n alias: 'S',\n type: 'boolean',\n describe:\n 'Require all code samples compile, and fail if one does not. Strict mode always enables --compile and --fail',\n default: false,\n })\n .options('loose', {\n alias: 'l',\n describe: 'Ignore missing fixtures and literate markdown files instead of failing',\n type: 'boolean',\n })\n .options('compress-tablet', {\n alias: 'z',\n type: 'boolean',\n describe: 'Compress the implicit tablet file',\n default: false,\n })\n .options('compress-cache', {\n type: 'boolean',\n describe: 'Compress the cache-to file',\n default: false,\n })\n .options('cleanup', {\n type: 'boolean',\n describe: 'Clean up temporary directories',\n default: true,\n })\n .option('batch', {\n alias: 'b',\n type: 'number',\n describe: 'Batch size for compiling snippets together (default: 1000 if -b provided, no batching if not)',\n // coerce is only called if the option is present\n coerce: (value) => (value == null ? 1000 : value),\n })\n .conflicts('loose', 'strict')\n .conflicts('loose', 'fail'),\n wrapHandler(async (args) => {\n // `--strict` is short for `--compile --fail`, and we'll override those even if they're set to `false`, such as\n // using `--no-(compile|fail)`, because yargs does not quite give us a better option that does not hurt CX.\n if (args.strict) {\n args.compile = args.c = true;\n args.fail = args.f = true;\n }\n\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n\n const absCacheFrom = fmap(args.cache ?? args['cache-from'], path.resolve);\n const absCacheTo = fmap(args.cache ?? args['cache-to'] ?? args.output, path.resolve);\n\n const extractOptions: ExtractOptions = {\n compilationDirectory: args.directory,\n includeCompilerDiagnostics: !!args.compile,\n validateAssemblies: args['validate-assemblies'],\n only: args.include,\n cacheFromFile: absCacheFrom,\n cacheToFile: absCacheTo,\n trimCache: args['trim-cache'],\n loose: args.loose,\n compressTablet: args['compress-tablet'],\n compressCacheToFile: args['compress-cache'],\n cleanup: args.cleanup,\n batchSize: args.batch,\n };\n\n const result = args.infuse\n ? await extractAndInfuse(absAssemblies, extractOptions)\n : await extractSnippets(absAssemblies, extractOptions);\n\n handleDiagnostics(result.diagnostics, args.fail, result.tablet.count);\n\n // Print timing table at the very end\n if (result.timings && result.timings.length > 0) {\n logging.warn(formatTimingTable(result.timings));\n }\n }),\n )\n .command(\n 'transliterate [ASSEMBLY..]',\n '(EXPERIMENTAL) Transliterates the designated assemblies',\n (command) =>\n command\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n required: true,\n describe: 'Assembly to transliterate',\n })\n .option('language', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Language ID to transliterate to',\n })\n .options('strict', {\n alias: 's',\n conflicts: 'loose',\n describe:\n 'Fail if an example that needs live transliteration fails to compile (which could cause incorrect transpilation results)',\n type: 'boolean',\n })\n .options('loose', {\n alias: 'l',\n conflicts: 'strict',\n describe: 'Ignore missing fixtures and literate markdown files instead of failing',\n type: 'boolean',\n })\n .option('tablet', {\n alias: 't',\n type: 'string',\n describe:\n 'Language tablet containing pre-translated code examples to use (these are generated by the `extract` command)',\n })\n .option('batch', {\n alias: 'b',\n type: 'number',\n describe: 'Batch size for compiling snippets together (default: 1000 if -b provided, no batching if not)',\n // coerce is only called if the option is present\n coerce: (value) => (value == null ? 1000 : value),\n }),\n wrapHandler((args) => {\n const assemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((dir) =>\n path.resolve(process.cwd(), dir),\n );\n const languages =\n args.language.length > 0\n ? args.language\n .map((lang) => lang.toUpperCase())\n .map((lang) => {\n const target = Object.entries(TargetLanguage).find(([k]) => k === lang)?.[1];\n if (target == null) {\n throw new Error(\n `Unknown target language: ${lang}. Expected one of ${Object.keys(TargetLanguage).join(', ')}`,\n );\n }\n return target;\n })\n : Object.values(TargetLanguage);\n return transliterateAssembly(assemblies, languages, args);\n }),\n )\n .command(\n 'trim-cache <TABLET> [ASSEMBLY..]',\n 'Retain only those snippets in the cache which occur in one of the given assemblies',\n (command) =>\n command\n .positional('TABLET', {\n type: 'string',\n required: true,\n describe: 'Language tablet to trim',\n })\n .positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: [],\n describe: 'Assembly or directory to search',\n })\n .demandOption('TABLET'),\n wrapHandler(async (args) => {\n await trimCache({\n cacheFile: args.TABLET,\n assemblyLocations: args.ASSEMBLY,\n });\n }),\n )\n .command(\n 'coverage [ASSEMBLY..]',\n 'Check the translation coverage of implicit tablets for the given assemblies',\n (command) =>\n command.positional('ASSEMBLY', {\n type: 'string',\n array: true,\n default: ['.'],\n describe: 'Assembly or directory to search',\n }),\n wrapHandler(async (args) => {\n const absAssemblies = (args.ASSEMBLY.length > 0 ? args.ASSEMBLY : ['.']).map((x) => path.resolve(x));\n await checkCoverage(absAssemblies);\n }),\n )\n .command(\n 'read <TABLET> [KEY] [LANGUAGE]',\n 'Display snippets in a language tablet file',\n (command) =>\n command\n .positional('TABLET', {\n type: 'string',\n required: true,\n describe: 'Language tablet to read',\n })\n .positional('KEY', {\n type: 'string',\n describe: 'Snippet key to read',\n })\n .positional('LANGUAGE', {\n type: 'string',\n describe: 'Language ID to read',\n })\n .demandOption('TABLET'),\n wrapHandler(async (args) => {\n await readTablet(args.TABLET, args.KEY, args.LANGUAGE);\n }),\n )\n .command(\n 'configure-strict [PACKAGE]',\n \"Enables strict mode for a package's assembly\",\n (command) =>\n command.positional('PACKAGE', {\n type: 'string',\n describe: 'The path to the package to configure',\n required: false,\n default: '.',\n normalize: true,\n }),\n wrapHandler(async (args) => {\n const packageJsonPath = (await fs.stat(args.PACKAGE)).isDirectory()\n ? path.join(args.PACKAGE, 'package.json')\n : args.PACKAGE;\n const packageJson = JSON.parse(await fs.readFile(packageJsonPath, 'utf-8'));\n if (packageJson.jsii == null) {\n console.error(\n `The package in ${args.PACKAGE} does not have a jsii configuration! You can set it up using jsii-config.`,\n );\n process.exitCode = 1;\n return Promise.resolve();\n }\n if (packageJson.jsii.metadata?.jsii?.rosetta?.strict) {\n // Nothing to do - it's already configured, so we assert idempotent success!\n return Promise.resolve();\n }\n const md = (packageJson.jsii.metadata = packageJson.jsii.metadata ?? {});\n const mdJsii = (md.jsii = md.jsii ?? {});\n const mdRosetta = (mdJsii.rosetta = mdJsii.rosetta ?? {});\n mdRosetta.strict = true;\n\n return fs.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));\n }),\n )\n .demandCommand()\n .help()\n .strict() // Error on wrong command\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n .version(require('../package.json').version)\n .showHelpOnFail(false).argv;\n\n // Evaluating .argv triggers the parsing but the command gets implicitly executed,\n // so we don't need the output.\n Array.isArray(argv);\n}\n\n/**\n * Wrap a command's handler with standard pre- and post-work\n */\nfunction wrapHandler<A extends { verbose?: number }, R>(handler: (x: A) => Promise<R>) {\n return (argv: A) => {\n logging.configure({ level: argv.verbose !== undefined ? argv.verbose : 0 });\n handler(argv).catch((e) => {\n logging.error(e.message);\n logging.error(e.stack);\n process.exitCode = 1;\n });\n };\n}\n\nfunction makeVisitor(args: { python?: boolean; language?: string }) {\n if (args.python != null && args.language == null) {\n args.language = 'python';\n }\n return getVisitorFromLanguage(args.language);\n}\n\nasync function makeFileSource(fileName: string, stdinName: string): Promise<File> {\n if (fileName === '-') {\n return {\n contents: await readStdin(),\n fileName: stdinName,\n };\n }\n return {\n contents: await fs.readFile(fileName, { encoding: 'utf-8' }),\n fileName: fileName,\n };\n}\n\nasync function readStdin(): Promise<string> {\n process.stdin.setEncoding('utf8');\n\n const parts: Buffer[] = [];\n\n return new Promise((resolve, reject) => {\n process.stdin.on('readable', () => {\n const chunk = process.stdin.read();\n if (chunk !== null) {\n parts.push(Buffer.from(chunk));\n }\n });\n\n process.stdin.on('error', reject);\n process.stdin.on('end', () => resolve(Buffer.concat(parts).toString('utf-8')));\n });\n}\n\nfunction handleSingleResult(result: TranslateResult) {\n process.stdout.write(`${result.translation}\\n`);\n\n // For a single result, we always request implicit failure.\n handleDiagnostics(result.diagnostics, 'implicit');\n}\n\n/**\n * Print diagnostics and set exit code\n *\n * 'fail' is whether or not the user passed '--fail' for commands that accept\n * it, or 'implicit' for commands that should always fail. 'implicit' will be\n * treated as 'fail=true, but will not print to the user that the '--fail' is\n * set (because for this particular command that switch does not exist and so it\n * would be confusing).\n */\nfunction handleDiagnostics(diagnostics: readonly RosettaDiagnostic[], fail: boolean | 'implicit', snippetCount = 1) {\n if (fail !== false) {\n // Fail on any diagnostic\n if (diagnostics.length > 0) {\n printDiagnostics(diagnostics, process.stderr, process.stderr.isTTY);\n logging.error(\n [\n `${diagnostics.length} diagnostics encountered in ${snippetCount} snippets`,\n ...(fail === true ? [\"(running with '--fail')\"] : []),\n ].join(' '),\n );\n process.exitCode = 1;\n }\n\n return;\n }\n\n // Otherwise fail only on strict diagnostics. If we have strict diagnostics, print only those\n // (so it's very clear what is failing the build), otherwise print everything.\n const strictDiagnostics = diagnostics.filter((diag) => diag.isFromStrictAssembly);\n if (strictDiagnostics.length > 0) {\n printDiagnostics(strictDiagnostics, process.stderr, process.stderr.isTTY);\n const remaining = diagnostics.length - strictDiagnostics.length;\n logging.warn(\n [\n `${strictDiagnostics.length} diagnostics from assemblies with 'strict' mode on`,\n ...(remaining > 0 ? [`(and ${remaining} more non-strict diagnostics)`] : []),\n ].join(' '),\n );\n process.exitCode = 1;\n return;\n }\n\n if (diagnostics.length > 0) {\n printDiagnostics(diagnostics, process.stderr, process.stderr.isTTY);\n logging.warn(`${diagnostics.length} diagnostics encountered in ${snippetCount} snippets`);\n }\n}\n\n/**\n * Rounds a decimal number to two decimal points.\n * The function is useful for fractions that need to be outputted as percentages.\n */\nfunction roundPercentage(num: number): number {\n return Math.round(10000 * num) / 100;\n}\n\nmain().catch((cause) => {\n console.error(cause);\n process.exitCode = -1;\n});\n"]}
|
package/lib/rosetta-reader.js
CHANGED
|
@@ -166,12 +166,12 @@ class RosettaTabletReader {
|
|
|
166
166
|
const extracted = this.extractedSnippets.get((0, key_1.snippetKey)(source));
|
|
167
167
|
if (extracted !== undefined) {
|
|
168
168
|
const snippet = this.translator.translate(extracted, this.options.targetLanguages);
|
|
169
|
-
this.liveTablet.
|
|
169
|
+
this.liveTablet.addTranslations(snippet);
|
|
170
170
|
return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);
|
|
171
171
|
}
|
|
172
172
|
// Try to live-convert it as-is.
|
|
173
173
|
const snippet = this.translator.translate(source, this.options.targetLanguages);
|
|
174
|
-
this.liveTablet.
|
|
174
|
+
this.liveTablet.addTranslations(snippet);
|
|
175
175
|
return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);
|
|
176
176
|
}
|
|
177
177
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA4G;AAE5G,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;AACnB,uCAA2C;AAC3C,+CAAgE;AAChE,2CAAyC;AACzC,iCAAoE;AAEpE,IAAY,kBAeX;AAfD,WAAY,kBAAkB;IAC5B;;OAEG;IACH,2CAAqB,CAAA;IAErB;;OAEG;IACH,6CAAuB,CAAA;IAEvB;;OAEG;IACH,mCAAa,CAAA;AACf,CAAC,EAfW,kBAAkB,kCAAlB,kBAAkB,QAe7B;AAsCD;;;;;;;;;;;GAWG;AACH,MAAa,mBAAmB;IAC9B;;OAEG;IACI,MAAM,KAAK,yBAAyB;QACzC,OAAO,wCAA2B,CAAC;IACrC,CAAC;IAiBD,YAAoC,UAA0B,EAAE;QAA5B,YAAO,GAAP,OAAO,CAAqB;QAfhE;;;;;WAKG;QACa,eAAU,GAAG,IAAI,wBAAc,EAAE,CAAC;QAEjC,kBAAa,GAAqB,EAAE,CAAC;QACrC,sBAAiB,GAAG,IAAI,GAAG,EAA6B,CAAC;QAOxE,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;QAC7B,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,kBAAkB,CAAC,QAAQ,CAAC;QAC9E,IAAI,CAAC,UAAU,GAAG,IAAI,sBAAU,CAAC,OAAO,CAAC,0B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AED;;;OAGG;IACK,gBAAgB,CAAC,WAAoC,EAAE,gBAAyB;QACtF,IAAI,CAAC,gBAAgB,IAAI,WAAW,EAAE,UAAU,KAAK,KAAK,EAAE,CAAC;YAC3D,OAAO,WAAW,CAAC;QACrB,CAAC;QACD,MAAM,OAAO,GAAG,IAAA,mBAAY,EAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QACnD,MAAM,UAAU,GAAG,gFAAgF,CAAC;QACpG,OAAO;YACL,GAAG,WAAW;YACd,MAAM,EAAE,GAAG,OAAO,IAAI,UAAU,KAAK,WAAW,CAAC,MAAM,EAAE;SAC1D,CAAC;IACJ,CAAC;CACF;AAnPD,kDAmPC;AAED,SAAS,EAAE,CAAC,CAAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation, SUPPORTED_ASSEMBLY_FEATURES } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * The assembly features that the current version of `jsii-rosetta` supports.\n */\n public static get supportedAssemblyFeatures(): spec.JsiiFeature[] {\n return SUPPORTED_ASSEMBLY_FEATURES;\n }\n\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addSnippets(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addSnippets(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
|
|
1
|
+
{"version":3,"file":"rosetta-reader.js","sourceRoot":"","sources":["../src/rosetta-reader.ts"],"names":[],"mappings":";;;AAEA,kDAA4G;AAE5G,qCAAqC;AACrC,kDAAwD;AACxD,oEAAgE;AAChE,0FAAqF;AAErF,uCAMmB;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AAc;IACxB,OAAO,CAAC,CAAC;AACX,CAAC;AAED;;;;GAIG;AACH,MAAa,OAAQ,SAAQ,mBAAmB;CAAG;AAAnD,0BAAmD","sourcesContent":["import * as spec from '@jsii/spec';\n\nimport { allTypeScriptSnippets, guessTabletLocation, SUPPORTED_ASSEMBLY_FEATURES } from './jsii/assemblies';\nimport { TargetLanguage } from './languages';\nimport * as logging from './logging';\nimport { transformMarkdown } from './markdown/markdown';\nimport { MarkdownRenderer } from './markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from './markdown/replace-typescript-transform';\nimport { CodeBlock } from './markdown/types';\nimport {\n SnippetParameters,\n TypeScriptSnippet,\n updateParameters,\n ApiLocation,\n typeScriptSnippetFromSource,\n} from './snippet';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, Translation } from './tablets/tablets';\nimport { Translator } from './translate';\nimport { commentToken, pathExists, printDiagnostics } from './util';\n\nexport enum UnknownSnippetMode {\n /**\n * Return the snippet as given (untranslated)\n */\n VERBATIM = 'verbatim',\n\n /**\n * Live-translate the snippet as best as we can\n */\n TRANSLATE = 'translate',\n\n /**\n * Throw an error if this occurs\n */\n FAIL = 'fail',\n}\n\nexport interface RosettaOptions {\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.VERBATIM\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n\n /**\n * Target languages to use for live conversion\n *\n * @default All languages\n */\n readonly targetLanguages?: readonly TargetLanguage[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Whether this Rosetta should operate in \"loose\" mode, where missing literate\n * source files and missing fixtures are ignored instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Adds a disclaimer to start of snippet if it did not compile.\n *\n * @default false\n */\n readonly prefixDisclaimer?: boolean;\n}\n\n/**\n * Entry point class for consumers of Rosetta tablets (primarily: pacmak)\n *\n * Rosetta can work in one of two modes:\n *\n * 1. Live translation of snippets.\n * 2. Read translations from a pre-translated tablet (prepared using `jsii-rosetta extract` command).\n *\n * The second method affords more control over the precise circumstances of\n * sample compilation and is recommended, but the first method will do\n * when the second one is not necessary.\n */\nexport class RosettaTabletReader {\n /**\n * The assembly features that the current version of `jsii-rosetta` supports.\n */\n public static get supportedAssemblyFeatures(): spec.JsiiFeature[] {\n return SUPPORTED_ASSEMBLY_FEATURES;\n }\n\n /**\n * Newly translated samples\n *\n * In case live translation has been enabled, all samples that have been translated on-the-fly\n * are added to this tablet.\n */\n public readonly liveTablet = new LanguageTablet();\n\n private readonly loadedTablets: LanguageTablet[] = [];\n private readonly extractedSnippets = new Map<string, TypeScriptSnippet>();\n private readonly translator: Translator;\n private readonly loose: boolean;\n private readonly unknownSnippets: UnknownSnippetMode;\n private readonly _prefixDisclaimer: boolean;\n\n public constructor(private readonly options: RosettaOptions = {}) {\n this.loose = !!options.loose;\n this.unknownSnippets = options.unknownSnippets ?? UnknownSnippetMode.VERBATIM;\n this.translator = new Translator(options.includeCompilerDiagnostics ?? false);\n this._prefixDisclaimer = options.prefixDisclaimer ?? false;\n }\n\n /**\n * Diagnostics encountered while doing live translation\n */\n public get diagnostics() {\n return this.translator.diagnostics;\n }\n\n /**\n * Load a tablet as a source for translateable snippets\n *\n * Note: the snippets loaded from this tablet will NOT be validated for\n * their fingerprints or translator versions! If a matching snippet is found\n * in the tablet, it will always be returned, whether or not it is stale.\n */\n public async loadTabletFromFile(tabletFile: string) {\n const tablet = new LanguageTablet();\n await tablet.load(tabletFile);\n this.addTablet(tablet);\n }\n\n /**\n * Directly add a tablet to the list of tablets to load translations from\n */\n public addTablet(tablet: LanguageTablet) {\n this.loadedTablets.push(tablet);\n }\n\n /**\n * Add an assembly\n *\n * If a default tablet file is found in the assembly's directory, it will be\n * loaded (and assumed to contain a complete list of translated snippets for\n * this assembly already).\n *\n * Otherwise, if live conversion is enabled, the snippets in the assembly\n * become available for live translation later. This is necessary because we probably\n * need to fixturize snippets for successful compilation, and the information\n * pacmak sends our way later on is not going to be enough to do that.\n */\n public async addAssembly(assembly: spec.Assembly, assemblyDir: string) {\n const defaultTablet = guessTabletLocation(assemblyDir);\n if (await pathExists(defaultTablet)) {\n try {\n await this.loadTabletFromFile(defaultTablet);\n return;\n } catch (e: any) {\n logging.warn(`Error loading ${defaultTablet}: ${e.message}. Skipped.`);\n }\n }\n\n // Inventarize the snippets from this assembly, but only if there's a chance\n // we're going to need them.\n if (this.unknownSnippets === UnknownSnippetMode.TRANSLATE) {\n for (const tsnip of await allTypeScriptSnippets([{ assembly, directory: assemblyDir }], this.loose)) {\n this.extractedSnippets.set(snippetKey(tsnip), tsnip);\n }\n }\n }\n\n /**\n * Translate the given snippet for the given target language\n *\n * This will either:\n *\n * - Find an existing translation in a tablet and return that, if available.\n * - Otherwise, find a fixturized version of this snippet in an assembly that\n * was loaded beforehand, and translate it on-the-fly. Finding the fixture\n * will be based on the snippet key, which consists of a hash of the\n * visible source and the API location.\n * - Otherwise, translate the snippet as-is (without fixture information).\n *\n * This will do and store a full conversion of the given snippet, even if it only\n * returns one language. Subsequent retrievals for the same snippet in other\n * languages will reuse the translation from cache.\n *\n * If you are calling this for the side effect of adding translations to the live\n * tablet, you only need to do that for one language.\n */\n public translateSnippet(source: TypeScriptSnippet, targetLang: TargetLanguage): Translation | undefined {\n // Look for it in loaded tablets (or previous conversions)\n for (const tab of this.allTablets) {\n const ret = tab.lookup(source, targetLang);\n if (ret !== undefined) {\n return this.prefixDisclaimer(ret, this._prefixDisclaimer);\n }\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.VERBATIM) {\n return this.prefixDisclaimer(\n {\n language: targetLang,\n source: source.visibleSource,\n },\n this._prefixDisclaimer,\n );\n }\n\n if (this.unknownSnippets === UnknownSnippetMode.FAIL) {\n const message = [\n 'The following snippet was not found in any of the loaded tablets:',\n source.visibleSource,\n `Location: ${JSON.stringify(source.location)}`,\n `Language: ${targetLang}`,\n ].join('\\n');\n throw new Error(message);\n }\n\n if (this.options.targetLanguages && !this.options.targetLanguages.includes(targetLang)) {\n throw new Error(\n `Rosetta configured for live conversion to ${this.options.targetLanguages.join(\n ', ',\n )}, but requested ${targetLang}`,\n );\n }\n\n // See if we can find a fixturized version of this snippet. If so, use that do the live\n // conversion.\n const extracted = this.extractedSnippets.get(snippetKey(source));\n if (extracted !== undefined) {\n const snippet = this.translator.translate(extracted, this.options.targetLanguages);\n this.liveTablet.addTranslations(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n // Try to live-convert it as-is.\n const snippet = this.translator.translate(source, this.options.targetLanguages);\n this.liveTablet.addTranslations(snippet);\n return this.prefixDisclaimer(snippet.get(targetLang), this._prefixDisclaimer);\n }\n\n /**\n * Translate a snippet found in the \"@ example\" section of a jsii assembly\n *\n * Behaves exactly like `translateSnippet`, so see that method for documentation.\n */\n public translateExample(\n apiLocation: ApiLocation,\n example: string,\n targetLang: TargetLanguage,\n strict: boolean,\n compileDirectory = process.cwd(),\n ): Translation {\n const location = { api: apiLocation, field: { field: 'example' } } as const;\n\n const snippet = typeScriptSnippetFromSource(example, location, strict, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n });\n\n const translated = this.translateSnippet(snippet, targetLang);\n\n return translated ?? { language: 'typescript', source: example };\n }\n\n /**\n * Translate all TypeScript snippets found in a block of Markdown text\n *\n * For each snippet, behaves exactly like `translateSnippet`, so see that\n * method for documentation.\n */\n public translateSnippetsInMarkdown(\n apiLocation: ApiLocation,\n markdown: string,\n targetLang: TargetLanguage,\n strict: boolean,\n translationToCodeBlock: (x: Translation) => CodeBlock = id,\n compileDirectory = process.cwd(),\n ): string {\n return transformMarkdown(\n markdown,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(apiLocation, strict, (tsSnip) => {\n const translated = this.translateSnippet(\n updateParameters(tsSnip, {\n [SnippetParameters.$COMPILATION_DIRECTORY]: compileDirectory,\n }),\n targetLang,\n );\n if (!translated) {\n return undefined;\n }\n\n return translationToCodeBlock(translated);\n }),\n );\n }\n\n public printDiagnostics(stream: NodeJS.WritableStream, colors = true) {\n printDiagnostics(this.diagnostics, stream, colors);\n }\n\n public get hasErrors() {\n return this.diagnostics.some((d) => d.isError);\n }\n\n private get allTablets(): LanguageTablet[] {\n return [...this.loadedTablets, this.liveTablet];\n }\n\n /**\n * Adds a disclaimer to the front of the example if the prefixDisclaimer\n * flag is set and we know it does not compile.\n */\n private prefixDisclaimer(translation: Translation | undefined, prefixDisclaimer: boolean): Translation | undefined {\n if (!prefixDisclaimer || translation?.didCompile !== false) {\n return translation;\n }\n const comment = commentToken(translation.language);\n const disclaimer = 'Example automatically generated from non-compiling source. May contain errors.';\n return {\n ...translation,\n source: `${comment} ${disclaimer}\\n${translation.source}`,\n };\n }\n}\n\nfunction id(x: Translation) {\n return x;\n}\n\n/**\n * Backwards compatibility\n *\n * @deprecated use RosettaTabletReader instead\n */\nexport class Rosetta extends RosettaTabletReader {}\n"]}
|