jsii-rosetta 5.9.20 → 5.9.21

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.
@@ -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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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 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"]}
1
+ {"version":3,"file":"fingerprinting.js","sourceRoot":"","sources":["../../src/jsii/fingerprinting.ts"],"names":[],"mappings":";;;AAAA,sCAAsC;AACtC,8BAA8B;AAC9B,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,IA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,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IAEO,QAAQ,CAAC,GAAW;QAC1B,MAAM,YAAY,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACzD,CAAC;CACF;AArJD,8CAqJC;AAED,SAAS,YAAY,CAA6B,EAAO;IACvD,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,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,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,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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5F,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, 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"]}
@@ -141,12 +141,16 @@ class RosettaTranslator {
141
141
  }
142
142
  }
143
143
  const fingerprinted = result.translatedSnippets.map((snippet) => snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())));
144
+ if (process.env.DEBUG_TYPE_FINGERPRINTS) {
145
+ this.fingerprinter.writeDebugFile(process.env.DEBUG_TYPE_FINGERPRINTS);
146
+ }
144
147
  if (options?.addToTablet ?? true) {
145
148
  this.tablet.addSnippets(...fingerprinted);
146
149
  }
147
150
  return {
148
151
  translatedSnippets: fingerprinted,
149
152
  diagnostics: result.diagnostics,
153
+ timings: result.timings,
150
154
  };
151
155
  }
