jsii-rosetta 5.2.8-dev.1 → 5.3.1-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +50 -43
  2. package/lib/commands/coverage.js.map +1 -1
  3. package/lib/commands/extract.js.map +1 -1
  4. package/lib/commands/infuse.js.map +1 -1
  5. package/lib/commands/read.js.map +1 -1
  6. package/lib/commands/transliterate.js.map +1 -1
  7. package/lib/find-utils.js.map +1 -1
  8. package/lib/fixtures.js.map +1 -1
  9. package/lib/jsii/assemblies.js.map +1 -1
  10. package/lib/jsii/fingerprinting.js.map +1 -1
  11. package/lib/jsii/jsii-types.js.map +1 -1
  12. package/lib/jsii/jsii-utils.js +1 -1
  13. package/lib/jsii/jsii-utils.js.map +1 -1
  14. package/lib/jsii/packages.js.map +1 -1
  15. package/lib/languages/csharp.js +1 -1
  16. package/lib/languages/csharp.js.map +1 -1
  17. package/lib/languages/default.js.map +1 -1
  18. package/lib/languages/go.js +1 -1
  19. package/lib/languages/go.js.map +1 -1
  20. package/lib/languages/java.js +1 -1
  21. package/lib/languages/java.js.map +1 -1
  22. package/lib/languages/python.js.map +1 -1
  23. package/lib/languages/record-references.js.map +1 -1
  24. package/lib/languages/target-language.js.map +1 -1
  25. package/lib/logging.js.map +1 -1
  26. package/lib/main.js.map +1 -1
  27. package/lib/markdown/escapes.js.map +1 -1
  28. package/lib/markdown/markdown-renderer.js.map +1 -1
  29. package/lib/markdown/markdown.js.map +1 -1
  30. package/lib/markdown/replace-typescript-transform.js.map +1 -1
  31. package/lib/markdown/structure-renderer.js.map +1 -1
  32. package/lib/markdown/xml-comment-renderer.js.map +1 -1
  33. package/lib/o-tree.js.map +1 -1
  34. package/lib/renderer.js.map +1 -1
  35. package/lib/rosetta-reader.js.map +1 -1
  36. package/lib/rosetta-translator.js.map +1 -1
  37. package/lib/snippet-dependencies.js.map +1 -1
  38. package/lib/snippet-selectors.js.map +1 -1
  39. package/lib/snippet.js.map +1 -1
  40. package/lib/submodule-reference.js.map +1 -1
  41. package/lib/support.js.map +1 -1
  42. package/lib/tablets/tablets.js.map +1 -1
  43. package/lib/translate.js.map +1 -1
  44. package/lib/translate_all.js.map +1 -1
  45. package/lib/translate_all_worker.js.map +1 -1
  46. package/lib/typescript/ast-utils.js.map +1 -1
  47. package/lib/typescript/imports.js +1 -1
  48. package/lib/typescript/imports.js.map +1 -1
  49. package/lib/typescript/syntax-kind-counter.js.map +1 -1
  50. package/lib/typescript/ts-compiler.js +2 -2
  51. package/lib/typescript/ts-compiler.js.map +1 -1
  52. package/lib/typescript/types.js.map +1 -1
  53. package/lib/typescript/visible-spans.js.map +1 -1
  54. package/lib/util.js.map +1 -1
  55. package/package.json +8 -6
  56. package/releases.json +4 -2
