jsii-rosetta 5.4.32-dev.2 → 5.5.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (82) hide show
  1. package/README.md +2 -2
  2. package/lib/commands/convert.js +1 -2
  3. package/lib/commands/convert.js.map +1 -1
  4. package/lib/commands/coverage.js +1 -2
  5. package/lib/commands/coverage.js.map +1 -1
  6. package/lib/commands/extract.js +2 -3
  7. package/lib/commands/extract.js.map +1 -1
  8. package/lib/commands/infuse.js +2 -2
  9. package/lib/commands/infuse.js.map +1 -1
  10. package/lib/commands/read.js +1 -2
  11. package/lib/commands/read.js.map +1 -1
  12. package/lib/commands/transliterate.js +1 -2
  13. package/lib/commands/transliterate.js.map +1 -1
  14. package/lib/commands/trim-cache.js +1 -2
  15. package/lib/commands/trim-cache.js.map +1 -1
  16. package/lib/find-utils.js +4 -5
  17. package/lib/find-utils.js.map +1 -1
  18. package/lib/fixtures.js +1 -2
  19. package/lib/fixtures.js.map +1 -1
  20. package/lib/jsii/assemblies.js +9 -9
  21. package/lib/jsii/assemblies.js.map +1 -1
  22. package/lib/jsii/jsii-types.js +2 -3
  23. package/lib/jsii/jsii-types.js.map +1 -1
  24. package/lib/jsii/jsii-utils.js +15 -16
  25. package/lib/jsii/jsii-utils.js.map +1 -1
  26. package/lib/jsii/packages.js +1 -2
  27. package/lib/jsii/packages.js.map +1 -1
  28. package/lib/json.d.ts +0 -2
  29. package/lib/json.js +2 -3
  30. package/lib/json.js.map +1 -1
  31. package/lib/languages/target-language.js +3 -3
  32. package/lib/languages/target-language.js.map +1 -1
  33. package/lib/logging.js +6 -6
  34. package/lib/logging.js.map +1 -1
  35. package/lib/markdown/escapes.js +2 -3
  36. package/lib/markdown/escapes.js.map +1 -1
  37. package/lib/markdown/extract-snippets.js +1 -2
  38. package/lib/markdown/extract-snippets.js.map +1 -1
  39. package/lib/markdown/index.js +3 -4
  40. package/lib/markdown/index.js.map +1 -1
  41. package/lib/markdown/markdown-renderer.js +5 -5
  42. package/lib/markdown/markdown-renderer.js.map +1 -1
  43. package/lib/markdown/markdown.js +5 -6
  44. package/lib/markdown/markdown.js.map +1 -1
  45. package/lib/o-tree.js +2 -2
  46. package/lib/o-tree.js.map +1 -1
  47. package/lib/renderer.js +3 -2
  48. package/lib/renderer.js.map +1 -1
  49. package/lib/rosetta-reader.d.ts +0 -1
  50. package/lib/snippet-dependencies.js +5 -6
  51. package/lib/snippet-dependencies.js.map +1 -1
  52. package/lib/snippet-selectors.js +4 -5
  53. package/lib/snippet-selectors.js.map +1 -1
  54. package/lib/snippet.js +11 -11
  55. package/lib/snippet.js.map +1 -1
  56. package/lib/strict.js +1 -2
  57. package/lib/strict.js.map +1 -1
  58. package/lib/support.js +1 -2
  59. package/lib/support.js.map +1 -1
  60. package/lib/tablets/key.js +1 -2
  61. package/lib/tablets/key.js.map +1 -1
  62. package/lib/translate.js +4 -4
  63. package/lib/translate.js.map +1 -1
  64. package/lib/translate_all.js +1 -2
  65. package/lib/translate_all.js.map +1 -1
  66. package/lib/translate_all_worker.js +1 -2
  67. package/lib/translate_all_worker.js.map +1 -1
  68. package/lib/typescript/ast-utils.d.ts +1 -1
  69. package/lib/typescript/ast-utils.js +23 -23
  70. package/lib/typescript/ast-utils.js.map +1 -1
  71. package/lib/typescript/imports.d.ts +2 -2
  72. package/lib/typescript/imports.js +2 -3
  73. package/lib/typescript/imports.js.map +1 -1
  74. package/lib/typescript/types.js +16 -17
  75. package/lib/typescript/types.js.map +1 -1
  76. package/lib/typescript/visible-spans.js +4 -4
  77. package/lib/typescript/visible-spans.js.map +1 -1
  78. package/lib/util.d.ts +0 -1
  79. package/lib/util.js +19 -19
  80. package/lib/util.js.map +1 -1
  81. package/package.json +4 -4
  82. package/releases.json +4 -3
package/README.md CHANGED
@@ -41,9 +41,9 @@ The current status of `jsii-rosetta` releases is:
41
41
 
42
42
  | Release | Status | EOS | Comment |
43
43
  | ------- | ----------- | -----------| ------------------------------------------------------------------------------------------------------- |
44
- | `5.4.x` | Current | TBD | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v5.4-latest?label=jsii-rosetta%40v5.4-latest&logo=npm) |
44
+ | `5.5.x` | Current | TBD | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v5.5-latest?label=jsii-rosetta%40v5.5-latest&logo=npm) |
45
+ | `5.4.x` | Maintenance | 2025-02-28 | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v5.4-latest?label=jsii-rosetta%40v5.4-latest&logo=npm) |
45
46
  | `5.3.x` | Maintenance | 2024-10-07 | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v5.3-latest?label=jsii-rosetta%40v5.3-latest&logo=npm) |
46
- | `5.2.x` | Maintenance | 2024-06-30 | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v5.2-latest?label=jsii-rosetta%40v5.2-latest&logo=npm) |
47
47
  | `1.x` | Maintenance | 2024-10-31 | ![npm](https://img.shields.io/npm/v/jsii-rosetta/v1?label=jsii-rosetta%40v1&logo=npm) |
48
48
 
49
49
  ## :gear: Contributing
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.translateMarkdown = void 0;
3
+ exports.translateMarkdown = translateMarkdown;
4
4
  const markdown_1 = require("../markdown/markdown");
5
5
  const markdown_renderer_1 = require("../markdown/markdown-renderer");
6
6
  const replace_typescript_transform_1 = require("../markdown/replace-typescript-transform");
@@ -20,5 +20,4 @@ function translateMarkdown(markdown, visitor, opts = {}) {
20
20
  diagnostics: translator.diagnostics,
21
21
  };
22
22
  }
23
- exports.translateMarkdown = translateMarkdown;
24
23
  //# sourceMappingURL=convert.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"convert.js","sourceRoot":"","sources":["../../src/commands/convert.ts"],"names":[],"mappings":";;;AAAA,mDAAyD;AACzD,qEAAiE;AACjE,2FAAsF;AAEtF,4CAA2D;AAe3D,SAAgB,iBAAiB,CAC/B,QAAc,EACd,OAAwB,EACxB,OAAiC,EAAE;IAEnC,MAAM,UAAU,GAAG,IAAI,sBAAU,CAAC,KAAK,CAAC,CAAC;IAEzC,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAW,CAAC;IAEvE,MAAM,kBAAkB,GAAG,IAAA,4BAAiB,EAC1C,QAAQ,CAAC,QAAQ,EACjB,IAAI,oCAAgB,EAAE,EACtB,IAAI,yDAA0B,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC,SAAS,EAAE,EAAE;QAC3E,MAAM,UAAU,GAAG,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC5E,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,kBAAkB,IAAI,EAAE;YACvC,MAAM,EAAE,UAAU;SACnB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,kBAAkB;QAC/B,WAAW,EAAE,UAAU,CAAC,WAAW;KACpC,CAAC;AACJ,CAAC;AAzBD,8CAyBC","sourcesContent":["import { transformMarkdown } from '../markdown/markdown';\nimport { MarkdownRenderer } from '../markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from '../markdown/replace-typescript-transform';\nimport { AstHandler, AstRendererOptions } from '../renderer';\nimport { TranslateResult, Translator } from '../translate';\nimport { File } from '../util';\n\nexport interface TranslateMarkdownOptions extends AstRendererOptions {\n /**\n * What language to put in the returned markdown blocks\n */\n languageIdentifier?: string;\n\n /**\n * Whether to operate in `strict` mode or not.\n */\n strict?: boolean;\n}\n\nexport function translateMarkdown(\n markdown: File,\n visitor: AstHandler<any>,\n opts: TranslateMarkdownOptions = {},\n): TranslateResult {\n const translator = new Translator(false);\n\n const location = { api: 'file', fileName: markdown.fileName } as const;\n\n const translatedMarkdown = transformMarkdown(\n markdown.contents,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(location, opts.strict ?? false, (tsSnippet) => {\n const translated = translator.translatorFor(tsSnippet).renderUsing(visitor);\n return {\n language: opts.languageIdentifier ?? '',\n source: translated,\n };\n }),\n );\n\n return {\n translation: translatedMarkdown,\n diagnostics: translator.diagnostics,\n };\n}\n"]}