152
156
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rosetta-translator.js","sourceRoot":"","sources":["../src/rosetta-translator.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AAGzC,0DAA0D;AAC1D,2CAA+C;AAC/C,qCAAqC;AACrC,uCAA8D;AAC9D,iEAKgC;AAChC,uCAA2C;AAC3C,+CAAsE;AACtE,mDAAmE;AAoCnE;;;;;GAKG;AACH,MAAa,iBAAiB;IAc5B,YAAmB,UAAoC,EAAE;QAbzD;;;;WAIG;QACa,WAAM,GAAG,IAAI,wBAAc,EAAE,CAAC;QAE9B,UAAK,GAAG,IAAI,wBAAc,EAAE,CAAC;QAO3C,IAAI,CAAC,aAAa,GAAG,IAAI,kCAAiB,CAAC,OAAO,EAAE,UAAU,IAAI,EAAE,CAAC,CAAC;QACtE,IAAI,CAAC,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,IAAI,KAAK,CAAC;QAC9E,IAAI,CAAC,sBAAsB,GAAG,OAAO,CAAC,sBAAsB,IAAI,KAAK,CAAC;IACxE,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,SAAS,CAAC,QAAgB;QACrC,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC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AC7D,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,IAAI,CAAC,EAAE,OAAO,KAAK,UAAU,CAAC,OAAO,CAC/F,CAAC;IACF,MAAM,UAAU,GAAG,aAAa,CAAC,cAAc,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC,KAAK,SAAS,CAAC,OAAO,CAAC,eAAe,CAAC;IAClH,MAAM,iBAAiB,GAAG,YAAY,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC;IAExE,IAAI,WAAW,IAAI,eAAe,IAAI,UAAU,IAAI,iBAAiB,EAAE,CAAC;QACtE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;IAChH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC7D,CAAC;AAcD,SAAS,SAAS,CAAC,OAA0B;IAC3C,OAAO,OAAO,CAAC,UAAU,EAAE,OAAO,KAAK,SAAS,CAAC;AACnD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as spec from '@jsii/spec';\n\nimport { TypeFingerprinter } from './jsii/fingerprinting';\nimport { TARGET_LANGUAGES } from './languages';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, completeSource } from './snippet';\nimport {\n collectDependencies,\n validateAvailableDependencies,\n prepareDependencyDirectory,\n expandWithTransitiveDependencies,\n} from './snippet-dependencies';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, TranslatedSnippet } from './tablets/tablets';\nimport { translateAll, TranslateAllResult } from './translate_all';\n\nexport interface RosettaTranslatorOptions {\n /**\n * Assemblies to use for fingerprinting\n *\n * The set of assemblies here are used to invalidate the cache. Any types that are\n * used in snippets are looked up in this set of assemblies. If found, their type\n * information is fingerprinted and compared to the type information at the time\n * compilation of the cached sample. If different, this is considered to be a cache\n * miss.\n *\n * You must use the same set of assemblies when generating and reading the cache\n * file, otherwise the fingerprint is guaranteed to be different and the cache will\n * be useless (e.g. if you generate the cache WITH assembly information but\n * read it without, or vice versa).\n *\n * @default No assemblies.\n */\n readonly assemblies?: spec.Assembly[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Allow reading dirty translations from cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n}\n\n/**\n * Entry point for consumers that want to translate code on-the-fly\n *\n * If you want to generate and translate code on-the-fly, in ways that cannot\n * be achieved by the rosetta CLI, use this class.\n */\nexport class RosettaTranslator {\n /**\n * Tablet with fresh translations\n *\n * All new translations (not read from cache) are added to this tablet.\n */\n public readonly tablet = new LanguageTablet();\n\n public readonly cache = new LanguageTablet();\n\n private readonly fingerprinter: TypeFingerprinter;\n private readonly includeCompilerDiagnostics: boolean;\n private readonly allowDirtyTranslations: boolean;\n\n public constructor(options: RosettaTranslatorOptions = {}) {\n this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []);\n this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false;\n this.allowDirtyTranslations = options.allowDirtyTranslations ?? false;\n }\n\n /**\n * @deprecated use `addToCache` instead\n */\n public async loadCache(fileName: string) {\n try {\n await this.cache.load(fileName);\n } catch (e: any) {\n logging.warn(`Error reading cache ${fileName}: ${e.message}`);\n }\n }\n\n public async addToCache(filename: string) {\n const tab = await LanguageTablet.fromOptionalFile(filename);\n this.cache.addTablet(tab);\n }\n\n public addTabletsToCache(...tablets: LanguageTablet[]) {\n for (const tab of tablets) {\n this.cache.addTablet(tab);\n }\n }\n\n public hasCache() {\n return this.cache.count > 0;\n }\n\n /**\n * For all the given snippets, try to read translations from the cache\n *\n * Will remove the cached snippets from the input array.\n */\n public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults {\n const translations = new Array<TranslatedSnippet>();\n const remaining = new Array<TypeScriptSnippet>();\n\n let infusedCount = 0;\n let dirtyCount = 0;\n let dirtySourceCount = 0;\n let dirtyTypesCount = 0;\n let dirtyTranslatorCount = 0;\n let dirtyDidntCompile = 0;\n\n for (const snippet of snippets) {\n const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly);\n switch (fromCache.type) {\n case 'hit':\n if (addToTablet) {\n this.tablet.addSnippets(fromCache.snippet);\n }\n translations.push(fromCache.snippet);\n\n infusedCount += fromCache.infused ? 1 : 0;\n break;\n\n case 'dirty':\n dirtyCount += 1;\n dirtySourceCount += fromCache.dirtySource ? 1 : 0;\n dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0;\n dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0;\n dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0;\n\n if (this.allowDirtyTranslations) {\n translations.push(fromCache.translation);\n } else {\n remaining.push(snippet);\n }\n break;\n\n case 'miss':\n remaining.push(snippet);\n break;\n }\n }\n\n return {\n translations,\n remaining,\n infusedCount,\n dirtyCount,\n dirtySourceCount,\n dirtyTranslatorCount,\n dirtyTypesCount,\n dirtyDidntCompile,\n };\n }\n\n public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;\n public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;\n public async translateAll(\n snippets: TypeScriptSnippet[],\n optionsOrAddToTablet?: boolean | TranslateAllOptions,\n ): Promise<TranslateAllResult> {\n const options =\n optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object'\n ? optionsOrAddToTablet\n : { addToTablet: optionsOrAddToTablet };\n\n const exampleDependencies = collectDependencies(snippets);\n await expandWithTransitiveDependencies(exampleDependencies);\n\n let compilationDirectory;\n let cleanCompilationDir = false;\n if (options?.compilationDirectory) {\n // If the user provided a directory, we're going to trust-but-confirm.\n await validateAvailableDependencies(options.compilationDirectory, exampleDependencies);\n compilationDirectory = options.compilationDirectory;\n } else {\n compilationDirectory = await prepareDependencyDirectory(exampleDependencies);\n cleanCompilationDir = true;\n }\n\n const origDir = process.cwd();\n // Easiest way to get a fixed working directory (for sources) in is to chdir\n process.chdir(compilationDirectory);\n\n let result;\n try {\n result = await translateAll(snippets, this.includeCompilerDiagnostics, options?.batchSize);\n } finally {\n process.chdir(origDir);\n if (cleanCompilationDir) {\n if (options.cleanup ?? true) {\n await fs.rm(compilationDirectory, { force: true, recursive: true });\n } else {\n logging.info(`Leaving directory uncleaned: ${compilationDirectory}`);\n }\n }\n }\n\n const fingerprinted = result.translatedSnippets.map((snippet) =>\n snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())),\n );\n\n if (options?.addToTablet ?? true) {\n this.tablet.addSnippets(...fingerprinted);\n }\n\n return {\n translatedSnippets: fingerprinted,\n diagnostics: result.diagnostics,\n };\n }\n}\n\n/**\n * Try to find the translation for the given snippet in the given cache\n *\n * Rules for cacheability are:\n * - id is the same (== visible source didn't change)\n * - complete source is the same (== fixture didn't change)\n * - all types involved have the same fingerprint (== API surface didn't change)\n * - the versions of all translations match the versions on the available translators (== translator itself didn't change)\n *\n * For the versions check: we could have selectively picked some translations\n * from the cache while performing others. However, since the big work is in\n * parsing the TypeScript, and the rendering itself is peanutes (assumption), it\n * doesn't really make a lot of difference. So, for simplification's sake,\n * we'll regen all translations if there's at least one that's outdated.\n */\nfunction tryReadFromCache(\n sourceSnippet: TypeScriptSnippet,\n cache: LanguageTablet,\n fingerprinter: TypeFingerprinter,\n compiledOnly: boolean,\n): CacheHit {\n const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet));\n\n if (!fromCache) {\n return { type: 'miss' };\n }\n\n // infused snippets won't pass the full source check or the fingerprinter\n // but there is no reason to try to recompile it, so return cached snippet\n // if there exists one.\n if (isInfused(sourceSnippet)) {\n return { type: 'hit', snippet: fromCache, infused: true };\n }\n\n const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource;\n const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every(\n ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version,\n );\n const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint;\n const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile;\n\n if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) {\n return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile };\n }\n return { type: 'hit', snippet: fromCache, infused: false };\n}\n\nexport type CacheHit =\n | { readonly type: 'miss' }\n | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean }\n | {\n readonly type: 'dirty';\n readonly translation: TranslatedSnippet;\n readonly dirtySource: boolean;\n readonly dirtyTranslator: boolean;\n readonly dirtyTypes: boolean;\n readonly dirtyDidntCompile: boolean;\n };\n\nfunction isInfused(snippet: TypeScriptSnippet) {\n return snippet.parameters?.infused !== undefined;\n}\n\nexport interface ReadFromCacheResults {\n /**\n * Successful translations\n */\n readonly translations: TranslatedSnippet[];\n\n /**\n * Successful but dirty hits\n */\n readonly remaining: TypeScriptSnippet[];\n\n /**\n * How many successfully hit translations were infused\n */\n readonly infusedCount: number;\n\n readonly dirtyCount: number;\n\n // Counts for dirtiness (a single snippet may be dirty for more than one reason)\n readonly dirtySourceCount: number;\n readonly dirtyTranslatorCount: number;\n readonly dirtyTypesCount: number;\n readonly dirtyDidntCompile: number;\n}\n\nexport interface TranslateAllOptions {\n /**\n * @default - Create a temporary directory with all necessary packages\n */\n readonly compilationDirectory?: string;\n\n /**\n * @default true\n */\n readonly addToTablet?: boolean;\n\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"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M,iBAAiB,GAAG,YAAY,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,UAAU,CAAC;IAExE,IAAI,WAAW,IAAI,eAAe,IAAI,UAAU,IAAI,iBAAiB,EAAE,CAAC;QACtE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,iBAAiB,EAAE,CAAC;IAChH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAC7D,CAAC;AAcD,SAAS,SAAS,CAAC,OAA0B;IAC3C,OAAO,OAAO,CAAC,UAAU,EAAE,OAAO,KAAK,SAAS,CAAC;AACnD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as spec from '@jsii/spec';\n\nimport { TypeFingerprinter } from './jsii/fingerprinting';\nimport { TARGET_LANGUAGES } from './languages';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, completeSource } from './snippet';\nimport {\n collectDependencies,\n validateAvailableDependencies,\n prepareDependencyDirectory,\n expandWithTransitiveDependencies,\n} from './snippet-dependencies';\nimport { snippetKey } from './tablets/key';\nimport { LanguageTablet, TranslatedSnippet } from './tablets/tablets';\nimport { translateAll, TranslateAllResult } from './translate_all';\n\nexport interface RosettaTranslatorOptions {\n /**\n * Assemblies to use for fingerprinting\n *\n * The set of assemblies here are used to invalidate the cache. Any types that are\n * used in snippets are looked up in this set of assemblies. If found, their type\n * information is fingerprinted and compared to the type information at the time\n * compilation of the cached sample. If different, this is considered to be a cache\n * miss.\n *\n * You must use the same set of assemblies when generating and reading the cache\n * file, otherwise the fingerprint is guaranteed to be different and the cache will\n * be useless (e.g. if you generate the cache WITH assembly information but\n * read it without, or vice versa).\n *\n * @default No assemblies.\n */\n readonly assemblies?: spec.Assembly[];\n\n /**\n * Whether to include compiler diagnostics in the compilation results.\n *\n * @default false\n */\n readonly includeCompilerDiagnostics?: boolean;\n\n /**\n * Allow reading dirty translations from cache\n *\n * @default false\n */\n readonly allowDirtyTranslations?: boolean;\n}\n\n/**\n * Entry point for consumers that want to translate code on-the-fly\n *\n * If you want to generate and translate code on-the-fly, in ways that cannot\n * be achieved by the rosetta CLI, use this class.\n */\nexport class RosettaTranslator {\n /**\n * Tablet with fresh translations\n *\n * All new translations (not read from cache) are added to this tablet.\n */\n public readonly tablet = new LanguageTablet();\n\n public readonly cache = new LanguageTablet();\n\n private readonly fingerprinter: TypeFingerprinter;\n private readonly includeCompilerDiagnostics: boolean;\n private readonly allowDirtyTranslations: boolean;\n\n public constructor(options: RosettaTranslatorOptions = {}) {\n this.fingerprinter = new TypeFingerprinter(options?.assemblies ?? []);\n this.includeCompilerDiagnostics = options.includeCompilerDiagnostics ?? false;\n this.allowDirtyTranslations = options.allowDirtyTranslations ?? false;\n }\n\n /**\n * @deprecated use `addToCache` instead\n */\n public async loadCache(fileName: string) {\n try {\n await this.cache.load(fileName);\n } catch (e: any) {\n logging.warn(`Error reading cache ${fileName}: ${e.message}`);\n }\n }\n\n public async addToCache(filename: string) {\n const tab = await LanguageTablet.fromOptionalFile(filename);\n this.cache.addTablet(tab);\n }\n\n public addTabletsToCache(...tablets: LanguageTablet[]) {\n for (const tab of tablets) {\n this.cache.addTablet(tab);\n }\n }\n\n public hasCache() {\n return this.cache.count > 0;\n }\n\n /**\n * For all the given snippets, try to read translations from the cache\n *\n * Will remove the cached snippets from the input array.\n */\n public readFromCache(snippets: TypeScriptSnippet[], addToTablet = true, compiledOnly = false): ReadFromCacheResults {\n const translations = new Array<TranslatedSnippet>();\n const remaining = new Array<TypeScriptSnippet>();\n\n let infusedCount = 0;\n let dirtyCount = 0;\n let dirtySourceCount = 0;\n let dirtyTypesCount = 0;\n let dirtyTranslatorCount = 0;\n let dirtyDidntCompile = 0;\n\n for (const snippet of snippets) {\n const fromCache = tryReadFromCache(snippet, this.cache, this.fingerprinter, compiledOnly);\n switch (fromCache.type) {\n case 'hit':\n if (addToTablet) {\n this.tablet.addSnippets(fromCache.snippet);\n }\n translations.push(fromCache.snippet);\n\n infusedCount += fromCache.infused ? 1 : 0;\n break;\n\n case 'dirty':\n dirtyCount += 1;\n dirtySourceCount += fromCache.dirtySource ? 1 : 0;\n dirtyTranslatorCount += fromCache.dirtyTranslator ? 1 : 0;\n dirtyTypesCount += fromCache.dirtyTypes ? 1 : 0;\n dirtyDidntCompile += fromCache.dirtyDidntCompile ? 1 : 0;\n\n if (this.allowDirtyTranslations) {\n translations.push(fromCache.translation);\n } else {\n remaining.push(snippet);\n }\n break;\n\n case 'miss':\n remaining.push(snippet);\n break;\n }\n }\n\n return {\n translations,\n remaining,\n infusedCount,\n dirtyCount,\n dirtySourceCount,\n dirtyTranslatorCount,\n dirtyTypesCount,\n dirtyDidntCompile,\n };\n }\n\n public async translateAll(snippets: TypeScriptSnippet[], addToTablet?: boolean): Promise<TranslateAllResult>;\n public async translateAll(snippets: TypeScriptSnippet[], options?: TranslateAllOptions): Promise<TranslateAllResult>;\n public async translateAll(\n snippets: TypeScriptSnippet[],\n optionsOrAddToTablet?: boolean | TranslateAllOptions,\n ): Promise<TranslateAllResult> {\n const options =\n optionsOrAddToTablet && typeof optionsOrAddToTablet === 'object'\n ? optionsOrAddToTablet\n : { addToTablet: optionsOrAddToTablet };\n\n const exampleDependencies = collectDependencies(snippets);\n await expandWithTransitiveDependencies(exampleDependencies);\n\n let compilationDirectory;\n let cleanCompilationDir = false;\n if (options?.compilationDirectory) {\n // If the user provided a directory, we're going to trust-but-confirm.\n await validateAvailableDependencies(options.compilationDirectory, exampleDependencies);\n compilationDirectory = options.compilationDirectory;\n } else {\n compilationDirectory = await prepareDependencyDirectory(exampleDependencies);\n cleanCompilationDir = true;\n }\n\n const origDir = process.cwd();\n // Easiest way to get a fixed working directory (for sources) in is to chdir\n process.chdir(compilationDirectory);\n\n let result;\n try {\n result = await translateAll(snippets, this.includeCompilerDiagnostics, options?.batchSize);\n } finally {\n process.chdir(origDir);\n if (cleanCompilationDir) {\n if (options.cleanup ?? true) {\n await fs.rm(compilationDirectory, { force: true, recursive: true });\n } else {\n logging.info(`Leaving directory uncleaned: ${compilationDirectory}`);\n }\n }\n }\n\n const fingerprinted = result.translatedSnippets.map((snippet) =>\n snippet.withFingerprint(this.fingerprinter.fingerprintAll(snippet.fqnsReferenced())),\n );\n\n if (process.env.DEBUG_TYPE_FINGERPRINTS) {\n this.fingerprinter.writeDebugFile(process.env.DEBUG_TYPE_FINGERPRINTS);\n }\n\n if (options?.addToTablet ?? true) {\n this.tablet.addSnippets(...fingerprinted);\n }\n\n return {\n translatedSnippets: fingerprinted,\n diagnostics: result.diagnostics,\n timings: result.timings,\n };\n }\n}\n\n/**\n * Try to find the translation for the given snippet in the given cache\n *\n * Rules for cacheability are:\n * - id is the same (== visible source didn't change)\n * - complete source is the same (== fixture didn't change)\n * - all types involved have the same fingerprint (== API surface didn't change)\n * - the versions of all translations match the versions on the available translators (== translator itself didn't change)\n *\n * For the versions check: we could have selectively picked some translations\n * from the cache while performing others. However, since the big work is in\n * parsing the TypeScript, and the rendering itself is peanutes (assumption), it\n * doesn't really make a lot of difference. So, for simplification's sake,\n * we'll regen all translations if there's at least one that's outdated.\n */\nfunction tryReadFromCache(\n sourceSnippet: TypeScriptSnippet,\n cache: LanguageTablet,\n fingerprinter: TypeFingerprinter,\n compiledOnly: boolean,\n): CacheHit {\n const fromCache = cache.tryGetSnippet(snippetKey(sourceSnippet));\n\n if (!fromCache) {\n return { type: 'miss' };\n }\n\n // infused snippets won't pass the full source check or the fingerprinter\n // but there is no reason to try to recompile it, so return cached snippet\n // if there exists one.\n if (isInfused(sourceSnippet)) {\n return { type: 'hit', snippet: fromCache, infused: true };\n }\n\n const dirtySource = completeSource(sourceSnippet) !== fromCache.snippet.fullSource;\n const dirtyTranslator = !Object.entries(TARGET_LANGUAGES).every(\n ([lang, translator]) => fromCache.snippet.translations?.[lang]?.version === translator.version,\n );\n const dirtyTypes = fingerprinter.fingerprintAll(fromCache.fqnsReferenced()) !== fromCache.snippet.fqnsFingerprint;\n const dirtyDidntCompile = compiledOnly && !fromCache.snippet.didCompile;\n\n if (dirtySource || dirtyTranslator || dirtyTypes || dirtyDidntCompile) {\n return { type: 'dirty', translation: fromCache, dirtySource, dirtyTranslator, dirtyTypes, dirtyDidntCompile };\n }\n return { type: 'hit', snippet: fromCache, infused: false };\n}\n\nexport type CacheHit =\n | { readonly type: 'miss' }\n | { readonly type: 'hit'; readonly snippet: TranslatedSnippet; readonly infused: boolean }\n | {\n readonly type: 'dirty';\n readonly translation: TranslatedSnippet;\n readonly dirtySource: boolean;\n readonly dirtyTranslator: boolean;\n readonly dirtyTypes: boolean;\n readonly dirtyDidntCompile: boolean;\n };\n\nfunction isInfused(snippet: TypeScriptSnippet) {\n return snippet.parameters?.infused !== undefined;\n}\n\nexport interface ReadFromCacheResults {\n /**\n * Successful translations\n */\n readonly translations: TranslatedSnippet[];\n\n /**\n * Successful but dirty hits\n */\n readonly remaining: TypeScriptSnippet[];\n\n /**\n * How many successfully hit translations were infused\n */\n readonly infusedCount: number;\n\n readonly dirtyCount: number;\n\n // Counts for dirtiness (a single snippet may be dirty for more than one reason)\n readonly dirtySourceCount: number;\n readonly dirtyTranslatorCount: number;\n readonly dirtyTypesCount: number;\n readonly dirtyDidntCompile: number;\n}\n\nexport interface TranslateAllOptions {\n /**\n * @default - Create a temporary directory with all necessary packages\n */\n readonly compilationDirectory?: string;\n\n /**\n * @default true\n */\n readonly addToTablet?: boolean;\n\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"]}
@@ -120,6 +120,11 @@ export declare class BatchSnippetTranslator {
120
120
  *
121
121
  * Reduce it down to only the information we need.
122
122
  */
123
+ export interface SnippetTimingInfo {
124
+ readonly name: string;
125
+ readonly snippetKey: string;
126
+ readonly durationMs: number;
127
+ }
123
128
  export interface RosettaDiagnostic {
124
129
  /**
125
130
  * If this is an error diagnostic or not
@@ -135,8 +140,18 @@ export interface RosettaDiagnostic {
135
140
  * Ends in a newline.
136
141
  */
137
142
  readonly formattedMessage: string;
143
+ /**
144
+ * Optional timing information for snippet translation
145
+ */
146
+ readonly timingInfo?: SnippetTimingInfo;
138
147
  }
139
148
  export declare function makeRosettaDiagnostic(isError: boolean, formattedMessage: string): RosettaDiagnostic;
149
+ export declare function makeTimingDiagnostic(snippetKey: string, name: string, durationMs: number): RosettaDiagnostic;
150
+ export declare function extractTimingInfo(diagnostics: readonly RosettaDiagnostic[]): {
151
+ timings: SnippetTimingInfo[];
152
+ diagnostics: RosettaDiagnostic[];
153
+ };
154
+ export declare function formatTimingTable(timings: SnippetTimingInfo[]): string;
140
155
  /**
141
156
  * Turn TypeScript diagnostics into Rosetta diagnostics
142
157
  */
package/lib/translate.js CHANGED
@@ -9,6 +9,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.BatchSnippetTranslator = exports.SnippetTranslator = exports.Translator = void 0;
10
10
  exports.translateTypeScript = translateTypeScript;
11
11
  exports.makeRosettaDiagnostic = makeRosettaDiagnostic;
12
+ exports.makeTimingDiagnostic = makeTimingDiagnostic;
13
+ exports.extractTimingInfo = extractTimingInfo;
14
+ exports.formatTimingTable = formatTimingTable;
12
15
  exports.rosettaDiagFromTypescript = rosettaDiagFromTypescript;
13
16
  const path = require("node:path");
14
17
  const node_util_1 = require("node:util");
@@ -21,7 +24,6 @@ const o_tree_1 = require("./o-tree");
21
24
  const renderer_1 = require("./renderer");
22
25
  const snippet_1 = require("./snippet");
23
26
  const submodule_reference_1 = require("./submodule-reference");
24
- const key_1 = require("./tablets/key");
25
27
  const schema_1 = require("./tablets/schema");
26
28
  const tablets_1 = require("./tablets/tablets");
27
29
  const syntax_kind_counter_1 = require("./typescript/syntax-kind-counter");
@@ -68,14 +70,8 @@ class Translator {
68
70
  * Translates a single snippet in its own TS context.
69
71
  */
70
72
  translate(snip, languages = Object.values(languages_1.TargetLanguage)) {
71
- const start = performance.now();
72
- logging.debug(`Translating ${(0, key_1.snippetKey)(snip)} ${(0, node_util_1.inspect)(snip.parameters ?? {})}`);
73
73
  const translator = this.translatorFor(snip);
74
74
  const translated = this.translateSnippet(snip, translator, languages);
75
- const duration = performance.now() - start;
76
- logging.debug(`Completed ${(0, key_1.snippetKey)(snip)} ${(0, node_util_1.inspect)({
77
- duration: `${(duration / 1000).toFixed(2)}s`,
78
- })}`);
79
75
  return translated;
80
76
  }
81
77
  /**
@@ -274,6 +270,49 @@ function filterVisibleDiagnostics(diags, visibleSpans) {
274
270
  function makeRosettaDiagnostic(isError, formattedMessage) {
275
271
  return { isError, formattedMessage, isFromStrictAssembly: false };
276
272
  }
273
+ function makeTimingDiagnostic(snippetKey, name, durationMs) {
274
+ return {
275
+ isError: false,
276
+ isFromStrictAssembly: false,
277
+ formattedMessage: '',
278
+ timingInfo: { snippetKey, name, durationMs },
279
+ };
280
+ }
281
+ function extractTimingInfo(diagnostics) {
282
+ const timings = [];
283
+ const regular = [];
284
+ for (const diag of diagnostics) {
285
+ if (diag.timingInfo) {
286
+ timings.push(diag.timingInfo);
287
+ }
288
+ else {
289
+ regular.push(diag);
290
+ }
291
+ }
292
+ return { timings, diagnostics: regular };
293
+ }
294
+ function formatTimingTable(timings) {
295
+ if (timings.length === 0) {
296
+ return '';
297
+ }
298
+ const totalTime = timings.reduce((sum, t) => sum + t.durationMs, 0);
299
+ const sorted = timings.sort((a, b) => b.durationMs - a.durationMs).slice(0, 10);
300
+ const lines = [
301
+ '',
302
+ '=== Top 10 Slowest Snippets ===',
303
+ 'Rank | Time (s) | % of Total | Snippet ',
304
+ '-----|----------|------------|--------------------------------',
305
+ ];
306
+ for (const [idx, timing] of sorted.entries()) {
307
+ const timeS = (timing.durationMs / 1000).toFixed(2).padStart(8);
308
+ const pct = ((timing.durationMs / totalTime) * 100).toFixed(1).padStart(9) + '%';
309
+ lines.push(`${(idx + 1).toString().padEnd(4)} | ${timeS} | ${pct} | ${timing.name}`);
310
+ }
311
+ lines.push('');
312
+ lines.push(`Total translation time: ${(totalTime / 1000).toFixed(2)}s`);
313
+ lines.push('');
314
+ return lines.join('\n');
315
+ }
277
316
  /**
278
317
  * Turn TypeScript diagnostics into Rosetta diagnostics
279
318
  */