@@ -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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EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;aAC3F;YACD,MAAM;QAER;YACE,MAAM,IAAI,KAAK,CAAC,0BAA2B,IAAY,CAAC,IAAI,EAAE,CAAC,CAAC;KACnE;IAED,SAAS,iBAAiB,CAAC,GAAgB,EAAE,IAAsB;QACjE,IAAI,IAAI,EAAE,OAAO,EAAE;YACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,2BAA2B,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;SACpG;QAED,IAAI,IAAI,EAAE,OAAO,EAAE;YACjB,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;gBACvB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;aACnC;SACF;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":";;;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;QAC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,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 +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;QACnB,MAAM,IAAI,KAAK,CAAC,8BAA8B,cAAc,WAAW,WAAW,GAAG,CAAC,CAAC;KACxF;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;QAC7B,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;KAChF;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;YACxB,OAAO,SAAS,CAAC;SAClB;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":["../src/find-utils.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,kCAAkC;AAElC,i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,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 +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,M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AAE,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":";;;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,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AED,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 +1 @@
1
- {"version":3,"file":"assemblies.js","sourceRoot":"","sources":["../../src/jsii/assemblies.ts"],"names":[],"mappings":";;;AAAA,qCAAiD;AACjD,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA0F;AAC1F,mCAAmC;AACnC,0CAAwC;AACxC,mEAAqF;AACrF,wCASoB;AACpB,kEAA6E;AAC7E,sCAA+C;AAC/C,gDAAyG;AACzG,kCAA2D;AAE3D;;;;;;;;;;;;;GAaG;AACU,QAAA,yBAAyB,GAAG,iBAAiB,CAAC;AAe3D;;GAEG;AACH,SAAgB,cAAc,CAC5B,iBAAoC,EACpC,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AAC","sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadAssemblyFromFile, loadAssemblyFromPath, findAssemblyFile } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { fixturize } from '../fixtures';\nimport { extractTypescriptSnippetsFromMarkdown } from '../markdown/extract-snippets';\nimport {\n TypeScriptSnippet,\n typeScriptSnippetFromSource,\n updateParameters,\n SnippetParameters,\n ApiLocation,\n parseMetadataLine,\n CompilationDependency,\n INITIALIZER_METHOD_NAME,\n} from '../snippet';\nimport { resolveDependenciesFromPackageJson } from '../snippet-dependencies';\nimport { enforcesStrictMode } from '../strict';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { fmap, mkDict, pathExists, sortBy } from '../util';\n\n/**\n * The JSDoc tag users can use to associate non-visible metadata with an example\n *\n * In a Markdown section, metadata goes after the code block fence, where it will\n * be attached to the example but invisible.\n *\n * ```ts metadata=goes here\n *\n * But in doc comments, '@example' already delineates the example, and any metadata\n * in there added by the '///' tags becomes part of the visible code (there is no\n * place to put hidden information).\n *\n * We introduce the '@exampleMetadata' tag to put that additional information.\n */\nexport const EXAMPLE_METADATA_JSDOCTAG = 'exampleMetadata';\n\ninterface RosettaPackageJson extends spec.PackageJson {\n readonly jsiiRosetta?: {\n readonly strict?: boolean;\n readonly exampleDependencies?: Record<string, string>;\n };\n}\n\nexport interface LoadedAssembly {\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly packageJson?: RosettaPackageJson;\n}\n\n/**\n * Load assemblies by filename or directory\n */\nexport function loadAssemblies(\n assemblyLocations: readonly string[],\n validateAssemblies: boolean,\n): readonly LoadedAssembly[] {\n return assemblyLocations.map(loadAssembly);\n\n function loadAssembly(location: string): LoadedAssembly {\n const stat = fs.statSync(location);\n if (stat.isDirectory()) {\n return loadAssembly(findAssemblyFile(location));\n }\n\n const directory = path.dirname(location);\n const pjLocation = path.join(directory, 'package.json');\n\n const assembly = loadAssemblyFromFile(location, validateAssemblies);\n const packageJson = fs.existsSync(pjLocation) ? JSON.parse(fs.readFileSync(pjLocation, 'utf-8')) : undefined;\n\n return { assembly, directory, packageJson };\n }\n}\n\n/**\n * Load the default tablets for every assembly, if available\n *\n * Returns a map of { directory -> tablet }.\n */\nexport async function loadAllDefaultTablets(asms: readonly LoadedAssembly[]): Promise<Record<string, LanguageTablet>> {\n return mkDict(\n await Promise.all(\n asms.map(\n async (a) => [a.directory, await LanguageTablet.fromOptionalFile(guessTabletLocation(a.directory))] as const,\n ),\n ),\n );\n}\n\n/**\n * Returns the location of the tablet file, either .jsii.tabl.json or .jsii.tabl.json.gz.\n * Assumes that a tablet exists in the directory and if not, the ensuing behavior is\n * handled by the caller of this function.\n */\nexport function guessTabletLocation(directory: string) {\n return compressedTabletExists(directory)\n ? path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED)\n : path.join(directory, DEFAULT_TABLET_NAME);\n}\n\nexport function compressedTabletExists(directory: string) {\n return fs.existsSync(path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED));\n}\n\nexport type AssemblySnippetSource =\n | { type: 'markdown'; markdown: string; location: ApiLocation }\n | { type: 'example'; source: string; metadata?: { [key: string]: string }; location: ApiLocation };\n\n/**\n * Return all markdown and example snippets from the given assembly\n */\nexport function allSnippetSources(assembly: spec.Assembly): AssemblySnippetSource[] {\n const ret: AssemblySnippetSource[] = [];\n\n if (assembly.readme) {\n ret.push({\n type: 'markdown',\n markdown: assembly.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: assembly.name },\n });\n }\n\n for (const [submoduleFqn, submodule] of Object.entries(assembly.submodules ?? {})) {\n if (submodule.readme) {\n ret.push({\n type: 'markdown',\n markdown: submodule.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: submoduleFqn },\n });\n }\n }\n\n if (assembly.types) {\n for (const type of Object.values(assembly.types)) {\n emitDocs(type.docs, { api: 'type', fqn: type.fqn });\n\n if (spec.isEnumType(type)) {\n for (const m of type.members) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n if (spec.isClassType(type)) {\n emitDocsForCallable(type.initializer, type.fqn);\n }\n if (spec.isClassOrInterfaceType(type)) {\n for (const m of type.methods ?? []) emitDocsForCallable(m, type.fqn, m.name);\n for (const m of type.properties ?? []) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n }\n }\n\n return ret;\n\n function emitDocsForCallable(callable: spec.Callable | undefined, fqn: string, memberName?: string) {\n if (!callable) {\n return;\n }\n emitDocs(callable.docs, memberName ? { api: 'member', fqn, memberName } : { api: 'initializer', fqn });\n\n for (const parameter of callable.parameters ?? []) {\n emitDocs(parameter.docs, {\n api: 'parameter',\n fqn: fqn,\n methodName: memberName ?? INITIALIZER_METHOD_NAME,\n parameterName: parameter.name,\n });\n }\n }\n\n function emitDocs(docs: spec.Docs | undefined, location: ApiLocation) {\n if (!docs) {\n return;\n }\n\n if (docs.remarks) {\n ret.push({\n type: 'markdown',\n markdown: docs.remarks,\n location,\n });\n }\n if (docs.example) {\n ret.push({\n type: 'example',\n source: docs.example,\n metadata: fmap(docs.custom?.[EXAMPLE_METADATA_JSDOCTAG], parseMetadataLine),\n location,\n });\n }\n }\n}\n\nexport async function allTypeScriptSnippets(\n assemblies: readonly LoadedAssembly[],\n loose = false,\n): Promise<TypeScriptSnippet[]> {\n return Promise.all(\n assemblies\n .flatMap((loaded) => allSnippetSources(loaded.assembly).map((source) => ({ source, loaded })))\n .flatMap(({ source, loaded }) => {\n switch (source.type) {\n case 'example':\n return [\n {\n snippet: updateParameters(\n typeScriptSnippetFromSource(\n source.source,\n { api: source.location, field: { field: 'example' } },\n isStrict(loaded),\n ),\n source.metadata ?? {},\n ),\n loaded,\n },\n ];\n case 'markdown':\n return extractTypescriptSnippetsFromMarkdown(source.markdown, source.location, isStrict(loaded)).map(\n (snippet) => ({ snippet, loaded }),\n );\n }\n })\n .map(async ({ snippet, loaded }) => {\n const isInfused = snippet.parameters?.infused != null;\n\n // Ignore fixturization errors if requested on this command, or if the snippet was infused\n const ignoreFixtureErrors = loose || isInfused;\n\n // Also if the snippet was infused: switch off 'strict' mode if it was set\n if (isInfused) {\n snippet = { ...snippet, strict: false };\n }\n\n snippet = await withDependencies(loaded, withProjectDirectory(loaded.directory, snippet));\n return fixturize(snippet, ignoreFixtureErrors);\n }),\n );\n}\n\nexport interface TypeLookupAssembly {\n readonly packageJson: any;\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly symbolIdMap: Record<string, string>;\n}\n\nconst MAX_ASM_CACHE = 3;\nconst ASM_CACHE: TypeLookupAssembly[] = [];\n\n/**\n * Recursively searches for a .jsii file in the directory.\n * When file is found, checks cache to see if we already\n * stored the assembly in memory. If not, we synchronously\n * load the assembly into memory.\n */\nexport function findTypeLookupAssembly(startingDirectory: string): TypeLookupAssembly | undefined {\n const pjLocation = findPackageJsonLocation(path.resolve(startingDirectory));\n if (!pjLocation) {\n return undefined;\n }\n const directory = path.dirname(pjLocation);\n\n const fromCache = ASM_CACHE.find((c) => c.directory === directory);\n if (fromCache) {\n return fromCache;\n }\n\n const loaded = loadLookupAssembly(directory);\n if (!loaded) {\n return undefined;\n }\n\n while (ASM_CACHE.length >= MAX_ASM_CACHE) {\n ASM_CACHE.pop();\n }\n ASM_CACHE.unshift(loaded);\n return loaded;\n}\n\nfunction loadLookupAssembly(directory: string): TypeLookupAssembly | undefined {\n try {\n const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf-8'));\n const assembly: spec.Assembly = loadAssemblyFromPath(directory);\n const symbolIdMap = mkDict([\n ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn] as const),\n ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn] as const),\n ]);\n\n return {\n packageJson,\n assembly,\n directory,\n symbolIdMap,\n };\n } catch {\n return undefined;\n }\n}\n\nfunction findPackageJsonLocation(currentPath: string): string | undefined {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const candidate = path.join(currentPath, 'package.json');\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n\n const parentPath = path.resolve(currentPath, '..');\n if (parentPath === currentPath) {\n return undefined;\n }\n currentPath = parentPath;\n }\n}\n\n/**\n * Find the jsii [sub]module that contains the given FQN\n *\n * @returns `undefined` if the type is a member of the assembly root.\n */\nexport function findContainingSubmodule(assembly: spec.Assembly, fqn: string): string | undefined {\n const submoduleNames = Object.keys(assembly.submodules ?? {});\n sortBy(submoduleNames, (s) => [-s.length]); // Longest first\n for (const s of submoduleNames) {\n if (fqn.startsWith(`${s}.`)) {\n return s;\n }\n }\n return undefined;\n}\n\nfunction withProjectDirectory(dir: string, snippet: TypeScriptSnippet) {\n return updateParameters(snippet, {\n [SnippetParameters.$PROJECT_DIRECTORY]: dir,\n });\n}\n\n/**\n * Return a TypeScript snippet with dependencies added\n *\n * The dependencies will be taken from the package.json, and will consist of:\n *\n * - The package itself\n * - The package's dependencies and peerDependencies (but NOT devDependencies). Will\n * symlink to the files on disk.\n * - Any additional dependencies declared in `jsiiRosetta.exampleDependencies`.\n */\nasync function withDependencies(asm: LoadedAssembly, snippet: TypeScriptSnippet): Promise<TypeScriptSnippet> {\n const compilationDependencies: Record<string, CompilationDependency> = {};\n\n if (await pathExists(path.join(asm.directory, 'package.json'))) {\n compilationDependencies[asm.assembly.name] = {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(asm.directory),\n };\n }\n\n Object.assign(compilationDependencies, await resolveDependenciesFromPackageJson(asm.packageJson, asm.directory));\n\n Object.assign(\n compilationDependencies,\n mkDict(\n Object.entries(asm.packageJson?.jsiiRosetta?.exampleDependencies ?? {}).map(\n ([name, versionRange]) => [name, { type: 'symbolic', versionRange }] as const,\n ),\n ),\n );\n\n return {\n ...snippet,\n compilationDependencies,\n };\n}\n\n/**\n * Whether samples in the assembly should be treated as strict\n *\n * True if the strict flag is found in the package.json (modern) or the assembly itself (legacy).\n */\nfunction isStrict(loaded: LoadedAssembly) {\n return loaded.packageJson?.jsiiRosetta?.strict ?? enforcesStrictMode(loaded.assembly);\n}\n"]}
1
+ {"version":3,"file":"assemblies.js","sourceRoot":"","sources":["../../src/jsii/assemblies.ts"],"names":[],"mappings":";;;AAAA,qCAAiD;AACjD,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA0F;AAC1F,mCAAmC;AACnC,0CAAwC;AACxC,mEAAqF;AACrF,wCASoB;AACpB,kEAA6E;AAC7E,sCAA+C;AAC/C,gDAAyG;AACzG,kCAA2D;AAE3D;;;;;;;;;;;;;GAaG;AACU,QAAA,yBAAyB,GAAG,iBAAiB,CAAC;AAe3D;;GAEG;AACH,SAAgB,cAAc,CAC5B,iBAAoC,EACpC,kBAA2B;IAE3B,OAAO,iBAAiB,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;IAE3C,SAAS,YAAY,CAAC,QAAgB;QACpC,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC;YACvB,OAAO,YAAY,CAAC,IAAA,uBAAgB,EAAC,QAAQ,CAAC,CAAC,CAAC;QAClD,CAAC;QAED,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;QACzC,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QAExD,MAAM,QAAQ,GAAG,IAAA,2BAAoB,EAAC,QAAQ,EAAE,kBAAkB,CAAC,CAAC;QACpE,MAAM,WAAW,GAAG,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,YAAY,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QAE7G,OAAO,EAAE,Q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GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG;YAC3C,IAAI,EAAE,UAAU;YAChB,iBAAiB,EAAE,MAAM,kBAAU,CAAC,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC;SAC5D,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAM,CAAC,uBAAuB,EAAE,MAAM,IAAA,yDAAkC,EAAC,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAEjH,MAAM,CAAC,MAAM,CACX,uBAAuB,EACvB,IAAA,aAAM,EACJ,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,EAAE,WAAW,EAAE,mBAAmB,IAAI,EAAE,CAAC,CAAC,GAAG,CACzE,CAAC,CAAC,IAAI,EAAE,YAAY,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,YAAY,EAAE,CAAU,CAC9E,CACF,CACF,CAAC;IAEF,OAAO;QACL,GAAG,OAAO;QACV,uBAAuB;KACxB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,QAAQ,CAAC,MAAsB;IACtC,OAAO,MAAM,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,IAAI,IAAA,2BAAkB,EAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;AACxF,CAAC","sourcesContent":["import { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadAssemblyFromFile, loadAssemblyFromPath, findAssemblyFile } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { fixturize } from '../fixtures';\nimport { extractTypescriptSnippetsFromMarkdown } from '../markdown/extract-snippets';\nimport {\n TypeScriptSnippet,\n typeScriptSnippetFromSource,\n updateParameters,\n SnippetParameters,\n ApiLocation,\n parseMetadataLine,\n CompilationDependency,\n INITIALIZER_METHOD_NAME,\n} from '../snippet';\nimport { resolveDependenciesFromPackageJson } from '../snippet-dependencies';\nimport { enforcesStrictMode } from '../strict';\nimport { LanguageTablet, DEFAULT_TABLET_NAME, DEFAULT_TABLET_NAME_COMPRESSED } from '../tablets/tablets';\nimport { fmap, mkDict, pathExists, sortBy } from '../util';\n\n/**\n * The JSDoc tag users can use to associate non-visible metadata with an example\n *\n * In a Markdown section, metadata goes after the code block fence, where it will\n * be attached to the example but invisible.\n *\n * ```ts metadata=goes here\n *\n * But in doc comments, '@example' already delineates the example, and any metadata\n * in there added by the '///' tags becomes part of the visible code (there is no\n * place to put hidden information).\n *\n * We introduce the '@exampleMetadata' tag to put that additional information.\n */\nexport const EXAMPLE_METADATA_JSDOCTAG = 'exampleMetadata';\n\ninterface RosettaPackageJson extends spec.PackageJson {\n readonly jsiiRosetta?: {\n readonly strict?: boolean;\n readonly exampleDependencies?: Record<string, string>;\n };\n}\n\nexport interface LoadedAssembly {\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly packageJson?: RosettaPackageJson;\n}\n\n/**\n * Load assemblies by filename or directory\n */\nexport function loadAssemblies(\n assemblyLocations: readonly string[],\n validateAssemblies: boolean,\n): readonly LoadedAssembly[] {\n return assemblyLocations.map(loadAssembly);\n\n function loadAssembly(location: string): LoadedAssembly {\n const stat = fs.statSync(location);\n if (stat.isDirectory()) {\n return loadAssembly(findAssemblyFile(location));\n }\n\n const directory = path.dirname(location);\n const pjLocation = path.join(directory, 'package.json');\n\n const assembly = loadAssemblyFromFile(location, validateAssemblies);\n const packageJson = fs.existsSync(pjLocation) ? JSON.parse(fs.readFileSync(pjLocation, 'utf-8')) : undefined;\n\n return { assembly, directory, packageJson };\n }\n}\n\n/**\n * Load the default tablets for every assembly, if available\n *\n * Returns a map of { directory -> tablet }.\n */\nexport async function loadAllDefaultTablets(asms: readonly LoadedAssembly[]): Promise<Record<string, LanguageTablet>> {\n return mkDict(\n await Promise.all(\n asms.map(\n async (a) => [a.directory, await LanguageTablet.fromOptionalFile(guessTabletLocation(a.directory))] as const,\n ),\n ),\n );\n}\n\n/**\n * Returns the location of the tablet file, either .jsii.tabl.json or .jsii.tabl.json.gz.\n * Assumes that a tablet exists in the directory and if not, the ensuing behavior is\n * handled by the caller of this function.\n */\nexport function guessTabletLocation(directory: string) {\n return compressedTabletExists(directory)\n ? path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED)\n : path.join(directory, DEFAULT_TABLET_NAME);\n}\n\nexport function compressedTabletExists(directory: string) {\n return fs.existsSync(path.join(directory, DEFAULT_TABLET_NAME_COMPRESSED));\n}\n\nexport type AssemblySnippetSource =\n | { type: 'markdown'; markdown: string; location: ApiLocation }\n | { type: 'example'; source: string; metadata?: { [key: string]: string }; location: ApiLocation };\n\n/**\n * Return all markdown and example snippets from the given assembly\n */\nexport function allSnippetSources(assembly: spec.Assembly): AssemblySnippetSource[] {\n const ret: AssemblySnippetSource[] = [];\n\n if (assembly.readme) {\n ret.push({\n type: 'markdown',\n markdown: assembly.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: assembly.name },\n });\n }\n\n for (const [submoduleFqn, submodule] of Object.entries(assembly.submodules ?? {})) {\n if (submodule.readme) {\n ret.push({\n type: 'markdown',\n markdown: submodule.readme.markdown,\n location: { api: 'moduleReadme', moduleFqn: submoduleFqn },\n });\n }\n }\n\n if (assembly.types) {\n for (const type of Object.values(assembly.types)) {\n emitDocs(type.docs, { api: 'type', fqn: type.fqn });\n\n if (spec.isEnumType(type)) {\n for (const m of type.members) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n if (spec.isClassType(type)) {\n emitDocsForCallable(type.initializer, type.fqn);\n }\n if (spec.isClassOrInterfaceType(type)) {\n for (const m of type.methods ?? []) emitDocsForCallable(m, type.fqn, m.name);\n for (const m of type.properties ?? []) emitDocs(m.docs, { api: 'member', fqn: type.fqn, memberName: m.name });\n }\n }\n }\n\n return ret;\n\n function emitDocsForCallable(callable: spec.Callable | undefined, fqn: string, memberName?: string) {\n if (!callable) {\n return;\n }\n emitDocs(callable.docs, memberName ? { api: 'member', fqn, memberName } : { api: 'initializer', fqn });\n\n for (const parameter of callable.parameters ?? []) {\n emitDocs(parameter.docs, {\n api: 'parameter',\n fqn: fqn,\n methodName: memberName ?? INITIALIZER_METHOD_NAME,\n parameterName: parameter.name,\n });\n }\n }\n\n function emitDocs(docs: spec.Docs | undefined, location: ApiLocation) {\n if (!docs) {\n return;\n }\n\n if (docs.remarks) {\n ret.push({\n type: 'markdown',\n markdown: docs.remarks,\n location,\n });\n }\n if (docs.example) {\n ret.push({\n type: 'example',\n source: docs.example,\n metadata: fmap(docs.custom?.[EXAMPLE_METADATA_JSDOCTAG], parseMetadataLine),\n location,\n });\n }\n }\n}\n\nexport async function allTypeScriptSnippets(\n assemblies: readonly LoadedAssembly[],\n loose = false,\n): Promise<TypeScriptSnippet[]> {\n return Promise.all(\n assemblies\n .flatMap((loaded) => allSnippetSources(loaded.assembly).map((source) => ({ source, loaded })))\n .flatMap(({ source, loaded }) => {\n switch (source.type) {\n case 'example':\n return [\n {\n snippet: updateParameters(\n typeScriptSnippetFromSource(\n source.source,\n { api: source.location, field: { field: 'example' } },\n isStrict(loaded),\n ),\n source.metadata ?? {},\n ),\n loaded,\n },\n ];\n case 'markdown':\n return extractTypescriptSnippetsFromMarkdown(source.markdown, source.location, isStrict(loaded)).map(\n (snippet) => ({ snippet, loaded }),\n );\n }\n })\n .map(async ({ snippet, loaded }) => {\n const isInfused = snippet.parameters?.infused != null;\n\n // Ignore fixturization errors if requested on this command, or if the snippet was infused\n const ignoreFixtureErrors = loose || isInfused;\n\n // Also if the snippet was infused: switch off 'strict' mode if it was set\n if (isInfused) {\n snippet = { ...snippet, strict: false };\n }\n\n snippet = await withDependencies(loaded, withProjectDirectory(loaded.directory, snippet));\n return fixturize(snippet, ignoreFixtureErrors);\n }),\n );\n}\n\nexport interface TypeLookupAssembly {\n readonly packageJson: any;\n readonly assembly: spec.Assembly;\n readonly directory: string;\n readonly symbolIdMap: Record<string, string>;\n}\n\nconst MAX_ASM_CACHE = 3;\nconst ASM_CACHE: TypeLookupAssembly[] = [];\n\n/**\n * Recursively searches for a .jsii file in the directory.\n * When file is found, checks cache to see if we already\n * stored the assembly in memory. If not, we synchronously\n * load the assembly into memory.\n */\nexport function findTypeLookupAssembly(startingDirectory: string): TypeLookupAssembly | undefined {\n const pjLocation = findPackageJsonLocation(path.resolve(startingDirectory));\n if (!pjLocation) {\n return undefined;\n }\n const directory = path.dirname(pjLocation);\n\n const fromCache = ASM_CACHE.find((c) => c.directory === directory);\n if (fromCache) {\n return fromCache;\n }\n\n const loaded = loadLookupAssembly(directory);\n if (!loaded) {\n return undefined;\n }\n\n while (ASM_CACHE.length >= MAX_ASM_CACHE) {\n ASM_CACHE.pop();\n }\n ASM_CACHE.unshift(loaded);\n return loaded;\n}\n\nfunction loadLookupAssembly(directory: string): TypeLookupAssembly | undefined {\n try {\n const packageJson = JSON.parse(fs.readFileSync(path.join(directory, 'package.json'), 'utf-8'));\n const assembly: spec.Assembly = loadAssemblyFromPath(directory);\n const symbolIdMap = mkDict([\n ...Object.values(assembly.types ?? {}).map((type) => [type.symbolId ?? '', type.fqn] as const),\n ...Object.entries(assembly.submodules ?? {}).map(([fqn, mod]) => [mod.symbolId ?? '', fqn] as const),\n ]);\n\n return {\n packageJson,\n assembly,\n directory,\n symbolIdMap,\n };\n } catch {\n return undefined;\n }\n}\n\nfunction findPackageJsonLocation(currentPath: string): string | undefined {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const candidate = path.join(currentPath, 'package.json');\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n\n const parentPath = path.resolve(currentPath, '..');\n if (parentPath === currentPath) {\n return undefined;\n }\n currentPath = parentPath;\n }\n}\n\n/**\n * Find the jsii [sub]module that contains the given FQN\n *\n * @returns `undefined` if the type is a member of the assembly root.\n */\nexport function findContainingSubmodule(assembly: spec.Assembly, fqn: string): string | undefined {\n const submoduleNames = Object.keys(assembly.submodules ?? {});\n sortBy(submoduleNames, (s) => [-s.length]); // Longest first\n for (const s of submoduleNames) {\n if (fqn.startsWith(`${s}.`)) {\n return s;\n }\n }\n return undefined;\n}\n\nfunction withProjectDirectory(dir: string, snippet: TypeScriptSnippet) {\n return updateParameters(snippet, {\n [SnippetParameters.$PROJECT_DIRECTORY]: dir,\n });\n}\n\n/**\n * Return a TypeScript snippet with dependencies added\n *\n * The dependencies will be taken from the package.json, and will consist of:\n *\n * - The package itself\n * - The package's dependencies and peerDependencies (but NOT devDependencies). Will\n * symlink to the files on disk.\n * - Any additional dependencies declared in `jsiiRosetta.exampleDependencies`.\n */\nasync function withDependencies(asm: LoadedAssembly, snippet: TypeScriptSnippet): Promise<TypeScriptSnippet> {\n const compilationDependencies: Record<string, CompilationDependency> = {};\n\n if (await pathExists(path.join(asm.directory, 'package.json'))) {\n compilationDependencies[asm.assembly.name] = {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(asm.directory),\n };\n }\n\n Object.assign(compilationDependencies, await resolveDependenciesFromPackageJson(asm.packageJson, asm.directory));\n\n Object.assign(\n compilationDependencies,\n mkDict(\n Object.entries(asm.packageJson?.jsiiRosetta?.exampleDependencies ?? {}).map(\n ([name, versionRange]) => [name, { type: 'symbolic', versionRange }] as const,\n ),\n ),\n );\n\n return {\n ...snippet,\n compilationDependencies,\n };\n}\n\n/**\n * Whether samples in the assembly should be treated as strict\n *\n * True if the strict flag is found in the package.json (modern) or the assembly itself (legacy).\n */\nfunction isStrict(loaded: LoadedAssembly) {\n return loaded.packageJson?.jsiiRosetta?.strict ?? enforcesStrictMode(loaded.assembly);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"fingerprinting.js","sourceRoot":"","sources":["../../src/jsii/fingerprinting.ts"],"names":[],"mappings":";;;AAAA,sCAAsC;AACtC,mCAAmC;AAEnC;;;;;;;;GAQG;AACH,MAAa,iBAAiB;IAI5B,YAAmB,UAA2B;QAH7B,UAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;QAClC,eAAU,GAAG,IAAI,GAAG,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AAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBACrC,kBAAkB,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;aACpD;YACD,IAAI,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,EAAE;gBACtC,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE;oBACnC,kBAAkB,CAAC,CAAC,CAAC,CAAC;iBACvB;aACF;QACH,CAAC;QAED,SAAS,UAAU,CAAC,GAAG,EAA8B;YACnD,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IAEO,QAAQ,CAAC,GAAW;QAC1B,MAAM,YAAY,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACzD,CAAC;CACF;AA5ID,8CA4IC;AAED,SAAS,YAAY,CAA6B,EAAO;IACvD,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import * as crypto from 'node:crypto';\nimport * as spec from '@jsii/spec';\n\n/**\n * Return a fingerprint for a type.\n *\n * The fingerprint will change if the API of the given type changes.\n *\n * The fingerprint is an approximation, it's not exhaustive. It will not trace\n * into types from assemblies it can't see, for example. For the purposes of Rosetta,\n * we'll assume this is Good Enough™.\n */\nexport class TypeFingerprinter {\n private readonly cache = new Map<string, string>();\n private readonly assemblies = new Map<string, spec.Assembly>();\n\n public constructor(assemblies: spec.Assembly[]) {\n for (const assembly of assemblies) {\n this.assemblies.set(assembly.name, assembly);\n }\n }\n\n /**\n * Return a single fingerprint that encompasses all fqns in the list\n */\n public fingerprintAll(fqns: string[]) {\n const hash = crypto.createHash('sha256');\n for (const fqn of fqns) {\n hash.update(this.fingerprintType(fqn));\n }\n return hash.digest('hex');\n }\n\n /**\n * Return the fingerprint for the given FQN in the assembly of this fingerprinter\n *\n * The fingerprint is always going to contain the FQN, even if the type doesn't exist\n * in this assembly.\n */\n public fingerprintType(fqn: string) {\n return this.doFingerprint(fqn, new Set([fqn]));\n }\n\n private doFingerprint(fqn: string, recursionBreaker: Set<string>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n const existing = this.cache.get(fqn);\n if (existing) {\n return existing;\n }\n\n const hash = crypto.createHash('sha256');\n hash.update(fqn);\n\n const type = this.findType(fqn);\n if (type) {\n hash.update(type.kind);\n switch (type.kind) {\n case spec.TypeKind.Enum:\n for (const member of sortedByName(type.members)) {\n hash.update(member.name);\n }\n break;\n case spec.TypeKind.Class:\n case spec.TypeKind.Interface:\n if (type.kind === spec.TypeKind.Class) {\n visitType(type.base);\n visitCallable(type.initializer);\n }\n\n for (const prop of sortedByName(type.properties ?? [])) {\n hash.update(prop.name);\n visitBools(prop.immutable, prop.static, prop.optional, prop.protected);\n visitTypeReference(prop.type);\n }\n for (const method of sortedByName(type.methods ?? [])) {\n hash.update(method.name);\n visitCallable(method);\n visitBools(method.returns?.optional);\n visitTypeReference(method.returns?.type);\n }\n for (const implint of type.interfaces ?? []) {\n visitType(implint);\n }\n\n break;\n }\n }\n\n const ret = hash.digest('hex');\n this.cache.set(fqn, ret);\n return ret;\n\n function visitType(fqnStr?: string) {\n if (!fqnStr) {\n return;\n }\n\n if (recursionBreaker.has(fqnStr)) {\n hash.update('$RECURSION$');\n return;\n }\n\n recursionBreaker.add(fqnStr);\n hash.update(self.doFingerprint(fqnStr, recursionBreaker));\n recursionBreaker.delete(fqnStr);\n }\n\n function visitCallable(callable?: spec.Callable) {\n if (!callable) {\n return;\n }\n\n visitBools(callable.protected);\n for (const param of callable.parameters ?? []) {\n visitBools(param.optional, param.variadic);\n visitTypeReference(param.type);\n }\n }\n\n function visitTypeReference(typeRef?: spec.TypeReference) {\n if (!typeRef) {\n return;\n }\n\n if (spec.isPrimitiveTypeReference(typeRef)) {\n hash.update(typeRef.primitive);\n }\n if (spec.isNamedTypeReference(typeRef)) {\n visitType(typeRef.fqn);\n }\n if (spec.isCollectionTypeReference(typeRef)) {\n hash.update(typeRef.collection.kind);\n visitTypeReference(typeRef.collection.elementtype);\n }\n if (spec.isUnionTypeReference(typeRef)) {\n for (const t of typeRef.union.types) {\n visitTypeReference(t);\n }\n }\n }\n\n function visitBools(...vs: Array<boolean | undefined>) {\n hash.update(vs.map((v) => (v ? '1' : '0')).join(''));\n }\n }\n\n private findType(fqn: string) {\n const assemblyName = fqn.split('.')[0];\n return this.assemblies.get(assemblyName)?.types?.[fqn];\n }\n}\n\nfunction sortedByName<A extends { name: string }>(xs: A[]): A[] {\n xs.sort((a, b) => a.name.localeCompare(b.name));\n return xs;\n}\n"]}
1
+ {"version":3,"file":"fingerprinting.js","sourceRoot":"","sources":["../../src/jsii/fingerprinting.ts"],"names":[],"mappings":";;;AAAA,sCAAsC;AACtC,mCAAmC;AAEnC;;;;;;;;GAQG;AACH,MAAa,iBAAiB;IAI5B,YAAmB,UAA2B;QAH7B,UAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;QAClC,eAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;QAG7D,KAAK,MAAM,QAAQ,IAAI,UAAU,EAAE,CAAC;YAClC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;QAC/C,CAAC;IACH,CAAC;IAED;;OAEG;IACI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;gBAC5C,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBACrC,kBAAkB,CAAC,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC;YACrD,CAAC;YACD,IAAI,IAAI,CAAC,oBAAoB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACvC,KAAK,MAAM,CAAC,IAAI,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;oBACpC,kBAAkB,CAAC,CAAC,CAAC,CAAC;gBACxB,CAAC;YACH,CAAC;QACH,CAAC;QAED,SAAS,UAAU,CAAC,GAAG,EAA8B;YACnD,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IAEO,QAAQ,CAAC,GAAW;QAC1B,MAAM,YAAY,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC;IACzD,CAAC;CACF;AA5ID,8CA4IC;AAED,SAAS,YAAY,CAA6B,EAAO;IACvD,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;IAChD,OAAO,EAAE,CAAC;AACZ,CAAC","sourcesContent":["import * as crypto from 'node:crypto';\nimport * as spec from '@jsii/spec';\n\n/**\n * Return a fingerprint for a type.\n *\n * The fingerprint will change if the API of the given type changes.\n *\n * The fingerprint is an approximation, it's not exhaustive. It will not trace\n * into types from assemblies it can't see, for example. For the purposes of Rosetta,\n * we'll assume this is Good Enough™.\n */\nexport class TypeFingerprinter {\n private readonly cache = new Map<string, string>();\n private readonly assemblies = new Map<string, spec.Assembly>();\n\n public constructor(assemblies: spec.Assembly[]) {\n for (const assembly of assemblies) {\n this.assemblies.set(assembly.name, assembly);\n }\n }\n\n /**\n * Return a single fingerprint that encompasses all fqns in the list\n */\n public fingerprintAll(fqns: string[]) {\n const hash = crypto.createHash('sha256');\n for (const fqn of fqns) {\n hash.update(this.fingerprintType(fqn));\n }\n return hash.digest('hex');\n }\n\n /**\n * Return the fingerprint for the given FQN in the assembly of this fingerprinter\n *\n * The fingerprint is always going to contain the FQN, even if the type doesn't exist\n * in this assembly.\n */\n public fingerprintType(fqn: string) {\n return this.doFingerprint(fqn, new Set([fqn]));\n }\n\n private doFingerprint(fqn: string, recursionBreaker: Set<string>) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n const existing = this.cache.get(fqn);\n if (existing) {\n return existing;\n }\n\n const hash = crypto.createHash('sha256');\n hash.update(fqn);\n\n const type = this.findType(fqn);\n if (type) {\n hash.update(type.kind);\n switch (type.kind) {\n case spec.TypeKind.Enum:\n for (const member of sortedByName(type.members)) {\n hash.update(member.name);\n }\n break;\n case spec.TypeKind.Class:\n case spec.TypeKind.Interface:\n if (type.kind === spec.TypeKind.Class) {\n visitType(type.base);\n visitCallable(type.initializer);\n }\n\n for (const prop of sortedByName(type.properties ?? [])) {\n hash.update(prop.name);\n visitBools(prop.immutable, prop.static, prop.optional, prop.protected);\n visitTypeReference(prop.type);\n }\n for (const method of sortedByName(type.methods ?? [])) {\n hash.update(method.name);\n visitCallable(method);\n visitBools(method.returns?.optional);\n visitTypeReference(method.returns?.type);\n }\n for (const implint of type.interfaces ?? []) {\n visitType(implint);\n }\n\n break;\n }\n }\n\n const ret = hash.digest('hex');\n this.cache.set(fqn, ret);\n return ret;\n\n function visitType(fqnStr?: string) {\n if (!fqnStr) {\n return;\n }\n\n if (recursionBreaker.has(fqnStr)) {\n hash.update('$RECURSION$');\n return;\n }\n\n recursionBreaker.add(fqnStr);\n hash.update(self.doFingerprint(fqnStr, recursionBreaker));\n recursionBreaker.delete(fqnStr);\n }\n\n function visitCallable(callable?: spec.Callable) {\n if (!callable) {\n return;\n }\n\n visitBools(callable.protected);\n for (const param of callable.parameters ?? []) {\n visitBools(param.optional, param.variadic);\n visitTypeReference(param.type);\n }\n }\n\n function visitTypeReference(typeRef?: spec.TypeReference) {\n if (!typeRef) {\n return;\n }\n\n if (spec.isPrimitiveTypeReference(typeRef)) {\n hash.update(typeRef.primitive);\n }\n if (spec.isNamedTypeReference(typeRef)) {\n visitType(typeRef.fqn);\n }\n if (spec.isCollectionTypeReference(typeRef)) {\n hash.update(typeRef.collection.kind);\n visitTypeReference(typeRef.collection.elementtype);\n }\n if (spec.isUnionTypeReference(typeRef)) {\n for (const t of typeRef.union.types) {\n visitTypeReference(t);\n }\n }\n }\n\n function visitBools(...vs: Array<boolean | undefined>) {\n hash.update(vs.map((v) => (v ? '1' : '0')).join(''));\n }\n }\n\n private findType(fqn: string) {\n const assemblyName = fqn.split('.')[0];\n return this.assemblies.get(assemblyName)?.types?.[fqn];\n }\n}\n\nfunction sortedByName<A extends { name: string }>(xs: A[]): A[] {\n xs.sort((a, b) => a.name.localeCompare(b.name));\n return xs;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"jsii-types.js","sourceRoot":"","sources":["../../src/jsii/jsii-types.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,6CAAyE;AACzE,+CAA6G;AAU7G,SAAgB,iBAAiB,CAAC,WAA2B,EAAE,IAAa;IAC1E,sGAAsG;IACtG,+BAA+B;IAC/B,IAAK,IAAY,CAAC,aAAa,KAAK,OAAO,EAAE;QAC3C,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;KAC5B;IAED,mEAAmE;IACnE,IAAI,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,EAAE,CA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EAAE,WAAW,CAAC,CAAC;IAEvF,IAAI,IAAA,uBAAU,EAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,CAAC,EAAE;QAC5C,gFAAgF;QAChF,kFAAkF;QAClF,4CAA4C;QAC5C,EAAE;QACF,sEAAsE;QACtE,iEAAiE;QACjE,OAAO,cAAc,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;KAC/D;IAED,+FAA+F;IAC/F,MAAM,gBAAgB,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IAC9D,KAAK,MAAM,SAAS,IAAI,gBAAgB,EAAE;QACxC,MAAM,UAAU,GAAG,IAAA,8BAAiB,EAAC,WAAW,EAAE,SAAS,CAAC,CAAC;QAC7D,IAAI,UAAU,EAAE;YACd,OAAO,UAAU,CAAC;SACnB;KACF;IAED,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AACzB,CAAC;AAhCD,oDAgCC;AAED,SAAS,2BAA2B,CAAC,IAAc;IACjD,OAAO,IAAI,EAAE;QACX,IAAI,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,EAAE;YACjC,OAAO,IAAI,CAAC;SACb;QACD,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC;KACpB;IAED,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["import * as ts from 'typescript';\n\nimport { hasAnyFlag, analyzeStructType, JsiiSymbol } from './jsii-utils';\nimport { inferredTypeOfExpression, BuiltInType, builtInTypeName, mapElementType } from '../typescript/types';\n\n// eslint-disable-next-line prettier/prettier\nexport type JsiiType =\n | { kind: 'unknown' }\n | { kind: 'error'; message: string }\n | { kind: 'map' | 'list'; elementType: JsiiType; elementTypeSymbol: ts.Symbol | undefined }\n | { kind: 'namedType'; name: string }\n | { kind: 'builtIn'; builtIn: BuiltInType };\n\nexport function determineJsiiType(typeChecker: ts.TypeChecker, type: ts.Type): JsiiType {\n // this means the snippet didn't have enough info for the TypeScript compiler to figure out the type -\n // so, just render the fallback\n if ((type as any).intrinsicName === 'error') {\n return { kind: 'unknown' };\n }\n\n // The non-nullable version of `void` is `never`, so check first...\n if ((type.flags & (ts.TypeFlags.Void | ts.TypeFlags.VoidLike)) !== 0) {\n return { kind: 'builtIn', builtIn: 'void' };\n }\n // The non-nullable version of `unknown` is some ObjectType, so check first...\n if ((type.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) !== 0) {\n return { kind: 'builtIn', builtIn: 'any' };\n }\n\n type = type.getNonNullableType();\n\n const mapValuesType = mapElementType(type, typeChecker);\n if (mapValuesType.result === 'map') {\n return {\n kind: 'map',\n elementType: mapValuesType.elementType\n ? determineJsiiType(typeChecker, mapValuesType.elementType)\n : { kind: 'builtIn', builtIn: 'any' },\n elementTypeSymbol: mapValuesType.elementType?.symbol,\n };\n }\n\n if (type.symbol?.name === 'Array') {\n const typeRef = type as ts.TypeReference;\n\n if (typeRef.typeArguments?.length === 1) {\n return {\n kind: 'list',\n elementType: determineJsiiType(typeChecker, typeRef.typeArguments[0]),\n elementTypeSymbol: typeRef.typeArguments[0].symbol,\n };\n }\n\n return {\n kind: 'list',\n elementType: { kind: 'builtIn', builtIn: 'any' },\n elementTypeSymbol: undefined,\n };\n }\n\n // User-defined or aliased type\n if (type.aliasSymbol) {\n return { kind: 'namedType', name: type.aliasSymbol.name };\n }\n if (type.symbol) {\n return { kind: 'namedType', name: type.symbol.name };\n }\n\n const typeScriptBuiltInType = builtInTypeName(type);\n if (typeScriptBuiltInType) {\n return { kind: 'builtIn', builtIn: typeScriptBuiltInType };\n }\n\n if (type.isUnion() || type.isIntersection()) {\n return {\n kind: 'error',\n message: `Type unions or intersections are not supported in examples, got: ${typeChecker.typeToString(type)}`,\n };\n }\n\n return { kind: 'unknown' };\n}\n\nexport type ObjectLiteralAnalysis = ObjectLiteralStruct | { readonly kind: 'map' } | { readonly kind: 'unknown' };\n\nexport type ObjectLiteralStruct =\n | { readonly kind: 'struct'; readonly type: ts.Type; readonly jsiiSym: JsiiSymbol }\n | { readonly kind: 'local-struct'; readonly type: ts.Type };\n\nexport function analyzeObjectLiteral(\n typeChecker: ts.TypeChecker,\n node: ts.ObjectLiteralExpression,\n): ObjectLiteralAnalysis {\n const type = inferredTypeOfExpression(typeChecker, node);\n if (!type) {\n return { kind: 'unknown' };\n }\n\n const call = findEnclosingCallExpression(node);\n const isDeclaredCall = !!(call && typeChecker.getResolvedSignature(call)?.declaration);\n\n if (hasAnyFlag(type.flags, ts.TypeFlags.Any)) {\n // The type checker by itself won't tell us the difference between an `any` that\n // was literally declared as a type in the code, vs an `any` it assumes because it\n // can't find a function's type declaration.\n //\n // Search for the function's declaration and only if we can't find it,\n // the type is actually unknown (otherwise it's a literal 'any').\n return isDeclaredCall ? { kind: 'map' } : { kind: 'unknown' };\n }\n\n // If the type is a union between a struct and something else, return the first possible struct\n const structCandidates = type.isUnion() ? type.types : [type];\n for (const candidate of structCandidates) {\n const structType = analyzeStructType(typeChecker, candidate);\n if (structType) {\n return structType;\n }\n }\n\n return { kind: 'map' };\n}\n\nfunction findEnclosingCallExpression(node?: ts.Node): ts.CallLikeExpression | undefined {\n while (node) {\n if (ts.isCallLikeExpression(node)) {\n return node;\n }\n node = node.parent;\n }\n\n return undefined;\n}\n"]}
1
+ {"version":3,"file":"jsii-types.js","sourceRoot":"","sources":["../../src/jsii/jsii-types.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,6CAAyE;AACzE,+CAA6G;AAU7G,SAAgB,iBAAiB,CAAC,WAA2B,EAAE,IAAa;IAC1E,sGAAsG;IACtG,+BAA+B;IAC/B,IAAK,IAAY,CAAC,aAAa,KAAK,OAAO,EAAE,CAAC;QAC5C,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IAC7B,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ts from 'typescript';\n\nimport { hasAnyFlag, analyzeStructType, JsiiSymbol } from './jsii-utils';\nimport { inferredTypeOfExpression, BuiltInType, builtInTypeName, mapElementType } from '../typescript/types';\n\n// eslint-disable-next-line prettier/prettier\nexport type JsiiType =\n | { kind: 'unknown' }\n | { kind: 'error'; message: string }\n | { kind: 'map' | 'list'; elementType: JsiiType; elementTypeSymbol: ts.Symbol | undefined }\n | { kind: 'namedType'; name: string }\n | { kind: 'builtIn'; builtIn: BuiltInType };\n\nexport function determineJsiiType(typeChecker: ts.TypeChecker, type: ts.Type): JsiiType {\n // this means the snippet didn't have enough info for the TypeScript compiler to figure out the type -\n // so, just render the fallback\n if ((type as any).intrinsicName === 'error') {\n return { kind: 'unknown' };\n }\n\n // The non-nullable version of `void` is `never`, so check first...\n if ((type.flags & (ts.TypeFlags.Void | ts.TypeFlags.VoidLike)) !== 0) {\n return { kind: 'builtIn', builtIn: 'void' };\n }\n // The non-nullable version of `unknown` is some ObjectType, so check first...\n if ((type.flags & (ts.TypeFlags.Unknown | ts.TypeFlags.Any)) !== 0) {\n return { kind: 'builtIn', builtIn: 'any' };\n }\n\n type = type.getNonNullableType();\n\n const mapValuesType = mapElementType(type, typeChecker);\n if (mapValuesType.result === 'map') {\n return {\n kind: 'map',\n elementType: mapValuesType.elementType\n ? determineJsiiType(typeChecker, mapValuesType.elementType)\n : { kind: 'builtIn', builtIn: 'any' },\n elementTypeSymbol: mapValuesType.elementType?.symbol,\n };\n }\n\n if (type.symbol?.name === 'Array') {\n const typeRef = type as ts.TypeReference;\n\n if (typeRef.typeArguments?.length === 1) {\n return {\n kind: 'list',\n elementType: determineJsiiType(typeChecker, typeRef.typeArguments[0]),\n elementTypeSymbol: typeRef.typeArguments[0].symbol,\n };\n }\n\n return {\n kind: 'list',\n elementType: { kind: 'builtIn', builtIn: 'any' },\n elementTypeSymbol: undefined,\n };\n }\n\n // User-defined or aliased type\n if (type.aliasSymbol) {\n return { kind: 'namedType', name: type.aliasSymbol.name };\n }\n if (type.symbol) {\n return { kind: 'namedType', name: type.symbol.name };\n }\n\n const typeScriptBuiltInType = builtInTypeName(type);\n if (typeScriptBuiltInType) {\n return { kind: 'builtIn', builtIn: typeScriptBuiltInType };\n }\n\n if (type.isUnion() || type.isIntersection()) {\n return {\n kind: 'error',\n message: `Type unions or intersections are not supported in examples, got: ${typeChecker.typeToString(type)}`,\n };\n }\n\n return { kind: 'unknown' };\n}\n\nexport type ObjectLiteralAnalysis = ObjectLiteralStruct | { readonly kind: 'map' } | { readonly kind: 'unknown' };\n\nexport type ObjectLiteralStruct =\n | { readonly kind: 'struct'; readonly type: ts.Type; readonly jsiiSym: JsiiSymbol }\n | { readonly kind: 'local-struct'; readonly type: ts.Type };\n\nexport function analyzeObjectLiteral(\n typeChecker: ts.TypeChecker,\n node: ts.ObjectLiteralExpression,\n): ObjectLiteralAnalysis {\n const type = inferredTypeOfExpression(typeChecker, node);\n if (!type) {\n return { kind: 'unknown' };\n }\n\n const call = findEnclosingCallExpression(node);\n const isDeclaredCall = !!(call && typeChecker.getResolvedSignature(call)?.declaration);\n\n if (hasAnyFlag(type.flags, ts.TypeFlags.Any)) {\n // The type checker by itself won't tell us the difference between an `any` that\n // was literally declared as a type in the code, vs an `any` it assumes because it\n // can't find a function's type declaration.\n //\n // Search for the function's declaration and only if we can't find it,\n // the type is actually unknown (otherwise it's a literal 'any').\n return isDeclaredCall ? { kind: 'map' } : { kind: 'unknown' };\n }\n\n // If the type is a union between a struct and something else, return the first possible struct\n const structCandidates = type.isUnion() ? type.types : [type];\n for (const candidate of structCandidates) {\n const structType = analyzeStructType(typeChecker, candidate);\n if (structType) {\n return structType;\n }\n }\n\n return { kind: 'map' };\n}\n\nfunction findEnclosingCallExpression(node?: ts.Node): ts.CallLikeExpression | undefined {\n while (node) {\n if (ts.isCallLikeExpression(node)) {\n return node;\n }\n node = node.parent;\n }\n\n return undefined;\n}\n"]}
@@ -234,7 +234,7 @@ function parentSymbol(sym) {
234
234
  }
235
235
  return {
236
236
  fqn: parts.slice(0, -1).join('.'),
237
- symbolType: 'module',
237
+ symbolType: 'module', // Might not be true, but probably good enough
238
238
  sourceAssembly: sym.sourceAssembly,
239
239
  };
240
240
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsii-utils.js","sourceRoot":"","sources":["../../src/jsii/jsii-utils.ts"],"names":[],"mappings":";;;AAAA,mCAAmC;AACnC,wCAA+C;AAC/C,iCAAiC;AAEjC,6CAA0E;AAG1E,+CAA4D;AAC5D,kCAA+B;AAE/B,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,kDAAkD;IAClD,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAHD,8CAGC;AAED,SAAgB,iBAAiB,CAAC,WAA2B,EAAE,IAAa;IAC1E,IACE,CAAC,IAAI,CAAC,kBAAkB,EAAE;QAC1B,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC;QACxD,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EACpC;QACA,OAAO,KAAK,CAAC;KACd;IAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3D,IAAI,OAAO,EAAE;QACX,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;KAC1C;IAED,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,EAAE,CAAC;AACxC,CAAC;AAfD,8CAeC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,SAAgB,kBAAkB,CAAC,WAA2B,EAAE,IAAa;IAC3E,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE;QAC1F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C;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAND,4DAMC;AAED,SAAS,wBAAwB,CAAC,IAAa,EAAE,WAA2B;IAC1E,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE;QACxB,OAAO,SAAS,CAAC;KAClB;IAED,MAAM,IAAI,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,CAAC,CAAC;IAC3C,OAAO,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AAClE,CAAC;AAED,SAAgB,YAAY,CAAC,GAAe;IAC1C,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACjC,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,EAAE;QACtB,OAAO,SAAS,CAAC;KAClB;IAED,OAAO;QACL,GAAG,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACjC,UAAU,EAAE,QAAQ;QACpB,cAAc,EAAE,GAAG,CAAC,cAAc;KACnC,CAAC;AACJ,CAAC;AAXD,oCAWC;AAED;;GAEG;AACH,SAAgB,UAAU,CAAC,CAAS;IAClC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACnC,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,CAAS;IACrC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC;AAFD,sCAEC","sourcesContent":["import * as spec from '@jsii/spec';\nimport { symbolIdentifier } from 'jsii/common';\nimport * as ts from 'typescript';\n\nimport { findTypeLookupAssembly, TypeLookupAssembly } from './assemblies';\nimport { ObjectLiteralStruct } from './jsii-types';\nimport { AstRenderer } from '../renderer';\nimport { typeContainsUndefined } from '../typescript/types';\nimport { fmap } from '../util';\n\nexport function isNamedLikeStruct(name: string) {\n // Start with an I and another uppercase character\n return !/^I[A-Z]/.test(name);\n}\n\nexport function analyzeStructType(typeChecker: ts.TypeChecker, type: ts.Type): ObjectLiteralStruct | false {\n if (\n !type.isClassOrInterface() ||\n !hasAllFlags(type.objectFlags, ts.ObjectFlags.Interface) ||\n !isNamedLikeStruct(type.symbol.name)\n ) {\n return false;\n }\n\n const jsiiSym = lookupJsiiSymbol(typeChecker, type.symbol);\n if (jsiiSym) {\n return { kind: 'struct', type, jsiiSym };\n }\n\n return { kind: 'local-struct', type };\n}\n\n/**\n * Whether the given type is a protocol AND comes from jsii\n *\n * - Protocol: a TypeScript interface that is *not* a \"struct\" type.\n * A.k.a. \"behavioral interface\".\n * - From jsii: whether the interface type is defined in and exported\n * via a jsii assembly. There can be literal interfaces defined\n * in an example, and they will not be mangled in the same way\n * as a jsii interface would be.\n *\n *\n * Examples:\n *\n * ```ts\n * // isJsiiProtocolType() -> false: not a protocol\n * interface Banana {\n * readonly arc: number;\n * }\n *\n * // isJsiiProtocolType() -> might be true: depends on whether it was defined\n * // in a jsii assembly.\n * interface IHello {\n * sayIt(): void;\n * }\n *\n * // isJsiiProtocolType() -> false: declared to not be a protocol, even though\n * // it has the naming scheme of one\n * /**\n * * @struct\n * * /\n * interface IPAddress {\n * readonly octets: number[];\n * }\n * ```\n */\nexport function isJsiiProtocolType(typeChecker: ts.TypeChecker, type: ts.Type): boolean | undefined {\n if (!type.isClassOrInterface() || !hasAllFlags(type.objectFlags, ts.ObjectFlags.Interface)) {\n return false;\n }\n\n const sym = lookupJsiiSymbol(typeChecker, type.symbol);\n if (!sym) {\n return false;\n }\n\n if (!sym.sourceAssembly) {\n // No source assembly, so this is a 'fake-from-jsii' type\n return !isNamedLikeStruct(type.symbol.name);\n }\n\n const jsiiType = resolveJsiiSymbolType(sym);\n return spec.isInterfaceType(jsiiType) && !jsiiType.datatype;\n}\n\nexport function hasAllFlags<A extends number>(flags: A, test: A) {\n // tslint:disable-next-line:no-bitwise\n return test !== 0 && (flags & test) === test;\n}\n\nexport function hasAnyFlag<A extends number>(flags: A, test: A) {\n // tslint:disable-next-line:no-bitwise\n return test !== 0 && (flags & test) !== 0;\n}\n\nexport interface StructProperty {\n name: string;\n type: ts.Type | undefined;\n questionMark: boolean;\n}\n\nexport function propertiesOfStruct(type: ts.Type, context: AstRenderer<any>): StructProperty[] {\n return type.isClassOrInterface()\n ? type.getProperties().map((s) => {\n let propType;\n let questionMark = false;\n\n const propSymbol = type.getProperty(s.name)!;\n const symbolDecl = propSymbol.valueDeclaration ?? propSymbol.declarations![0];\n if (ts.isPropertyDeclaration(symbolDecl) || ts.isPropertySignature(symbolDecl)) {\n questionMark = symbolDecl.questionToken !== undefined;\n propType = symbolDecl.type && context.typeOfType(symbolDecl.type);\n }\n\n return {\n name: s.name,\n type: propType,\n questionMark,\n };\n })\n : [];\n}\n\nexport function structPropertyAcceptsUndefined(prop: StructProperty): boolean {\n return prop.questionMark || (!!prop.type && typeContainsUndefined(prop.type));\n}\n\n/**\n * A TypeScript symbol resolved to its jsii type\n */\nexport interface JsiiSymbol {\n /**\n * FQN of the symbol\n *\n * Is either the FQN of a type (for a type). For a membr, the FQN looks like:\n * 'type.fqn#memberName'.\n */\n readonly fqn: string;\n\n /**\n * What kind of symbol this is\n */\n readonly symbolType: 'module' | 'type' | 'member';\n\n /**\n * Assembly where the type was found\n *\n * Might be undefined if the type was FAKE from jsii (for tests)\n */\n readonly sourceAssembly?: TypeLookupAssembly;\n}\n\nexport function lookupJsiiSymbolFromNode(typeChecker: ts.TypeChecker, node: ts.Node): JsiiSymbol | undefined {\n return fmap(typeChecker.getSymbolAtLocation(node), (s) => lookupJsiiSymbol(typeChecker, s));\n}\n\nexport function resolveJsiiSymbolType(jsiiSymbol: JsiiSymbol): spec.Type {\n if (jsiiSymbol.symbolType !== 'type') {\n throw new Error(\n `Expected symbol to refer to a 'type', got '${jsiiSymbol.fqn}' which is a '${jsiiSymbol.symbolType}'`,\n );\n }\n\n if (!jsiiSymbol.sourceAssembly) {\n throw new Error('`resolveJsiiSymbolType: requires an actual source assembly');\n }\n\n const type = jsiiSymbol.sourceAssembly?.assembly.types?.[jsiiSymbol.fqn];\n if (!type) {\n throw new Error(\n `resolveJsiiSymbolType: ${jsiiSymbol.fqn} not found in assembly ${jsiiSymbol.sourceAssembly.assembly.name}`,\n );\n }\n return type;\n}\n\n/**\n * Returns the jsii FQN for a TypeScript (class or type) symbol\n *\n * TypeScript only knows the symbol NAME plus the FILE the symbol is defined\n * in. We need to extract two things:\n *\n * 1. The package name (extracted from the nearest `package.json`)\n * 2. The submodule name (...?? don't know how to get this yet)\n * 3. Any containing type names or namespace names.\n *\n * For tests, we also treat symbols in a file that has the string '/// fake-from-jsii'\n * as coming from jsii.\n */\nexport function lookupJsiiSymbol(typeChecker: ts.TypeChecker, sym: ts.Symbol): JsiiSymbol | undefined {\n // Resolve alias, if it is one. This comes into play if the symbol refers to a module,\n // we need to resolve the alias to find the ACTUAL module.\n if (hasAnyFlag(sym.flags, ts.SymbolFlags.Alias)) {\n sym = typeChecker.getAliasedSymbol(sym);\n }\n\n const decl: ts.Node | undefined = sym.declarations?.[0];\n if (!decl) {\n return undefined;\n }\n\n if (ts.isSourceFile(decl)) {\n // This is a module.\n const sourceAssembly = findTypeLookupAssembly(decl.fileName);\n return fmap(\n sourceAssembly,\n (asm) =>\n ({\n fqn:\n fmap(\n symbolIdentifier(\n typeChecker,\n sym,\n fmap(sourceAssembly, (sa) => ({ assembly: sa.assembly })),\n ),\n (symbolId) => sourceAssembly?.symbolIdMap[symbolId],\n ) ?? sourceAssembly?.assembly.name,\n sourceAssembly: asm,\n symbolType: 'module',\n } as JsiiSymbol),\n );\n }\n\n if (!isDeclaration(decl)) {\n return undefined;\n }\n\n const declaringFile = decl.getSourceFile();\n if (/^\\/\\/\\/ fake-from-jsii/m.test(declaringFile.getFullText())) {\n return { fqn: `fake_jsii.${sym.name}`, symbolType: 'type' };\n }\n\n const declSym = getSymbolFromDeclaration(decl, typeChecker);\n if (!declSym) {\n return undefined;\n }\n\n const fileName = decl.getSourceFile().fileName;\n const sourceAssembly = findTypeLookupAssembly(fileName);\n const symbolId = symbolIdentifier(typeChecker, declSym, { assembly: sourceAssembly?.assembly });\n if (!symbolId) {\n return undefined;\n }\n\n return fmap(/([^#]*)(#.*)?/.exec(symbolId), ([, typeSymbolId, memberFragment]) => {\n if (memberFragment) {\n return fmap(sourceAssembly?.symbolIdMap[typeSymbolId], (fqn) => ({\n fqn: `${fqn}${memberFragment}`,\n sourceAssembly,\n symbolType: 'member',\n }));\n }\n\n return fmap(sourceAssembly?.symbolIdMap[typeSymbolId], (fqn) => ({ fqn, sourceAssembly, symbolType: 'type' }));\n });\n}\n\nfunction isDeclaration(x: ts.Node): x is ts.Declaration {\n return (\n ts.isClassDeclaration(x) ||\n ts.isNamespaceExportDeclaration(x) ||\n ts.isNamespaceExport(x) ||\n ts.isModuleDeclaration(x) ||\n ts.isEnumDeclaration(x) ||\n ts.isEnumMember(x) ||\n ts.isInterfaceDeclaration(x) ||\n ts.isMethodDeclaration(x) ||\n ts.isMethodSignature(x) ||\n ts.isPropertyDeclaration(x) ||\n ts.isPropertySignature(x)\n );\n}\n\n/**\n * If the given type is an enum literal, resolve to the enum type\n */\nexport function resolveEnumLiteral(typeChecker: ts.TypeChecker, type: ts.Type) {\n if (!hasAnyFlag(type.flags, ts.TypeFlags.EnumLiteral)) {\n return type;\n }\n\n return typeChecker.getBaseTypeOfLiteralType(type);\n}\n\nexport function resolvedSymbolAtLocation(typeChecker: ts.TypeChecker, node: ts.Node) {\n let symbol = typeChecker.getSymbolAtLocation(node);\n while (symbol && hasAnyFlag(symbol.flags, ts.SymbolFlags.Alias)) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n return symbol;\n}\n\nfunction getSymbolFromDeclaration(decl: ts.Node, typeChecker: ts.TypeChecker): ts.Symbol | undefined {\n if (!isDeclaration(decl)) {\n return undefined;\n }\n\n const name = ts.getNameOfDeclaration(decl);\n return name ? typeChecker.getSymbolAtLocation(name) : undefined;\n}\n\nexport function parentSymbol(sym: JsiiSymbol): JsiiSymbol | undefined {\n const parts = sym.fqn.split('.');\n if (parts.length === 1) {\n return undefined;\n }\n\n return {\n fqn: parts.slice(0, -1).join('.'),\n symbolType: 'module', // Might not be true, but probably good enough\n sourceAssembly: sym.sourceAssembly,\n };\n}\n\n/**\n * Get the last part of a dot-separated string\n */\nexport function simpleName(x: string) {\n return x.split('.').slice(-1)[0];\n}\n\n/**\n * Get all parts except the last of a dot-separated string\n */\nexport function namespaceName(x: string) {\n return x.split('.').slice(0, -1).join('.');\n}\n"]}
1
+ {"version":3,"file":"jsii-utils.js","sourceRoot":"","sources":["../../src/jsii/jsii-utils.ts"],"names":[],"mappings":";;;AAAA,mCAAmC;AACnC,wCAA+C;AAC/C,iCAAiC;AAEjC,6CAA0E;AAG1E,+CAA4D;AAC5D,kCAA+B;AAE/B,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,kDAAkD;IAClD,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC/B,CAAC;AAHD,8CAGC;AAED,SAAgB,iBAAiB,CAAC,WAA2B,EAAE,IAAa;IAC1E,IACE,CAAC,IAAI,CAAC,kBAAkB,EAAE;QAC1B,CAAC,WAAW,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,SAAS,CAAC;QACxD,CAAC,iBAAiB,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EACpC,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,OAAO,GAAG,gBAAgB,CAAC,WAAW,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3D,IAAI,OAAO,EAAE,CAAC;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AC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;QACjC,UAAU,EAAE,QAAQ,EAAE,8CAA8C;QACpE,cAAc,EAAE,GAAG,CAAC,cAAc;KACnC,CAAC;AACJ,CAAC;AAXD,oCAWC;AAED;;GAEG;AACH,SAAgB,UAAU,CAAC,CAAS;IAClC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACnC,CAAC;AAFD,gCAEC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,CAAS;IACrC,OAAO,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC7C,CAAC;AAFD,sCAEC","sourcesContent":["import * as spec from '@jsii/spec';\nimport { symbolIdentifier } from 'jsii/common';\nimport * as ts from 'typescript';\n\nimport { findTypeLookupAssembly, TypeLookupAssembly } from './assemblies';\nimport { ObjectLiteralStruct } from './jsii-types';\nimport { AstRenderer } from '../renderer';\nimport { typeContainsUndefined } from '../typescript/types';\nimport { fmap } from '../util';\n\nexport function isNamedLikeStruct(name: string) {\n // Start with an I and another uppercase character\n return !/^I[A-Z]/.test(name);\n}\n\nexport function analyzeStructType(typeChecker: ts.TypeChecker, type: ts.Type): ObjectLiteralStruct | false {\n if (\n !type.isClassOrInterface() ||\n !hasAllFlags(type.objectFlags, ts.ObjectFlags.Interface) ||\n !isNamedLikeStruct(type.symbol.name)\n ) {\n return false;\n }\n\n const jsiiSym = lookupJsiiSymbol(typeChecker, type.symbol);\n if (jsiiSym) {\n return { kind: 'struct', type, jsiiSym };\n }\n\n return { kind: 'local-struct', type };\n}\n\n/**\n * Whether the given type is a protocol AND comes from jsii\n *\n * - Protocol: a TypeScript interface that is *not* a \"struct\" type.\n * A.k.a. \"behavioral interface\".\n * - From jsii: whether the interface type is defined in and exported\n * via a jsii assembly. There can be literal interfaces defined\n * in an example, and they will not be mangled in the same way\n * as a jsii interface would be.\n *\n *\n * Examples:\n *\n * ```ts\n * // isJsiiProtocolType() -> false: not a protocol\n * interface Banana {\n * readonly arc: number;\n * }\n *\n * // isJsiiProtocolType() -> might be true: depends on whether it was defined\n * // in a jsii assembly.\n * interface IHello {\n * sayIt(): void;\n * }\n *\n * // isJsiiProtocolType() -> false: declared to not be a protocol, even though\n * // it has the naming scheme of one\n * /**\n * * @struct\n * * /\n * interface IPAddress {\n * readonly octets: number[];\n * }\n * ```\n */\nexport function isJsiiProtocolType(typeChecker: ts.TypeChecker, type: ts.Type): boolean | undefined {\n if (!type.isClassOrInterface() || !hasAllFlags(type.objectFlags, ts.ObjectFlags.Interface)) {\n return false;\n }\n\n const sym = lookupJsiiSymbol(typeChecker, type.symbol);\n if (!sym) {\n return false;\n }\n\n if (!sym.sourceAssembly) {\n // No source assembly, so this is a 'fake-from-jsii' type\n return !isNamedLikeStruct(type.symbol.name);\n }\n\n const jsiiType = resolveJsiiSymbolType(sym);\n return spec.isInterfaceType(jsiiType) && !jsiiType.datatype;\n}\n\nexport function hasAllFlags<A extends number>(flags: A, test: A) {\n // tslint:disable-next-line:no-bitwise\n return test !== 0 && (flags & test) === test;\n}\n\nexport function hasAnyFlag<A extends number>(flags: A, test: A) {\n // tslint:disable-next-line:no-bitwise\n return test !== 0 && (flags & test) !== 0;\n}\n\nexport interface StructProperty {\n name: string;\n type: ts.Type | undefined;\n questionMark: boolean;\n}\n\nexport function propertiesOfStruct(type: ts.Type, context: AstRenderer<any>): StructProperty[] {\n return type.isClassOrInterface()\n ? type.getProperties().map((s) => {\n let propType;\n let questionMark = false;\n\n const propSymbol = type.getProperty(s.name)!;\n const symbolDecl = propSymbol.valueDeclaration ?? propSymbol.declarations![0];\n if (ts.isPropertyDeclaration(symbolDecl) || ts.isPropertySignature(symbolDecl)) {\n questionMark = symbolDecl.questionToken !== undefined;\n propType = symbolDecl.type && context.typeOfType(symbolDecl.type);\n }\n\n return {\n name: s.name,\n type: propType,\n questionMark,\n };\n })\n : [];\n}\n\nexport function structPropertyAcceptsUndefined(prop: StructProperty): boolean {\n return prop.questionMark || (!!prop.type && typeContainsUndefined(prop.type));\n}\n\n/**\n * A TypeScript symbol resolved to its jsii type\n */\nexport interface JsiiSymbol {\n /**\n * FQN of the symbol\n *\n * Is either the FQN of a type (for a type). For a membr, the FQN looks like:\n * 'type.fqn#memberName'.\n */\n readonly fqn: string;\n\n /**\n * What kind of symbol this is\n */\n readonly symbolType: 'module' | 'type' | 'member';\n\n /**\n * Assembly where the type was found\n *\n * Might be undefined if the type was FAKE from jsii (for tests)\n */\n readonly sourceAssembly?: TypeLookupAssembly;\n}\n\nexport function lookupJsiiSymbolFromNode(typeChecker: ts.TypeChecker, node: ts.Node): JsiiSymbol | undefined {\n return fmap(typeChecker.getSymbolAtLocation(node), (s) => lookupJsiiSymbol(typeChecker, s));\n}\n\nexport function resolveJsiiSymbolType(jsiiSymbol: JsiiSymbol): spec.Type {\n if (jsiiSymbol.symbolType !== 'type') {\n throw new Error(\n `Expected symbol to refer to a 'type', got '${jsiiSymbol.fqn}' which is a '${jsiiSymbol.symbolType}'`,\n );\n }\n\n if (!jsiiSymbol.sourceAssembly) {\n throw new Error('`resolveJsiiSymbolType: requires an actual source assembly');\n }\n\n const type = jsiiSymbol.sourceAssembly?.assembly.types?.[jsiiSymbol.fqn];\n if (!type) {\n throw new Error(\n `resolveJsiiSymbolType: ${jsiiSymbol.fqn} not found in assembly ${jsiiSymbol.sourceAssembly.assembly.name}`,\n );\n }\n return type;\n}\n\n/**\n * Returns the jsii FQN for a TypeScript (class or type) symbol\n *\n * TypeScript only knows the symbol NAME plus the FILE the symbol is defined\n * in. We need to extract two things:\n *\n * 1. The package name (extracted from the nearest `package.json`)\n * 2. The submodule name (...?? don't know how to get this yet)\n * 3. Any containing type names or namespace names.\n *\n * For tests, we also treat symbols in a file that has the string '/// fake-from-jsii'\n * as coming from jsii.\n */\nexport function lookupJsiiSymbol(typeChecker: ts.TypeChecker, sym: ts.Symbol): JsiiSymbol | undefined {\n // Resolve alias, if it is one. This comes into play if the symbol refers to a module,\n // we need to resolve the alias to find the ACTUAL module.\n if (hasAnyFlag(sym.flags, ts.SymbolFlags.Alias)) {\n sym = typeChecker.getAliasedSymbol(sym);\n }\n\n const decl: ts.Node | undefined = sym.declarations?.[0];\n if (!decl) {\n return undefined;\n }\n\n if (ts.isSourceFile(decl)) {\n // This is a module.\n const sourceAssembly = findTypeLookupAssembly(decl.fileName);\n return fmap(\n sourceAssembly,\n (asm) =>\n ({\n fqn:\n fmap(\n symbolIdentifier(\n typeChecker,\n sym,\n fmap(sourceAssembly, (sa) => ({ assembly: sa.assembly })),\n ),\n (symbolId) => sourceAssembly?.symbolIdMap[symbolId],\n ) ?? sourceAssembly?.assembly.name,\n sourceAssembly: asm,\n symbolType: 'module',\n } as JsiiSymbol),\n );\n }\n\n if (!isDeclaration(decl)) {\n return undefined;\n }\n\n const declaringFile = decl.getSourceFile();\n if (/^\\/\\/\\/ fake-from-jsii/m.test(declaringFile.getFullText())) {\n return { fqn: `fake_jsii.${sym.name}`, symbolType: 'type' };\n }\n\n const declSym = getSymbolFromDeclaration(decl, typeChecker);\n if (!declSym) {\n return undefined;\n }\n\n const fileName = decl.getSourceFile().fileName;\n const sourceAssembly = findTypeLookupAssembly(fileName);\n const symbolId = symbolIdentifier(typeChecker, declSym, { assembly: sourceAssembly?.assembly });\n if (!symbolId) {\n return undefined;\n }\n\n return fmap(/([^#]*)(#.*)?/.exec(symbolId), ([, typeSymbolId, memberFragment]) => {\n if (memberFragment) {\n return fmap(sourceAssembly?.symbolIdMap[typeSymbolId], (fqn) => ({\n fqn: `${fqn}${memberFragment}`,\n sourceAssembly,\n symbolType: 'member',\n }));\n }\n\n return fmap(sourceAssembly?.symbolIdMap[typeSymbolId], (fqn) => ({ fqn, sourceAssembly, symbolType: 'type' }));\n });\n}\n\nfunction isDeclaration(x: ts.Node): x is ts.Declaration {\n return (\n ts.isClassDeclaration(x) ||\n ts.isNamespaceExportDeclaration(x) ||\n ts.isNamespaceExport(x) ||\n ts.isModuleDeclaration(x) ||\n ts.isEnumDeclaration(x) ||\n ts.isEnumMember(x) ||\n ts.isInterfaceDeclaration(x) ||\n ts.isMethodDeclaration(x) ||\n ts.isMethodSignature(x) ||\n ts.isPropertyDeclaration(x) ||\n ts.isPropertySignature(x)\n );\n}\n\n/**\n * If the given type is an enum literal, resolve to the enum type\n */\nexport function resolveEnumLiteral(typeChecker: ts.TypeChecker, type: ts.Type) {\n if (!hasAnyFlag(type.flags, ts.TypeFlags.EnumLiteral)) {\n return type;\n }\n\n return typeChecker.getBaseTypeOfLiteralType(type);\n}\n\nexport function resolvedSymbolAtLocation(typeChecker: ts.TypeChecker, node: ts.Node) {\n let symbol = typeChecker.getSymbolAtLocation(node);\n while (symbol && hasAnyFlag(symbol.flags, ts.SymbolFlags.Alias)) {\n symbol = typeChecker.getAliasedSymbol(symbol);\n }\n return symbol;\n}\n\nfunction getSymbolFromDeclaration(decl: ts.Node, typeChecker: ts.TypeChecker): ts.Symbol | undefined {\n if (!isDeclaration(decl)) {\n return undefined;\n }\n\n const name = ts.getNameOfDeclaration(decl);\n return name ? typeChecker.getSymbolAtLocation(name) : undefined;\n}\n\nexport function parentSymbol(sym: JsiiSymbol): JsiiSymbol | undefined {\n const parts = sym.fqn.split('.');\n if (parts.length === 1) {\n return undefined;\n }\n\n return {\n fqn: parts.slice(0, -1).join('.'),\n symbolType: 'module', // Might not be true, but probably good enough\n sourceAssembly: sym.sourceAssembly,\n };\n}\n\n/**\n * Get the last part of a dot-separated string\n */\nexport function simpleName(x: string) {\n return x.split('.').slice(-1)[0];\n}\n\n/**\n * Get all parts except the last of a dot-separated string\n */\nexport function namespaceName(x: string) {\n return x.split('.').slice(0, -1).join('.');\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"packages.js","sourceRoot":"","sources":["../../src/jsii/packages.ts"],"names":[],"mappings":";;;AAEA,SAAgB,mBAAmB,CAAC,MAAuB,EAAE,KAAa;IACxE,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,CAAC,GAAQ,MAAM,CAAC,OAAO,CAAC;IAC5B,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,EAAE;QAC7D,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KAC7B;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAPD,kDAOC","sourcesContent":["import * as spec from '@jsii/spec';\n\nexport function jsiiTargetParameter(target: spec.Targetable, field: string) {\n const path = field.split('.');\n let r: any = target.targets;\n while (path.length > 0 && typeof r === 'object' && r !== null) {\n r = r[path.splice(0, 1)[0]];\n }\n return r;\n}\n"]}
1
+ {"version":3,"file":"packages.js","sourceRoot":"","sources":["../../src/jsii/packages.ts"],"names":[],"mappings":";;;AAEA,SAAgB,mBAAmB,CAAC,MAAuB,EAAE,KAAa;IACxE,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9B,IAAI,CAAC,GAAQ,MAAM,CAAC,OAAO,CAAC;IAC5B,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,EAAE,CAAC;QAC9D,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC;AAPD,kDAOC","sourcesContent":["import * as spec from '@jsii/spec';\n\nexport function jsiiTargetParameter(target: spec.Targetable, field: string) {\n const path = field.split('.');\n let r: any = target.targets;\n while (path.length > 0 && typeof r === 'object' && r !== null) {\n r = r[path.splice(0, 1)[0]];\n }\n return r;\n}\n"]}
@@ -216,7 +216,7 @@ class CSharpVisitor extends default_1.DefaultVisitor {
216
216
  }
217
217
  parameterDeclaration(node, renderer) {
218
218
  return new o_tree_1.OTree([
219
- ...(node.dotDotDotToken ? ['params '] : []),
219
+ ...(node.dotDotDotToken ? ['params '] : []), // Varargs. Render with 'params' keyword
220
220
  this.renderTypeNode(node.type, node.questionToken !== undefined, renderer),
221
221
  ' ',
222
222
  renderer.convert(node.name),