1
+ {"version":3,"file":"convert.js","sourceRoot":"","sources":["../../src/commands/convert.ts"],"names":[],"mappings":";;AAmBA,8CAyBC;AA5CD,mDAAyD;AACzD,qEAAiE;AACjE,2FAAsF;AAEtF,4CAA2D;AAe3D,SAAgB,iBAAiB,CAC/B,QAAc,EACd,OAAwB,EACxB,OAAiC,EAAE;IAEnC,MAAM,UAAU,GAAG,IAAI,sBAAU,CAAC,KAAK,CAAC,CAAC;IAEzC,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,CAAC,QAAQ,EAAW,CAAC;IAEvE,MAAM,kBAAkB,GAAG,IAAA,4BAAiB,EAC1C,QAAQ,CAAC,QAAQ,EACjB,IAAI,oCAAgB,EAAE,EACtB,IAAI,yDAA0B,CAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC,SAAS,EAAE,EAAE;QAC3E,MAAM,UAAU,GAAG,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC5E,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,kBAAkB,IAAI,EAAE;YACvC,MAAM,EAAE,UAAU;SACnB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,WAAW,EAAE,kBAAkB;QAC/B,WAAW,EAAE,UAAU,CAAC,WAAW;KACpC,CAAC;AACJ,CAAC","sourcesContent":["import { transformMarkdown } from '../markdown/markdown';\nimport { MarkdownRenderer } from '../markdown/markdown-renderer';\nimport { ReplaceTypeScriptTransform } from '../markdown/replace-typescript-transform';\nimport { AstHandler, AstRendererOptions } from '../renderer';\nimport { TranslateResult, Translator } from '../translate';\nimport { File } from '../util';\n\nexport interface TranslateMarkdownOptions extends AstRendererOptions {\n /**\n * What language to put in the returned markdown blocks\n */\n languageIdentifier?: string;\n\n /**\n * Whether to operate in `strict` mode or not.\n */\n strict?: boolean;\n}\n\nexport function translateMarkdown(\n markdown: File,\n visitor: AstHandler<any>,\n opts: TranslateMarkdownOptions = {},\n): TranslateResult {\n const translator = new Translator(false);\n\n const location = { api: 'file', fileName: markdown.fileName } as const;\n\n const translatedMarkdown = transformMarkdown(\n markdown.contents,\n new MarkdownRenderer(),\n new ReplaceTypeScriptTransform(location, opts.strict ?? false, (tsSnippet) => {\n const translated = translator.translatorFor(tsSnippet).renderUsing(visitor);\n return {\n language: opts.languageIdentifier ?? '',\n source: translated,\n };\n }),\n );\n\n return {\n translation: translatedMarkdown,\n diagnostics: translator.diagnostics,\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkCoverage = void 0;
3
+ exports.checkCoverage = checkCoverage;
4
4
  const assemblies_1 = require("../jsii/assemblies");
5
5
  const logging = require("../logging");
6
6
  const rosetta_translator_1 = require("../rosetta-translator");
@@ -30,5 +30,4 @@ async function checkCoverage(assemblyLocations) {
30
30
  process.stdout.write(` ${(0, snippet_1.formatLocation)(remaining.location)}\n`);
31
31
  }
32
32
  }
33
- exports.checkCoverage = checkCoverage;
34
33
  //# sourceMappingURL=coverage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"coverage.js","sourceRoot":"","sources":["../../src/commands/coverage.ts"],"names":[],"mappings":";;;AAAA,mDAAkG;AAClG,sCAAsC;AACtC,8DAA0D;AAC1D,wCAA4C;AAErC,KAAK,UAAU,aAAa,CAAC,iBAAoC;IACtE,OAAO,CAAC,IAAI,CAAC,WAAW,iBAAiB,CAAC,MAAM,aAAa,CAAC,CAAC;IAC/D,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAE5D,MAAM,QAAQ,GA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C,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,eAAe,wBAAwB,CAAC,CAAC;IAC9E,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,iBAAiB,kCAAkC,CAAC,CAAC;IAC1F,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,SAAS,CAAC,MAAM,2BAA2B,CAAC,CAAC;IAE/E,KAAK,MAAM,SAAS,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QAC1C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,IAAA,wBAAc,EAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvE,CAAC;AACH,CAAC;AA7BD,sCA6BC","sourcesContent":["import { loadAssemblies, allTypeScriptSnippets, loadAllDefaultTablets } from '../jsii/assemblies';\nimport * as logging from '../logging';\nimport { RosettaTranslator } from '../rosetta-translator';\nimport { formatLocation } from '../snippet';\n\nexport async function checkCoverage(assemblyLocations: readonly string[]): Promise<void> {\n logging.info(`Loading ${assemblyLocations.length} assemblies`);\n const assemblies = loadAssemblies(assemblyLocations, false);\n\n const snippets = Array.from(await allTypeScriptSnippets(assemblies, true));\n\n const translator = new RosettaTranslator({\n assemblies: assemblies.map((a) => a.assembly),\n allowDirtyTranslations: true,\n });\n translator.addTabletsToCache(...Object.values(await loadAllDefaultTablets(assemblies)));\n\n process.stdout.write(`- ${snippets.length} total snippets.\\n`);\n process.stdout.write(`- ${translator.cache.count} translations in cache.\\n`);\n process.stdout.write('\\n');\n\n const results = translator.readFromCache(snippets, true, true);\n process.stdout.write(`- ${results.translations.length - results.dirtyCount} successful cache hits.\\n`);\n process.stdout.write(` ${results.infusedCount} infused.\\n`);\n process.stdout.write(`- ${results.dirtyCount} translations in cache but dirty (ok for pacmak, transliterate)\\n`);\n process.stdout.write(` ${results.dirtySourceCount} sources have changed.\\n`);\n process.stdout.write(` ${results.dirtyTranslatorCount} translator has changed.\\n`);\n process.stdout.write(` ${results.dirtyTypesCount} types have changed.\\n`);\n process.stdout.write(` ${results.dirtyDidntCompile} did not successfully compile.\\n`);\n process.stdout.write(`- ${results.remaining.length} snippets untranslated.\\n`);\n\n for (const remaining of results.remaining) {\n process.stdout.write(` ${formatLocation(remaining.location)}\\n`);\n }\n}\n"]}
1
+ {"version":3,"file":"coverage.js","sourceRoot":"","sources":["../../src/commands/coverage.ts"],"names":[],"mappings":";;AAKA,sCA6BC;AAlCD,mDAAkG;AAClG,sCAAsC;AACtC,8DAA0D;AAC1D,wCAA4C;AAErC,KAAK,UAAU,aAAa,CAAC,iBAAoC;IACtE,OAAO,CAAC,IAAI,CAAC,WAAW,iBAAiB,CAAC,MAAM,aAAa,CAAC,CAAC;IAC/D,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAE5D,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,IAAA,kCAAqB,EAAC,UAAU,EAAE,IAAI,CAAC,CAAC,CAAC;IAE3E,MAAM,UAAU,GAAG,IAAI,sCAAiB,CAAC;QACvC,UAAU,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;QAC7C,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IACH,UAAU,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,IAAA,kCAAqB,EAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAExF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,QAAQ,CAAC,MAAM,oBAAoB,CAAC,CAAC;IAC/D,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,UAAU,CAAC,KAAK,CAAC,KAAK,2BAA2B,CAAC,CAAC;IAC7E,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAE3B,MAAM,OAAO,GAAG,UAAU,CAAC,aAAa,CAAC,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC/D,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,YAAY,CAAC,MAAM,GAAG,OAAO,CAAC,UAAU,2BAA2B,CAAC,CAAC;IACvG,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,YAAY,aAAa,CAAC,CAAC;IAChE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,UAAU,mEAAmE,CAAC,CAAC;IACjH,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,gBAAgB,0BAA0B,CAAC,CAAC;IACjF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,oBAAoB,4BAA4B,CAAC,CAAC;IACvF,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,eAAe,wBAAwB,CAAC,CAAC;IAC9E,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,OAAO,CAAC,iBAAiB,kCAAkC,CAAC,CAAC;IAC1F,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,SAAS,CAAC,MAAM,2BAA2B,CAAC,CAAC;IAE/E,KAAK,MAAM,SAAS,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QAC1C,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,IAAA,wBAAc,EAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACvE,CAAC;AACH,CAAC","sourcesContent":["import { loadAssemblies, allTypeScriptSnippets, loadAllDefaultTablets } from '../jsii/assemblies';\nimport * as logging from '../logging';\nimport { RosettaTranslator } from '../rosetta-translator';\nimport { formatLocation } from '../snippet';\n\nexport async function checkCoverage(assemblyLocations: readonly string[]): Promise<void> {\n logging.info(`Loading ${assemblyLocations.length} assemblies`);\n const assemblies = loadAssemblies(assemblyLocations, false);\n\n const snippets = Array.from(await allTypeScriptSnippets(assemblies, true));\n\n const translator = new RosettaTranslator({\n assemblies: assemblies.map((a) => a.assembly),\n allowDirtyTranslations: true,\n });\n translator.addTabletsToCache(...Object.values(await loadAllDefaultTablets(assemblies)));\n\n process.stdout.write(`- ${snippets.length} total snippets.\\n`);\n process.stdout.write(`- ${translator.cache.count} translations in cache.\\n`);\n process.stdout.write('\\n');\n\n const results = translator.readFromCache(snippets, true, true);\n process.stdout.write(`- ${results.translations.length - results.dirtyCount} successful cache hits.\\n`);\n process.stdout.write(` ${results.infusedCount} infused.\\n`);\n process.stdout.write(`- ${results.dirtyCount} translations in cache but dirty (ok for pacmak, transliterate)\\n`);\n process.stdout.write(` ${results.dirtySourceCount} sources have changed.\\n`);\n process.stdout.write(` ${results.dirtyTranslatorCount} translator has changed.\\n`);\n process.stdout.write(` ${results.dirtyTypesCount} types have changed.\\n`);\n process.stdout.write(` ${results.dirtyDidntCompile} did not successfully compile.\\n`);\n process.stdout.write(`- ${results.remaining.length} snippets untranslated.\\n`);\n\n for (const remaining of results.remaining) {\n process.stdout.write(` ${formatLocation(remaining.location)}\\n`);\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractSnippets = exports.extractAndInfuse = void 0;
3
+ exports.extractAndInfuse = extractAndInfuse;
4
+ exports.extractSnippets = extractSnippets;
4
5
  const path = require("node:path");
5
6
  const infuse_1 = require("./infuse");
6
7
  const assemblies_1 = require("../jsii/assemblies");
@@ -19,7 +20,6 @@ async function extractAndInfuse(assemblyLocations, options) {
19
20
  });
20
21
  return result;
21
22
  }
22
- exports.extractAndInfuse = extractAndInfuse;
23
23
  /**
24
24
  * Extract all samples from the given assemblies into a tablet
25
25
  */
@@ -93,7 +93,6 @@ async function extractSnippets(assemblyLocations, options = {}) {
93
93
  }
94
94
  return { diagnostics, tablet: translator.tablet };
95
95
  }
96
- exports.extractSnippets = extractSnippets;
97
96
  /**
98
97
  * Only yield the snippets whose id exists in a whitelist
99
98
  */
@@ -1 +1 @@
1
- {"version":3,"file":"extract.js","sourceRoot":"","sources":["../../src/commands/extract.ts"],"names":[],"mappings":";;;AAAA,kCAAkC;AAElC,qCAAkC;AAClC,mDAK4B;AAC5B,sCAAsC;AACtC,8DAAoF;AACpF,wCAAkE;AAClE,wCAA4C;AAC5C,gDAAyG;AAEzG,kCAA6C;AAwFtC,KAAK,UAAU,gBAAgB,CAAC,iBAA2B,EAAE,OAAuB;IACzF,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACjE,MAAM,IAAA,eAAM,EAAC,iBAAiB,EAAE;QAC9B,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;KACjD,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAChB,CAAC;AARD,4CAQC;AAED;;GAEG;AACI,KAAK,UAAU,eAAe,CACnC,iBAAoC,EACpC,UAA0B,EAAE;IAE5B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;IAEhC,OAAO,CAAC,IAAI,CAAC,WAAW,iBAAiB,CAAC,MAAM,aAAa,CAAC,CAAC;IAC/D,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,iBAAiB,EAAE,OAAO,CAAC,kBAAkB,IAAI,KAAK,CAAC,CAAC;IAE1F,IAAI,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,IAAA,kCAAqB,EAAC,UAAU,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;IAClF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACpB,QAAQ,GAAG,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAC5C,CAAC;IA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,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\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 { translations, remaining } = translator.readFromCache(snippets, true, options.includeCompilerDiagnostics);\n logging.info(`Reused ${translations.length} translations from cache`);\n snippets = 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 });\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":";;AAuGA,4CAQC;AAKD,0CAkGC;AAtND,kCAAkC;AAElC,qCAAkC;AAClC,mDAK4B;AAC5B,sCAAsC;AACtC,8DAAoF;AACpF,wCAAkE;AAClE,wCAA4C;AAC5C,gDAAyG;AAEzG,kCAA6C;AAwFtC,KAAK,UAAU,gBAAgB,CAAC,iBAA2B,EAAE,OAAuB;IACzF,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,iBAAiB,EAAE,OAAO,CAAC,CAAC;IACjE,MAAM,IAAA,eAAM,EAAC,iBAAiB,EAAE;QAC9B,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,WAAW,EAAE,OAAO,CAAC,WAAW;QAChC,mBAAmB,EAAE,OAAO,CAAC,mBAAmB;KACjD,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;GAEG;AACI,KAAK,UAAU,eAAe,CACnC,iBAAoC,EACpC,UAA0B,EAAE;IAE5B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC;IAEhC,OAAO,CAAC,IAAI,CAAC,WAAW,iBAAiB,CAAC,MAAM,aAAa,CAAC,CAAC;IAC/D,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,iBAAiB,EAAE,OAAO,CAAC,kBAAkB,IAAI,KAAK,CAAC,CAAC;IAE1F,IAAI,QA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AAC;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\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 { translations, remaining } = translator.readFromCache(snippets, true, options.includeCompilerDiagnostics);\n logging.info(`Reused ${translations.length} translations from cache`);\n snippets = 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 });\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,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.infuse = exports.DEFAULT_INFUSION_RESULTS_NAME = void 0;
3
+ exports.DEFAULT_INFUSION_RESULTS_NAME = void 0;
4
+ exports.infuse = infuse;
4
5
  const fs = require("node:fs");
5
6
  const path = require("node:path");
6
7
  const spec = require("@jsii/spec");
@@ -92,7 +93,6 @@ async function infuse(assemblyLocations, options) {
92
93
  coverageResults: coverageResults,
93
94
  };
94
95
  }
95
- exports.infuse = infuse;
96
96
  function pickBestExample(typeFqn, choices, logStream) {
97
97
  const meanResult = (0, snippet_selectors_1.mean)(choices);
98
98
  if (logStream) {
@@ -1 +1 @@
1
- {"version":3,"file":"infuse.js","sourceRoot":"","sources":["../../src/commands/infuse.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAClC,mCAAmC;AACnC,qCAA6C;AAE7C,mDAAkH;AAClH,wCAAmE;AACnE,4DAA4F;AAC5F,wCAA4C;AAC5C,gDAK4B;AAC5B,kCAAqD;AA8BxC,QA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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.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.addSnippet(\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":[],"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,4BAAQ,EAAE,OAAO,EAAP,2BAAO,EAAE,CAAC;AAEhG,MAAM,aAAa;IAAnB;QACkB,UAAK,GAAwB,EAAE,CAAC;IAQlD,CAAC;IANQ,GAAG,CAAC,GAAW,EAAE,KAAQ;QAC9B,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;YACrB,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;QACvB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;CACF;AAED;;;GAGG;AACI,KAAK,UAAU,MAAM,CAAC,iBAA2B,EAAE,OAAuB;IAC/E,IAAI,MAAM,GAA+B,SAAS,CAAC;IACnD,IAAI,OAAO,EAAE,OAAO,EAAE,CAAC;QACrB,sDAAsD;QACtD,MAAM,GAAG,EAAE,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QACtE,SAAS,CAAC,MAAM,CAAC,CAAC;IACpB,CAAC;IAED,kCAAkC;IAClC,MAAM,UAAU,GAAG,IAAA,2BAAc,EAAC,iBAAiB,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,cAAc,GAAG,M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IAAI,YAAY,EAAE,CAAC;QACjC,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,cAAc,IAAI,EAAE,EAAE,CAAC;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.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.addSnippet(\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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readTablet = void 0;
3
+ exports.readTablet = readTablet;
4
4
  const tablets_1 = require("../tablets/tablets");
5
5
  async function readTablet(tabletFile, key, lang) {
6
6
  const tab = new tablets_1.LanguageTablet();
@@ -51,7 +51,6 @@ async function readTablet(tabletFile, key, lang) {
51
51
  process.stdout.write(`${translation.source}\n`);
52
52
  }
53
53
  }
54
- exports.readTablet = readTablet;
55
54
  function snippetHeader(key) {
56
55
  return center(` ${key} `, 100, '=');
57
56
  }
@@ -1 +1 @@
1
- {"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/commands/read.ts"],"names":[],"mappings":";;;AACA,gDAAoF;AAE7E,KAAK,UAAU,UAAU,CAAC,UAAkB,EAAE,GAAY,EAAE,IAAa;IAC9E,MAAM,GAAG,GAAG,IAAI,wBAAc,EAAE,CAAC;IACjC,MAAM,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAE3B,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QACvC,IAAI,OAAO,KAAK,SAAS,EAAE,CAAC;YAC1B,MAAM,IAAI,KAAK,CAAC,oBAAoB,GAAG,EAAE,CAAC,CAAC;QAC7C,CAAC;QACD,cAAc,CAAC,OAAO,CAAC,CAAC;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K,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YAC/C,kBAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAE,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,SAAS,kBAAkB,CAAC,WAAwB;QAClD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,WAAW,CAAC,MAAM,IAAI,CAAC,CAAC;IAClD,CAAC;AACH,CAAC;AArDD,gCAqDC;AAED,SAAS,aAAa,CAAC,GAAW;IAChC,OAAO,MAAM,CAAC,IAAI,GAAG,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AACtC,CAAC;AAED,SAAS,cAAc,CAAC,GAAW;IACjC,OAAO,MAAM,CAAC,IAAI,GAAG,GAAG,EAAE,EAAE,EAAE,GAAG,CAAC,CAAC;AACrC,CAAC;AAED,SAAS,MAAM,CAAC,GAAW,EAAE,CAAS,EAAE,IAAY;IAClD,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAChD,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;IAE9C,OAAO,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;AAClF,CAAC","sourcesContent":["import { TargetLanguage } from '../languages';\nimport { LanguageTablet, TranslatedSnippet, Translation } from '../tablets/tablets';\n\nexport async function readTablet(tabletFile: string, key?: string, lang?: string) {\n const tab = new LanguageTablet();\n await tab.load(tabletFile);\n\n if (key !== undefined) {\n const snippet = tab.tryGetSnippet(key);\n if (snippet === undefined) {\n throw new Error(`No such snippet: ${key}`);\n }\n displaySnippet(snippet);\n } else {\n listSnippets();\n }\n\n function listSnippets() {\n for (const k of tab.snippetKeys) {\n process.stdout.write(`${snippetHeader(k)}\\n`);\n displaySnippet(tab.tryGetSnippet(k)!);\n process.stdout.write('\\n');\n }\n }\n\n function displaySnippet(snippet: TranslatedSnippet) {\n if (snippet.snippet.didCompile !== undefined) {\n process.stdout.write(`Compiled: ${snippet.snippet.didCompile}\\n`);\n }\n\n if (lang !== undefined) {\n const translation = snippet.get(lang as TargetLanguage);\n if (translation === undefined) {\n throw new Error(`No translation for ${lang} in snippet ${snippet.key}`);\n }\n displayTranslation(translation);\n } else {\n listTranslations(snippet);\n }\n }\n\n function listTranslations(snippet: TranslatedSnippet) {\n const original = snippet.originalSource;\n if (original !== undefined) {\n displayTranslation(original);\n }\n\n for (const l of snippet.languages) {\n process.stdout.write(`${languageHeader(l)}\\n`);\n displayTranslation(snippet.get(l)!);\n }\n }\n\n function displayTranslation(translation: Translation) {\n process.stdout.write(`${translation.source}\\n`);\n }\n}\n\nfunction snippetHeader(key: string) {\n return center(` ${key} `, 100, '=');\n}\n\nfunction languageHeader(key: string) {\n return center(` ${key} `, 30, '-');\n}\n\nfunction center(str: string, n: number, fill: string) {\n const before = Math.floor((n - str.length) / 2);\n const after = Math.ceil((n - str.length) / 2);\n\n return fill.repeat(Math.max(before, 0)) + str + fill.repeat(Math.max(after, 0));\n}\n"]}
1
+ {"version":3,"file":"read.js","sourceRoot":"","sources":["../../src/commands/read.ts"],"names":[],"mappings":";;AAGA,gCAqDC;AAvDD,gDAAoF;AAE7E,KAAK,UAAU,UAAU,CAAC,UAAkB,EAAE,GAAY,EAAE,IAAa;IAC9E,MAAM,GAAG,GAAG,IAAI,wBAAc,EAAE,CAAC;IACjC,MAAM,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IAE3B,IAAI,GAAG,KAAK,SAAS,EAAE,CAAC;QACtB,MAAM,OAAO,GAAG,GA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../languages';\nimport { LanguageTablet, TranslatedSnippet, Translation } from '../tablets/tablets';\n\nexport async function readTablet(tabletFile: string, key?: string, lang?: string) {\n const tab = new LanguageTablet();\n await tab.load(tabletFile);\n\n if (key !== undefined) {\n const snippet = tab.tryGetSnippet(key);\n if (snippet === undefined) {\n throw new Error(`No such snippet: ${key}`);\n }\n displaySnippet(snippet);\n } else {\n listSnippets();\n }\n\n function listSnippets() {\n for (const k of tab.snippetKeys) {\n process.stdout.write(`${snippetHeader(k)}\\n`);\n displaySnippet(tab.tryGetSnippet(k)!);\n process.stdout.write('\\n');\n }\n }\n\n function displaySnippet(snippet: TranslatedSnippet) {\n if (snippet.snippet.didCompile !== undefined) {\n process.stdout.write(`Compiled: ${snippet.snippet.didCompile}\\n`);\n }\n\n if (lang !== undefined) {\n const translation = snippet.get(lang as TargetLanguage);\n if (translation === undefined) {\n throw new Error(`No translation for ${lang} in snippet ${snippet.key}`);\n }\n displayTranslation(translation);\n } else {\n listTranslations(snippet);\n }\n }\n\n function listTranslations(snippet: TranslatedSnippet) {\n const original = snippet.originalSource;\n if (original !== undefined) {\n displayTranslation(original);\n }\n\n for (const l of snippet.languages) {\n process.stdout.write(`${languageHeader(l)}\\n`);\n displayTranslation(snippet.get(l)!);\n }\n }\n\n function displayTranslation(translation: Translation) {\n process.stdout.write(`${translation.source}\\n`);\n }\n}\n\nfunction snippetHeader(key: string) {\n return center(` ${key} `, 100, '=');\n}\n\nfunction languageHeader(key: string) {\n return center(` ${key} `, 30, '-');\n}\n\nfunction center(str: string, n: number, fill: string) {\n const before = Math.floor((n - str.length) / 2);\n const after = Math.ceil((n - str.length) / 2);\n\n return fill.repeat(Math.max(before, 0)) + str + fill.repeat(Math.max(after, 0));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.transliterateAssembly = void 0;
3
+ exports.transliterateAssembly = transliterateAssembly;
4
4
  const node_fs_1 = require("node:fs");
5
5
  const node_path_1 = require("node:path");
6
6
  const spec_1 = require("@jsii/spec");
@@ -73,7 +73,6 @@ async function transliterateAssembly(assemblyLocations, targetLanguages, options
73
73
  throw new Error('Strict mode is enabled and some examples failed compilation!');
74
74
  }
75
75
  }
76
- exports.transliterateAssembly = transliterateAssembly;
77
76
  /**
78
77
  * Given a set of directories containing `.jsii` assemblies, load all the
79
78
  * assemblies into the provided `Rosetta` instance and return a map of
@@ -1 +1 @@
1
- {"version":3,"file":"transliterate.js","sourceRoot":"","sources":["../../src/commands/transliterate.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,yCAAoC;AACpC,qCAAkG;AAElG,uCAA4C;AAE5C,kEAA0D;AAC1D,wCAAmC;AACnC,sDAA4E;AAC5E,wCAA6E;AA0C7E;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,qBAAqB,CACzC,iBAAoC,EACpC,eAA0C,EAC1C,UAAwC,EAAE;IAE1C,uDAAuD;IACvD,EAAE;IACF,+EAA+E;IAC/E,mFAAmF;IACnF,4CAA4C;IAC5C,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAA,yBAAe,EAAC,iBAAiB,EAAE;QAC1D,0BAA0B,EAAE,IAAI;QAChC,KAAK,EAAE,OAAO,CAAC,KAAK;QACpB,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE,KAAK;QAC7B,sBAAsB,EAAE,IAAI;KAC7B,CAAC,CAAC;IAEH,yFAAyF;IACzF,iFAAiF;IACjF,MAAM,OAAO,GAAG,IAAI,oCAAmB,CAAC;QACtC,eAAe,EAAE,OAAO,EAAE,eAAe,IAAI,mCAAkB,CAAC,IAAI;QACpE,eAAe;QACf,gBAAgB,EAAE,IAAI;KACvB,CAAC,CAAC;IACH,sCAAsC;IACtC,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnB,MAAM,OAAO,CAAC,kBAAkB,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;IACD,8CAA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AAC;YAC5F,CAAC;YACD,MAAM;QAER;YACE,MAAM,IAAI,KAAK,CAAC,0BAA2B,IAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IACpE,CAAC;IAED,SAAS,iBAAiB,CAAC,GAAgB,EAAE,IAAsB;QACjE,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,2BAA2B,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACrG,CAAC;QAED,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC;YAClB,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,EAAW,CAAC;YAC/D,MAAM,OAAO,GAAG,IAAA,4CAAkC,EAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;YAC9F,MAAM,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAChE,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;gBACxB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected taregt languages.\n *\n * @param assemblyLocations the directories which contain assemblies to\n * transliterate.\n * @param targetLanguages the languages into which to transliterate.\n * @param tabletLocation an optional Rosetta tablet file to source\n * pre-transliterated snippets from.\n *\n * @experimental\n */\nexport async function transliterateAssembly(\n assemblyLocations: readonly string[],\n targetLanguages: readonly TargetLanguage[],\n options: TransliterateAssemblyOptions = {},\n): Promise<void> {\n // Start by doing an 'extract' for all these assemblies\n //\n // This will locate all examples that haven't been translated yet and translate\n // them. Importantly: it will translate them in parallel, which is going to improve\n // performance a lot. We ignore diagnostics.\n const { tablet } = await extractSnippets(assemblyLocations, {\n includeCompilerDiagnostics: true,\n loose: options.loose,\n cacheFromFile: options.tablet,\n writeToImplicitTablets: false,\n allowDirtyTranslations: true,\n });\n\n // Now do a regular \"tablet reader\" cycle, expecting everything to be translated already,\n // and therefore it doesn't matter that we do this all in a single-threaded loop.\n const rosetta = new RosettaTabletReader({\n unknownSnippets: options?.unknownSnippets ?? UnknownSnippetMode.FAIL,\n targetLanguages,\n prefixDisclaimer: true,\n });\n // Put in the same caching tablet here\n if (options.tablet) {\n await rosetta.loadTabletFromFile(options.tablet);\n }\n // Any fresh translations we just came up with\n rosetta.addTablet(tablet);\n\n const assemblies = await loadAssemblies(assemblyLocations, rosetta);\n\n for (const [location, loadAssembly] of assemblies.entries()) {\n for (const language of targetLanguages) {\n const now = new Date().getTime();\n const result = loadAssembly();\n\n if (result.targets?.[targetName(language)] == null) {\n // This language is not supported by the assembly, so we skip it...\n continue;\n }\n\n if (result.readme?.markdown) {\n result.readme.markdown = rosetta.translateSnippetsInMarkdown(\n { api: 'moduleReadme', moduleFqn: result.name },\n result.readme.markdown,\n language,\n true /* strict */,\n );\n }\n for (const type of Object.values(result.types ?? {})) {\n transliterateType(type, rosetta, language);\n }\n // eslint-disable-next-line no-await-in-loop\n await fs.writeFile(\n resolve(options?.outdir ?? location, `${SPEC_FILE_NAME}.${language}`),\n JSON.stringify(result, null, 2),\n );\n const then = new Date().getTime();\n debug(`Done transliterating ${result.name}@${result.version} to ${language} after ${then - now} milliseconds`);\n }\n }\n\n rosetta.printDiagnostics(process.stderr, process.stderr.isTTY);\n if (rosetta.hasErrors && options.strict) {\n throw new Error('Strict mode is enabled and some examples failed compilation!');\n }\n}\n\n/**\n * Given a set of directories containing `.jsii` assemblies, load all the\n * assemblies into the provided `Rosetta` instance and return a map of\n * directories to assembly-loading functions (the function re-loads the original\n * assembly from disk on each invocation).\n *\n * @param directories the assembly-containing directories to traverse.\n * @param rosetta the `Rosetta` instance in which to load assemblies.\n *\n * @returns a map of directories to a function that loads the `.jsii` assembly\n * contained therein from disk.\n */\nasync function loadAssemblies(\n directories: readonly string[],\n rosetta: RosettaTabletReader,\n): Promise<ReadonlyMap<string, AssemblyLoader>> {\n const result = new Map<string, AssemblyLoader>();\n\n for (const directory of directories) {\n const loader = () => loadAssemblyFromPath(directory);\n // eslint-disable-next-line no-await-in-loop\n await rosetta.addAssembly(loader(), directory);\n result.set(directory, loader);\n }\n\n return result;\n}\n\ntype AssemblyLoader = () => Mutable<Assembly>;\n\nfunction transliterateType(type: Type, rosetta: RosettaTabletReader, language: TargetLanguage): void {\n transliterateDocs({ api: 'type', fqn: type.fqn }, type.docs);\n switch (type.kind) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore 7029\n case TypeKind.Class:\n if (type.initializer) {\n transliterateDocs({ api: 'initializer', fqn: type.fqn }, type.initializer.docs);\n }\n\n // fallthrough\n case TypeKind.Interface:\n for (const method of type.methods ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: method.name }, method.docs);\n for (const parameter of method.parameters ?? []) {\n transliterateDocs(\n { api: 'parameter', fqn: type.fqn, methodName: method.name, parameterName: parameter.name },\n parameter.docs,\n );\n }\n }\n for (const property of type.properties ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: property.name }, property.docs);\n }\n break;\n\n case TypeKind.Enum:\n for (const member of type.members) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: member.name }, member.docs);\n }\n break;\n\n default:\n throw new Error(`Unsupported type kind: ${(type as any).kind}`);\n }\n\n function transliterateDocs(api: ApiLocation, docs: Docs | undefined) {\n if (docs?.remarks) {\n docs.remarks = rosetta.translateSnippetsInMarkdown(api, docs.remarks, language, true /* strict */);\n }\n\n if (docs?.example) {\n const location = { api, field: { field: 'example' } } as const;\n const snippet = typeScriptSnippetFromVisibleSource(docs.example, location, true /* strict */);\n const translation = rosetta.translateSnippet(snippet, language);\n if (translation != null) {\n docs.example = translation.source;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transliterate.js","sourceRoot":"","sources":["../../src/commands/transliterate.ts"],"names":[],"mappings":";;AA+DA,sDAqEC;AApID,qCAAyC;AACzC,yCAAoC;AACpC,qCAAkG;AAElG,uCAA4C;AAE5C,kEAA0D;AAC1D,wCAAmC;AACnC,sDAA4E;AAC5E,wCAA6E;AA0C7E;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,qBAAqB,CACzC,iBAAoC,EACpC,eAA0C,EAC1C,UAAwC,EAAE;IAE1C,uDAAuD;IACvD,EAAE;IACF,+EAA+E;IAC/E,mFAAmF;IACnF,4CAA4C;IAC5C,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAA,yBAAe,EAAC,iBAAiB,EAAE;QAC1D,0BAA0B,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,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected taregt languages.\n *\n * @param assemblyLocations the directories which contain assemblies to\n * transliterate.\n * @param targetLanguages the languages into which to transliterate.\n * @param tabletLocation an optional Rosetta tablet file to source\n * pre-transliterated snippets from.\n *\n * @experimental\n */\nexport async function transliterateAssembly(\n assemblyLocations: readonly string[],\n targetLanguages: readonly TargetLanguage[],\n options: TransliterateAssemblyOptions = {},\n): Promise<void> {\n // Start by doing an 'extract' for all these assemblies\n //\n // This will locate all examples that haven't been translated yet and translate\n // them. Importantly: it will translate them in parallel, which is going to improve\n // performance a lot. We ignore diagnostics.\n const { tablet } = await extractSnippets(assemblyLocations, {\n includeCompilerDiagnostics: true,\n loose: options.loose,\n cacheFromFile: options.tablet,\n writeToImplicitTablets: false,\n allowDirtyTranslations: true,\n });\n\n // Now do a regular \"tablet reader\" cycle, expecting everything to be translated already,\n // and therefore it doesn't matter that we do this all in a single-threaded loop.\n const rosetta = new RosettaTabletReader({\n unknownSnippets: options?.unknownSnippets ?? UnknownSnippetMode.FAIL,\n targetLanguages,\n prefixDisclaimer: true,\n });\n // Put in the same caching tablet here\n if (options.tablet) {\n await rosetta.loadTabletFromFile(options.tablet);\n }\n // Any fresh translations we just came up with\n rosetta.addTablet(tablet);\n\n const assemblies = await loadAssemblies(assemblyLocations, rosetta);\n\n for (const [location, loadAssembly] of assemblies.entries()) {\n for (const language of targetLanguages) {\n const now = new Date().getTime();\n const result = loadAssembly();\n\n if (result.targets?.[targetName(language)] == null) {\n // This language is not supported by the assembly, so we skip it...\n continue;\n }\n\n if (result.readme?.markdown) {\n result.readme.markdown = rosetta.translateSnippetsInMarkdown(\n { api: 'moduleReadme', moduleFqn: result.name },\n result.readme.markdown,\n language,\n true /* strict */,\n );\n }\n for (const type of Object.values(result.types ?? {})) {\n transliterateType(type, rosetta, language);\n }\n // eslint-disable-next-line no-await-in-loop\n await fs.writeFile(\n resolve(options?.outdir ?? location, `${SPEC_FILE_NAME}.${language}`),\n JSON.stringify(result, null, 2),\n );\n const then = new Date().getTime();\n debug(`Done transliterating ${result.name}@${result.version} to ${language} after ${then - now} milliseconds`);\n }\n }\n\n rosetta.printDiagnostics(process.stderr, process.stderr.isTTY);\n if (rosetta.hasErrors && options.strict) {\n throw new Error('Strict mode is enabled and some examples failed compilation!');\n }\n}\n\n/**\n * Given a set of directories containing `.jsii` assemblies, load all the\n * assemblies into the provided `Rosetta` instance and return a map of\n * directories to assembly-loading functions (the function re-loads the original\n * assembly from disk on each invocation).\n *\n * @param directories the assembly-containing directories to traverse.\n * @param rosetta the `Rosetta` instance in which to load assemblies.\n *\n * @returns a map of directories to a function that loads the `.jsii` assembly\n * contained therein from disk.\n */\nasync function loadAssemblies(\n directories: readonly string[],\n rosetta: RosettaTabletReader,\n): Promise<ReadonlyMap<string, AssemblyLoader>> {\n const result = new Map<string, AssemblyLoader>();\n\n for (const directory of directories) {\n const loader = () => loadAssemblyFromPath(directory);\n // eslint-disable-next-line no-await-in-loop\n await rosetta.addAssembly(loader(), directory);\n result.set(directory, loader);\n }\n\n return result;\n}\n\ntype AssemblyLoader = () => Mutable<Assembly>;\n\nfunction transliterateType(type: Type, rosetta: RosettaTabletReader, language: TargetLanguage): void {\n transliterateDocs({ api: 'type', fqn: type.fqn }, type.docs);\n switch (type.kind) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore 7029\n case TypeKind.Class:\n if (type.initializer) {\n transliterateDocs({ api: 'initializer', fqn: type.fqn }, type.initializer.docs);\n }\n\n // fallthrough\n case TypeKind.Interface:\n for (const method of type.methods ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: method.name }, method.docs);\n for (const parameter of method.parameters ?? []) {\n transliterateDocs(\n { api: 'parameter', fqn: type.fqn, methodName: method.name, parameterName: parameter.name },\n parameter.docs,\n );\n }\n }\n for (const property of type.properties ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: property.name }, property.docs);\n }\n break;\n\n case TypeKind.Enum:\n for (const member of type.members) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: member.name }, member.docs);\n }\n break;\n\n default:\n throw new Error(`Unsupported type kind: ${(type as any).kind}`);\n }\n\n function transliterateDocs(api: ApiLocation, docs: Docs | undefined) {\n if (docs?.remarks) {\n docs.remarks = rosetta.translateSnippetsInMarkdown(api, docs.remarks, language, true /* strict */);\n }\n\n if (docs?.example) {\n const location = { api, field: { field: 'example' } } as const;\n const snippet = typeScriptSnippetFromVisibleSource(docs.example, location, true /* strict */);\n const translation = rosetta.translateSnippet(snippet, language);\n if (translation != null) {\n docs.example = translation.source;\n }\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.trimCache = void 0;
3
+ exports.trimCache = trimCache;
4
4
  const assemblies_1 = require("../jsii/assemblies");
5
5
  const logging = require("../logging");
6
6
  const key_1 = require("../tablets/key");
@@ -18,5 +18,4 @@ async function trimCache(options) {
18
18
  // eslint-disable-next-line prettier/prettier
19
19
  logging.info(`${options.cacheFile}: ${updated.count} snippets remaining (${original.count} - ${updated.count} trimmed)`);
20
20
  }
21
- exports.trimCache = trimCache;
22
21
  //# sourceMappingURL=trim-cache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trim-cache.js","sourceRoot":"","sources":["../../src/commands/trim-cache.ts"],"names":[],"mappings":";;;AAAA,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,SAAS,CAAC,CAAC;IAClE,MAAM,OAAO,GAAG,IAAI,wBAAc,EAAE,CAAC;IACrC,OAAO,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAA,gBAAU,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,gBAAS,CAAC,CAAC,CAAC;IAC3G,0EAA0E;IAC1E,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAEjE,6CAA6C;IAC7C,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,SAAS,KAAK,OAAO,CAAC,KAAK,wBAAwB,QAAQ,CAAC,KAAK,MAAM,OAAO,CAAC,KAAK,WAAW,CAAC,CAAC;AAC3H,CAAC;AAdD,8BAcC","sourcesContent":["import { loadAssemblies, allTypeScriptSnippets } 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.addSnippets(...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"]}
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,SAAS,CAAC,CAAC;IAClE,MAAM,OAAO,GAAG,IAAI,wBAAc,EAAE,CAAC;IACrC,OAAO,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,IAAA,gBAAU,EAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,gBAAS,CAAC,CAAC,CAAC;IAC3G,0EAA0E;IAC1E,MAAM,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAEjE,6CAA6C;IAC7C,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,SAAS,KAAK,OAAO,CAAC,KAAK,wBAAwB,QAAQ,CAAC,KAAK,MAAM,OAAO,CAAC,KAAK,WAAW,CAAC,CAAC;AAC3H,CAAC","sourcesContent":["import { loadAssemblies, allTypeScriptSnippets } 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.addSnippets(...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"]}
package/lib/find-utils.js CHANGED
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBuiltinModule = exports.findUp = exports.findPackageJsonUp = exports.findDependencyDirectory = void 0;
3
+ exports.findDependencyDirectory = findDependencyDirectory;
4
+ exports.findPackageJsonUp = findPackageJsonUp;
5
+ exports.findUp = findUp;
6
+ exports.isBuiltinModule = isBuiltinModule;
4
7
  const node_fs_1 = require("node:fs");
5
8
  const path = require("node:path");
6
9
  const util_1 = require("./util");
@@ -24,7 +27,6 @@ async function findDependencyDirectory(dependencyName, searchStart) {
24
27
  }
25
28
  return depPkgJsonPath;
26
29
  }
27
- exports.findDependencyDirectory = findDependencyDirectory;
28
30
  /**
29
31
  * Find the package.json for a given package upwards from the given directory
30
32
  *
@@ -37,7 +39,6 @@ async function findPackageJsonUp(packageName, directory) {
37
39
  return (await (0, util_1.pathExists)(pjFile)) && JSON.parse(await node_fs_1.promises.readFile(pjFile, 'utf-8')).name === packageName;
38
40
  });
39
41
  }
40
- exports.findPackageJsonUp = findPackageJsonUp;
41
42
  // eslint-disable-next-line @typescript-eslint/promise-function-async
42
43
  function findUp(directory, pred) {
43
44
  const result = pred(directory);
@@ -53,7 +54,6 @@ function findUp(directory, pred) {
53
54
  return findUp(parent, pred);
54
55
  }
55
56
  }
56
- exports.findUp = findUp;
57
57
  /**
58
58
  * Whether the given dependency is a built-in
59
59
  *
@@ -65,5 +65,4 @@ function isBuiltinModule(depName) {
65
65
  const { builtinModules } = require('node:module');
66
66
  return (builtinModules ?? []).includes(depName);
67
67
  }
68
- exports.isBuiltinModule = isBuiltinModule;
69
68
  //# sourceMappingURL=find-utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"find-utils.js","sourceRoot":"","sources":["../src/find-utils.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,kCAAkC;AAElC,iCAAoC;AAEpC;;;;;GAKG;AACI,KAAK,UAAU,uBAAuB,CAAC,cAAsB,EAAE,WAAmB;IACvF,oFAAoF;IACpF,gDAAgD;IAChD,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE;QACjD,KAAK,EAAE,CAAC,WAAW,CAAC;KACrB,CAAC,CAAC;IAEH,8EAA8E;IAC9E,6EAA6E;IAC7E,MAAM,cAAc,GAAG,MAAM,iBAAiB,CAAC,cAAc,EAAE,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;IAEzF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,IAAI,KAAK,CAAC,8BAA8B,cAAc,WAAW,WAAW,GAAG,CAAC,CAAC;IACzF,CAAC;IAED,OAAO,cAAc,CAAC;AACxB,CAAC;AAhBD,0DAgBC;AAED;;;;;GAKG;AACI,KAAK,UAAU,iBAAiB,CAAC,WAAmB,EAAE,SAAiB;IAC5E,OAAO,MAAM,CAAC,SAAS,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC;QAC9C,OAAO,CAAC,MAAM,IAAA,iBAAU,EAAC,MAAM,CAAC,CAAC,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAE,CAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,WAAW,CAAC;IAC3G,CAAC,CAAC,CAAC;AACL,CAAC;AALD,8CAKC;AAYD,qEAAqE;AACrE,SAAgB,MAAM,CACpB,SAAiB,EACjB,IAAiD;IAEjD,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/B,IAAI,MAAM,YAAY,OAAO,EAAE,CAAC;QAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IACjF,CAAC;IAED,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;IAEtC,SAAS,OAAO;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACvC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,EAAE,IAAW,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAlBD,wBAkBC;AAED;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,OAAe;IAC7C,oGAAoG;IACpG,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAClD,OAAO,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClD,CAAC;AAJD,0CAIC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\n\nimport { pathExists } from './util';\n\n/**\n * Find the directory that contains a given dependency, identified by its 'package.json', from a starting search directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport async function findDependencyDirectory(dependencyName: string, searchStart: string) {\n // Explicitly do not use 'require(\"dep/package.json\")' because that will fail if the\n // package does not export that particular file.\n const entryPoint = require.resolve(dependencyName, {\n paths: [searchStart],\n });\n\n // Search up from the given directory, looking for a package.json that matches\n // the dependency name (so we don't accidentally find stray 'package.jsons').\n const depPkgJsonPath = await findPackageJsonUp(dependencyName, path.dirname(entryPoint));\n\n if (!depPkgJsonPath) {\n throw new Error(`Could not find dependency '${dependencyName}' from '${searchStart}'`);\n }\n\n return depPkgJsonPath;\n}\n\n/**\n * Find the package.json for a given package upwards from the given directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport async function findPackageJsonUp(packageName: string, directory: string) {\n return findUp(directory, async (dir) => {\n const pjFile = path.join(dir, 'package.json');\n return (await pathExists(pjFile)) && JSON.parse(await fs.readFile(pjFile, 'utf-8')).name === packageName;\n });\n}\n\n/**\n * Find a directory up the tree from a starting directory matching a condition\n *\n * Will return `undefined` if no directory matches\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findUp(directory: string, pred: (dir: string) => Promise<boolean>): Promise<string | undefined>;\nexport function findUp(directory: string, pred: (dir: string) => boolean): string | undefined;\n// eslint-disable-next-line @typescript-eslint/promise-function-async\nexport function findUp(\n directory: string,\n pred: (dir: string) => boolean | Promise<boolean>,\n): Promise<string | undefined> | string | undefined {\n const result = pred(directory);\n if (result instanceof Promise) {\n return result.then((thisDirectory) => (thisDirectory ? directory : recurse()));\n }\n\n return result ? directory : recurse();\n\n function recurse() {\n const parent = path.dirname(directory);\n if (parent === directory) {\n return undefined;\n }\n return findUp(parent, pred as any);\n }\n}\n\n/**\n * Whether the given dependency is a built-in\n *\n * Some dependencies that occur in `package.json` are also built-ins in modern Node\n * versions (most egregious example: 'punycode'). Detect those and filter them out.\n */\nexport function isBuiltinModule(depName: string) {\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n const { builtinModules } = require('node:module');\n return (builtinModules ?? []).includes(depName);\n}\n"]}
1
+ {"version":3,"file":"find-utils.js","sourceRoot":"","sources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QAC9B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IACjF,CAAC;IAED,OAAO,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;IAEtC,SAAS,OAAO;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACvC,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,OAAO,MAAM,CAAC,MAAM,EAAE,IAAW,CAAC,CAAC;IACrC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAgB,eAAe,CAAC,OAAe;IAC7C,oGAAoG;IACpG,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IAClD,OAAO,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAClD,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\n\nimport { pathExists } from './util';\n\n/**\n * Find the directory that contains a given dependency, identified by its 'package.json', from a starting search directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport async function findDependencyDirectory(dependencyName: string, searchStart: string) {\n // Explicitly do not use 'require(\"dep/package.json\")' because that will fail if the\n // package does not export that particular file.\n const entryPoint = require.resolve(dependencyName, {\n paths: [searchStart],\n });\n\n // Search up from the given directory, looking for a package.json that matches\n // the dependency name (so we don't accidentally find stray 'package.jsons').\n const depPkgJsonPath = await findPackageJsonUp(dependencyName, path.dirname(entryPoint));\n\n if (!depPkgJsonPath) {\n throw new Error(`Could not find dependency '${dependencyName}' from '${searchStart}'`);\n }\n\n return depPkgJsonPath;\n}\n\n/**\n * Find the package.json for a given package upwards from the given directory\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport async function findPackageJsonUp(packageName: string, directory: string) {\n return findUp(directory, async (dir) => {\n const pjFile = path.join(dir, 'package.json');\n return (await pathExists(pjFile)) && JSON.parse(await fs.readFile(pjFile, 'utf-8')).name === packageName;\n });\n}\n\n/**\n * Find a directory up the tree from a starting directory matching a condition\n *\n * Will return `undefined` if no directory matches\n *\n * (This code is duplicated among jsii/jsii-pacmak/jsii-reflect. Changes should be done in all\n * 3 locations, and we should unify these at some point: https://github.com/aws/jsii/issues/3236)\n */\nexport function findUp(directory: string, pred: (dir: string) => Promise<boolean>): Promise<string | undefined>;\nexport function findUp(directory: string, pred: (dir: string) => boolean): string | undefined;\n// eslint-disable-next-line @typescript-eslint/promise-function-async\nexport function findUp(\n directory: string,\n pred: (dir: string) => boolean | Promise<boolean>,\n): Promise<string | undefined> | string | undefined {\n const result = pred(directory);\n if (result instanceof Promise) {\n return result.then((thisDirectory) => (thisDirectory ? directory : recurse()));\n }\n\n return result ? directory : recurse();\n\n function recurse() {\n const parent = path.dirname(directory);\n if (parent === directory) {\n return undefined;\n }\n return findUp(parent, pred as any);\n }\n}\n\n/**\n * Whether the given dependency is a built-in\n *\n * Some dependencies that occur in `package.json` are also built-ins in modern Node\n * versions (most egregious example: 'punycode'). Detect those and filter them out.\n */\nexport function isBuiltinModule(depName: string) {\n // eslint-disable-next-line @typescript-eslint/no-require-imports,@typescript-eslint/no-var-requires\n const { builtinModules } = require('node:module');\n return (builtinModules ?? []).includes(depName);\n}\n"]}
package/lib/fixtures.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fixturize = void 0;
3
+ exports.fixturize = fixturize;
4
4
  const fs = require("node:fs");
5
5
  const path = require("node:path");
6
6
  const typescript_1 = require("typescript");
@@ -44,7 +44,6 @@ function fixturize(snippet, loose = false) {
44
44
  parameters,
45
45
  };
46
46
  }
47
- exports.fixturize = fixturize;
48
47
  function loadLiterateSource(directory, literateFileName) {
49
48
  const fullPath = path.join(directory, literateFileName);
50
49
  const exists = fs.existsSync(fullPath);
@@ -1 +1 @@
1
- {"version":3,"file":"fixtures.js","sourceRoot":"","sources":["../src/fixtures.ts"],"names":[],"mappings":";;;AAAA,8BAA8B;AAC9B,kCAAkC;AAClC,2CAAoF;AAEpF,uCAA8E;AAE9E;;GAEG;AACH,SAAgB,SAAS,CAAC,OAA0B,EAAE,KAAK,GAAG,KAAK;IACjE,IAAI,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IACnC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;IAE5C,MAAM,SAAS,GAAG,UAAU,CAAC,2BAAiB,CAAC,kBAAkB,CAAC,CAAC;IACnE,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,cAAc,GAAG,UAAU,CAAC,2BAAiB,CAAC,eAAe,CAAC,CAAC;IACrE,IAAI,cAAc,EAAE,CAAC;QACnB,mEAAmE;QACnE,uEAAuE;QACvE,IAAI,CAAC;YACH,MAAM,GAAG,kBAAkB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QACzD,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,yEAAyE;YACzE,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,MAAM,EAAE,CAAC;YACX,CAAC;QACH,CAAC;QACD,UAAU,CAAC,2BAAiB,CAAC,sBAAsB,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;IAC5G,CAAC;SAAM,IAAI,UAAU,CAAC,2BAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;Q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C,UAAU,EAAE,MAAM,EAAE,yBAAY,CAAC,MAAM,EAAE,IAAI,EAAE,uBAAU,CAAC,EAAE,CAAC,CAAC;IAClG,KAAK,MAAM,SAAS,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC;QAC9C,IACE,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,iBAAiB;YAC/C,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,uBAAuB;YACrD,CAAC,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,iBAAiB;gBAC9C,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,KAAK,uBAAU,CAAC,cAAc,CAAC,EAC7E,CAAC;YACD,OAAO,IAAI,SAAS,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAC/C,CAAC;aAAM,CAAC;YACN,UAAU,IAAI,SAAS,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;AACjC,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { createSourceFile, ScriptKind, ScriptTarget, SyntaxKind } from 'typescript';\n\nimport { TypeScriptSnippet, SnippetParameters, ApiLocation } from './snippet';\n\n/**\n * Complete snippets with fixtures, if required\n */\nexport function fixturize(snippet: TypeScriptSnippet, loose = false): TypeScriptSnippet {\n let source = snippet.visibleSource;\n const parameters = snippet.parameters ?? {};\n\n const directory = parameters[SnippetParameters.$PROJECT_DIRECTORY];\n if (!directory) {\n return snippet;\n }\n\n const literateSource = parameters[SnippetParameters.LITERATE_SOURCE];\n if (literateSource) {\n // Compatibility with the \"old school\" example inclusion mechanism.\n // Completely load this file and attach a parameter with its directory.\n try {\n source = loadLiterateSource(directory, literateSource);\n } catch (ex) {\n // In loose mode, we ignore this failure and stick to the visible source.\n if (!loose) {\n throw ex;\n }\n }\n parameters[SnippetParameters.$COMPILATION_DIRECTORY] = path.join(directory, path.dirname(literateSource));\n } else if (parameters[SnippetParameters.FIXTURE]) {\n // Explicitly requested fixture must exist, unless we are operating in loose mode\n source = loadAndSubFixture(directory, snippet.location.api, parameters.fixture, source, !loose);\n } else if (parameters[SnippetParameters.NO_FIXTURE] === undefined) {\n // Don't explicitly request no fixture, load the default.\n source = loadAndSubFixture(directory, snippet.location.api, 'default', source, false);\n }\n\n return {\n ...snippet,\n completeSource: source,\n parameters,\n };\n}\n\nfunction loadLiterateSource(directory: string, literateFileName: string) {\n const fullPath = path.join(directory, literateFileName);\n const exists = fs.existsSync(fullPath);\n if (!exists) {\n // This couldn't really happen in practice, but do the check anyway\n throw new Error(`Sample uses literate source ${literateFileName}, but not found: ${fullPath}`);\n }\n return fs.readFileSync(fullPath).toString('utf-8');\n}\n\n/**\n * Load the fixture with the given name, and substitute the source into it\n *\n * If no fixture could be found and `mustExist` is true, and error will be thrown.\n *\n * In principle, the fixture we're looking for is `rosetta/FIXTURE.ts-fixture`.\n * However, we want to support an automatic transform of many small packages\n * combined into a single large package, perhaps into submodules (i.e., we want\n * to support monocdk), and in those cases the names of fixtures might conflict.\n * For example, all of them will have a `default.ts-fixture`, and there won't be\n * any explicit reference to that file anywhere... yet in the combined\n * monopackage we have to distinguish those fixtures.\n *\n * Therefore, we will consider submodule names as subdirectories, based on the\n * API location of the snippet we're fixturizing.\n *\n * (For example, the fixtures for a type called `monocdk.aws_s3.Bucket` will be\n * searched both in `rosetta/aws_s3/default.ts-fixture` as well as\n * `rosetta/default.ts-fixture`).\n */\nfunction loadAndSubFixture(\n directory: string,\n location: ApiLocation,\n fixtureName: string,\n source: string,\n mustExist: boolean,\n) {\n const candidates = fixtureCandidates(directory, fixtureName, location);\n const fixtureFileName = candidates.find((n) => fs.existsSync(n));\n\n if (!fixtureFileName) {\n if (mustExist) {\n throw new Error(`Sample uses fixture ${fixtureName}, but not found: ${JSON.stringify(candidates)}`);\n }\n return source;\n }\n\n const fixtureContents = fs.readFileSync(fixtureFileName, {\n encoding: 'utf-8',\n });\n\n const subRegex = /[/]{3}[ \\t]*here[ \\t]*$/im;\n if (!subRegex.test(fixtureContents)) {\n throw new Error(`Fixture does not contain '/// here': ${fixtureFileName}`);\n }\n\n const { imports, statements } = sidelineImports(source);\n const show = '/// !show';\n const hide = '/// !hide';\n\n const result = fixtureContents.replace(\n subRegex,\n [\n '// Code snippet begins after !show marker below',\n show,\n statements,\n hide,\n '// Code snippet ended before !hide marker above',\n ].join('\\n'),\n );\n\n return imports\n ? [\n '// Hoisted imports begin after !show marker below',\n show,\n imports,\n hide,\n '// Hoisted imports ended before !hide marker above',\n result,\n ].join('\\n')\n : result;\n}\n\nfunction fixtureCandidates(directory: string, fixtureName: string, location: ApiLocation): string[] {\n const ret = new Array<string>();\n const fileName = `${fixtureName}.ts-fixture`;\n const mods = submodules(location);\n\n ret.push(path.join(directory, 'rosetta', fileName));\n for (let i = 0; i < mods.length; i++) {\n ret.push(path.join(directory, 'rosetta', ...mods.slice(0, i + 1), fileName));\n }\n\n // Most specific one up front\n ret.reverse();\n return ret;\n}\n\n/**\n * Return the submodule parts from a given ApiLocation\n */\nfunction submodules(location: ApiLocation): string[] {\n switch (location.api) {\n case 'file':\n return [];\n case 'initializer':\n case 'member':\n case 'type':\n case 'parameter':\n return middle(location.fqn.split('.'));\n case 'moduleReadme':\n return location.moduleFqn.split('.').slice(1);\n }\n\n function middle(xs: string[]) {\n return xs.slice(1, xs.length - 1);\n }\n}\n\n/**\n * When embedding code fragments in a fixture, \"import\" statements must be\n * hoisted up to the top of the resulting document, as TypeScript only allows\n * those to be present in the top-level context of an ESM.\n *\n * @param source a block of TypeScript source\n *\n * @returns an object containing the import statements on one end, and the rest\n * on the other hand.\n */\nfunction sidelineImports(source: string): {\n imports: string;\n statements: string;\n} {\n let imports = '';\n let statements = '';\n\n const sourceFile = createSourceFile('index.ts', source, ScriptTarget.Latest, true, ScriptKind.TS);\n for (const statement of sourceFile.statements) {\n if (\n statement.kind === SyntaxKind.ImportDeclaration ||\n statement.kind === SyntaxKind.ImportEqualsDeclaration ||\n (statement.kind === SyntaxKind.VariableStatement &&\n statement.getChildAt(0)?.getChildAt(0)?.kind === SyntaxKind.DeclareKeyword)\n ) {\n imports += statement.getFullText(sourceFile);\n } else {\n statements += statement.getFullText(sourceFile);\n }\n }\n\n return { imports, statements };\n}\n"]}
1
+ {"version":3,"file":"fixtures.js","sourceRoot":"","sources":["../src/fixtures.ts"],"names":[],"mappings":";;AASA,8BAmCC;AA5CD,8BAA8B;AAC9B,kCAAkC;AAClC,2CAAoF;AAEpF,uCAA8E;AAE9E;;GAEG;AACH,SAAgB,SAAS,CAAC,OAA0B,EAAE,KAAK,GAAG,KAAK;IACjE,IAAI,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IACnC,MAAM,UAAU,GAAG,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;IAE5C,MAAM,SAAS,GAAG,UAAU,CAAC,2BAAiB,CAAC,kBAAkB,CAAC,CAAC;IACnE,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,cAAc,GAAG,UAAU,CAAC,2BAAiB,CAAC,eAAe,CAAC,CAAC;IACrE,IAAI,cAAc,EAAE,CAAC;QACnB,mEAAmE;QACnE,uEAAuE;QACvE,IAAI,CAAC;YACH,MAAM,GAAG,kBAAkB,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QACzD,CAAC;QAAC,OAAO,EAAE,EAAE,CAAC;YACZ,yEAAyE;YACzE,IAAI,CAAC,KAAK,EAAE,CAAC;gBACX,MAAM,EAAE,CAAC;YACX,CAAC;QACH,CAAC;QACD,UAAU,CAAC,2BAAiB,CAAC,sBAAsB,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC;IAC5G,CAAC;SAAM,IAAI,UAAU,CAAC,2BAAiB,CA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,6BAAgB,EAAC,UAAU,EAAE,MAAM,EAAE,yBAAY,CAAC,MAAM,EAAE,IAAI,EAAE,uBAAU,CAAC,EAAE,CAAC,CAAC;IAClG,KAAK,MAAM,SAAS,IAAI,UAAU,CAAC,UAAU,EAAE,CAAC;QAC9C,IACE,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,iBAAiB;YAC/C,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,uBAAuB;YACrD,CAAC,SAAS,CAAC,IAAI,KAAK,uBAAU,CAAC,iBAAiB;gBAC9C,SAAS,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,IAAI,KAAK,uBAAU,CAAC,cAAc,CAAC,EAC7E,CAAC;YACD,OAAO,IAAI,SAAS,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAC/C,CAAC;aAAM,CAAC;YACN,UAAU,IAAI,SAAS,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC;QAClD,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;AACjC,CAAC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { createSourceFile, ScriptKind, ScriptTarget, SyntaxKind } from 'typescript';\n\nimport { TypeScriptSnippet, SnippetParameters, ApiLocation } from './snippet';\n\n/**\n * Complete snippets with fixtures, if required\n */\nexport function fixturize(snippet: TypeScriptSnippet, loose = false): TypeScriptSnippet {\n let source = snippet.visibleSource;\n const parameters = snippet.parameters ?? {};\n\n const directory = parameters[SnippetParameters.$PROJECT_DIRECTORY];\n if (!directory) {\n return snippet;\n }\n\n const literateSource = parameters[SnippetParameters.LITERATE_SOURCE];\n if (literateSource) {\n // Compatibility with the \"old school\" example inclusion mechanism.\n // Completely load this file and attach a parameter with its directory.\n try {\n source = loadLiterateSource(directory, literateSource);\n } catch (ex) {\n // In loose mode, we ignore this failure and stick to the visible source.\n if (!loose) {\n throw ex;\n }\n }\n parameters[SnippetParameters.$COMPILATION_DIRECTORY] = path.join(directory, path.dirname(literateSource));\n } else if (parameters[SnippetParameters.FIXTURE]) {\n // Explicitly requested fixture must exist, unless we are operating in loose mode\n source = loadAndSubFixture(directory, snippet.location.api, parameters.fixture, source, !loose);\n } else if (parameters[SnippetParameters.NO_FIXTURE] === undefined) {\n // Don't explicitly request no fixture, load the default.\n source = loadAndSubFixture(directory, snippet.location.api, 'default', source, false);\n }\n\n return {\n ...snippet,\n completeSource: source,\n parameters,\n };\n}\n\nfunction loadLiterateSource(directory: string, literateFileName: string) {\n const fullPath = path.join(directory, literateFileName);\n const exists = fs.existsSync(fullPath);\n if (!exists) {\n // This couldn't really happen in practice, but do the check anyway\n throw new Error(`Sample uses literate source ${literateFileName}, but not found: ${fullPath}`);\n }\n return fs.readFileSync(fullPath).toString('utf-8');\n}\n\n/**\n * Load the fixture with the given name, and substitute the source into it\n *\n * If no fixture could be found and `mustExist` is true, and error will be thrown.\n *\n * In principle, the fixture we're looking for is `rosetta/FIXTURE.ts-fixture`.\n * However, we want to support an automatic transform of many small packages\n * combined into a single large package, perhaps into submodules (i.e., we want\n * to support monocdk), and in those cases the names of fixtures might conflict.\n * For example, all of them will have a `default.ts-fixture`, and there won't be\n * any explicit reference to that file anywhere... yet in the combined\n * monopackage we have to distinguish those fixtures.\n *\n * Therefore, we will consider submodule names as subdirectories, based on the\n * API location of the snippet we're fixturizing.\n *\n * (For example, the fixtures for a type called `monocdk.aws_s3.Bucket` will be\n * searched both in `rosetta/aws_s3/default.ts-fixture` as well as\n * `rosetta/default.ts-fixture`).\n */\nfunction loadAndSubFixture(\n directory: string,\n location: ApiLocation,\n fixtureName: string,\n source: string,\n mustExist: boolean,\n) {\n const candidates = fixtureCandidates(directory, fixtureName, location);\n const fixtureFileName = candidates.find((n) => fs.existsSync(n));\n\n if (!fixtureFileName) {\n if (mustExist) {\n throw new Error(`Sample uses fixture ${fixtureName}, but not found: ${JSON.stringify(candidates)}`);\n }\n return source;\n }\n\n const fixtureContents = fs.readFileSync(fixtureFileName, {\n encoding: 'utf-8',\n });\n\n const subRegex = /[/]{3}[ \\t]*here[ \\t]*$/im;\n if (!subRegex.test(fixtureContents)) {\n throw new Error(`Fixture does not contain '/// here': ${fixtureFileName}`);\n }\n\n const { imports, statements } = sidelineImports(source);\n const show = '/// !show';\n const hide = '/// !hide';\n\n const result = fixtureContents.replace(\n subRegex,\n [\n '// Code snippet begins after !show marker below',\n show,\n statements,\n hide,\n '// Code snippet ended before !hide marker above',\n ].join('\\n'),\n );\n\n return imports\n ? [\n '// Hoisted imports begin after !show marker below',\n show,\n imports,\n hide,\n '// Hoisted imports ended before !hide marker above',\n result,\n ].join('\\n')\n : result;\n}\n\nfunction fixtureCandidates(directory: string, fixtureName: string, location: ApiLocation): string[] {\n const ret = new Array<string>();\n const fileName = `${fixtureName}.ts-fixture`;\n const mods = submodules(location);\n\n ret.push(path.join(directory, 'rosetta', fileName));\n for (let i = 0; i < mods.length; i++) {\n ret.push(path.join(directory, 'rosetta', ...mods.slice(0, i + 1), fileName));\n }\n\n // Most specific one up front\n ret.reverse();\n return ret;\n}\n\n/**\n * Return the submodule parts from a given ApiLocation\n */\nfunction submodules(location: ApiLocation): string[] {\n switch (location.api) {\n case 'file':\n return [];\n case 'initializer':\n case 'member':\n case 'type':\n case 'parameter':\n return middle(location.fqn.split('.'));\n case 'moduleReadme':\n return location.moduleFqn.split('.').slice(1);\n }\n\n function middle(xs: string[]) {\n return xs.slice(1, xs.length - 1);\n }\n}\n\n/**\n * When embedding code fragments in a fixture, \"import\" statements must be\n * hoisted up to the top of the resulting document, as TypeScript only allows\n * those to be present in the top-level context of an ESM.\n *\n * @param source a block of TypeScript source\n *\n * @returns an object containing the import statements on one end, and the rest\n * on the other hand.\n */\nfunction sidelineImports(source: string): {\n imports: string;\n statements: string;\n} {\n let imports = '';\n let statements = '';\n\n const sourceFile = createSourceFile('index.ts', source, ScriptTarget.Latest, true, ScriptKind.TS);\n for (const statement of sourceFile.statements) {\n if (\n statement.kind === SyntaxKind.ImportDeclaration ||\n statement.kind === SyntaxKind.ImportEqualsDeclaration ||\n (statement.kind === SyntaxKind.VariableStatement &&\n statement.getChildAt(0)?.getChildAt(0)?.kind === SyntaxKind.DeclareKeyword)\n ) {\n imports += statement.getFullText(sourceFile);\n } else {\n statements += statement.getFullText(sourceFile);\n }\n }\n\n return { imports, statements };\n}\n"]}