jsii-rosetta 5.3.52-dev.0 → 5.3.52

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.
@@ -36,7 +36,7 @@ export interface TransliterateAssemblyOptions {
36
36
  }
37
37
  /**
38
38
  * Prepares transliterated versions of the designated assemblies into the
39
- * selected taregt languages.
39
+ * selected target languages.
40
40
  *
41
41
  * @param assemblyLocations the directories which contain assemblies to
42
42
  * transliterate.
@@ -11,7 +11,7 @@ const rosetta_reader_1 = require("../rosetta-reader");
11
11
  const snippet_1 = require("../snippet");
12
12
  /**
13
13
  * Prepares transliterated versions of the designated assemblies into the
14
- * selected taregt languages.
14
+ * selected target languages.
15
15
  *
16
16
  * @param assemblyLocations the directories which contain assemblies to
17
17
  * transliterate.
@@ -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,eAA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,CAAC,IAAI;YAChB,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBAClC,iBAAiB,CAAC,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;YAC5F,CAAC;YACD,MAAM;QAER;YACE,MAAM,IAAI,KAAK,CAAC,0BAA2B,IAAY,CAAC,IAAI,EAAE,CAAC,CAAC;IACpE,CAAC;IAED,SAAS,iBAAiB,CAAC,GAAgB,EAAE,IAAsB;QACjE,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC;YAClB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,2BAA2B,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QACrG,CAAC;QAED,IAAI,IAAI,EAAE,OAAO,EAAE,CAAC;YAClB,MAAM,QAAQ,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,EAAW,CAAC;YAC/D,MAAM,OAAO,GAAG,IAAA,4CAAkC,EAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;YAC9F,MAAM,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAChE,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;gBACxB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected taregt languages.\n *\n * @param assemblyLocations the directories which contain assemblies to\n * transliterate.\n * @param targetLanguages the languages into which to transliterate.\n * @param tabletLocation an optional Rosetta tablet file to source\n * pre-transliterated snippets from.\n *\n * @experimental\n */\nexport async function transliterateAssembly(\n assemblyLocations: readonly string[],\n targetLanguages: readonly TargetLanguage[],\n options: TransliterateAssemblyOptions = {},\n): Promise<void> {\n // Start by doing an 'extract' for all these assemblies\n //\n // This will locate all examples that haven't been translated yet and translate\n // them. Importantly: it will translate them in parallel, which is going to improve\n // performance a lot. We ignore diagnostics.\n const { tablet } = await extractSnippets(assemblyLocations, {\n includeCompilerDiagnostics: true,\n loose: options.loose,\n cacheFromFile: options.tablet,\n writeToImplicitTablets: false,\n allowDirtyTranslations: true,\n });\n\n // Now do a regular \"tablet reader\" cycle, expecting everything to be translated already,\n // and therefore it doesn't matter that we do this all in a single-threaded loop.\n const rosetta = new RosettaTabletReader({\n unknownSnippets: options?.unknownSnippets ?? UnknownSnippetMode.FAIL,\n targetLanguages,\n prefixDisclaimer: true,\n });\n // Put in the same caching tablet here\n if (options.tablet) {\n await rosetta.loadTabletFromFile(options.tablet);\n }\n // Any fresh translations we just came up with\n rosetta.addTablet(tablet);\n\n const assemblies = await loadAssemblies(assemblyLocations, rosetta);\n\n for (const [location, loadAssembly] of assemblies.entries()) {\n for (const language of targetLanguages) {\n const now = new Date().getTime();\n const result = loadAssembly();\n\n if (result.targets?.[targetName(language)] == null) {\n // This language is not supported by the assembly, so we skip it...\n continue;\n }\n\n if (result.readme?.markdown) {\n result.readme.markdown = rosetta.translateSnippetsInMarkdown(\n { api: 'moduleReadme', moduleFqn: result.name },\n result.readme.markdown,\n language,\n true /* strict */,\n );\n }\n for (const type of Object.values(result.types ?? {})) {\n transliterateType(type, rosetta, language);\n }\n // eslint-disable-next-line no-await-in-loop\n await fs.writeFile(\n resolve(options?.outdir ?? location, `${SPEC_FILE_NAME}.${language}`),\n JSON.stringify(result, null, 2),\n );\n const then = new Date().getTime();\n debug(`Done transliterating ${result.name}@${result.version} to ${language} after ${then - now} milliseconds`);\n }\n }\n\n rosetta.printDiagnostics(process.stderr, process.stderr.isTTY);\n if (rosetta.hasErrors && options.strict) {\n throw new Error('Strict mode is enabled and some examples failed compilation!');\n }\n}\n\n/**\n * Given a set of directories containing `.jsii` assemblies, load all the\n * assemblies into the provided `Rosetta` instance and return a map of\n * directories to assembly-loading functions (the function re-loads the original\n * assembly from disk on each invocation).\n *\n * @param directories the assembly-containing directories to traverse.\n * @param rosetta the `Rosetta` instance in which to load assemblies.\n *\n * @returns a map of directories to a function that loads the `.jsii` assembly\n * contained therein from disk.\n */\nasync function loadAssemblies(\n directories: readonly string[],\n rosetta: RosettaTabletReader,\n): Promise<ReadonlyMap<string, AssemblyLoader>> {\n const result = new Map<string, AssemblyLoader>();\n\n for (const directory of directories) {\n const loader = () => loadAssemblyFromPath(directory);\n // eslint-disable-next-line no-await-in-loop\n await rosetta.addAssembly(loader(), directory);\n result.set(directory, loader);\n }\n\n return result;\n}\n\ntype AssemblyLoader = () => Mutable<Assembly>;\n\nfunction transliterateType(type: Type, rosetta: RosettaTabletReader, language: TargetLanguage): void {\n transliterateDocs({ api: 'type', fqn: type.fqn }, type.docs);\n switch (type.kind) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore 7029\n case TypeKind.Class:\n if (type.initializer) {\n transliterateDocs({ api: 'initializer', fqn: type.fqn }, type.initializer.docs);\n }\n\n // fallthrough\n case TypeKind.Interface:\n for (const method of type.methods ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: method.name }, method.docs);\n for (const parameter of method.parameters ?? []) {\n transliterateDocs(\n { api: 'parameter', fqn: type.fqn, methodName: method.name, parameterName: parameter.name },\n parameter.docs,\n );\n }\n }\n for (const property of type.properties ?? []) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: property.name }, property.docs);\n }\n break;\n\n case TypeKind.Enum:\n for (const member of type.members) {\n transliterateDocs({ api: 'member', fqn: type.fqn, memberName: member.name }, member.docs);\n }\n break;\n\n default:\n throw new Error(`Unsupported type kind: ${(type as any).kind}`);\n }\n\n function transliterateDocs(api: ApiLocation, docs: Docs | undefined) {\n if (docs?.remarks) {\n docs.remarks = rosetta.translateSnippetsInMarkdown(api, docs.remarks, language, true /* strict */);\n }\n\n if (docs?.example) {\n const location = { api, field: { field: 'example' } } as const;\n const snippet = typeScriptSnippetFromVisibleSource(docs.example, location, true /* strict */);\n const translation = rosetta.translateSnippet(snippet, language);\n if (translation != null) {\n docs.example = translation.source;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"transliterate.js","sourceRoot":"","sources":["../../src/commands/transliterate.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,yCAAoC;AACpC,qCAAkG;AAElG,uCAA4C;AAE5C,kEAA0D;AAC1D,wCAAmC;AACnC,sDAA4E;AAC5E,wCAA6E;AA0C7E;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,qBA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AAA,4CAAkC,EAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;YAC9F,MAAM,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;YAChE,IAAI,WAAW,IAAI,IAAI,EAAE,CAAC;gBACxB,IAAI,CAAC,OAAO,GAAG,WAAW,CAAC,MAAM,CAAC;YACpC,CAAC;QACH,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { promises as fs } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { Assembly, Docs, SPEC_FILE_NAME, Type, TypeKind, loadAssemblyFromPath } from '@jsii/spec';\n\nimport { extractSnippets } from './extract';\nimport { TargetLanguage } from '../languages';\nimport { targetName } from '../languages/target-language';\nimport { debug } from '../logging';\nimport { RosettaTabletReader, UnknownSnippetMode } from '../rosetta-reader';\nimport { typeScriptSnippetFromVisibleSource, ApiLocation } from '../snippet';\nimport { Mutable } from '../util';\n\nexport interface TransliterateAssemblyOptions {\n /**\n * Whether to ignore any missing fixture files or literate markdown documents\n * referenced by the assembly, instead of failing.\n *\n * @default false\n */\n readonly loose?: boolean;\n\n /**\n * Whether transliteration should fail upon failing to compile an example that\n * required live transliteration.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * A pre-build translation tablet (as produced by `jsii-rosetta extract`).\n *\n * @default - Only the default tablet (`.jsii.tabl.json`) files will be used.\n */\n readonly tablet?: string;\n\n /**\n * A directory to output translated assemblies to\n *\n * @default - assembly location\n */\n readonly outdir?: string;\n\n /**\n * Whether or not to live-convert samples\n *\n * @default UnknownSnippetMode.FAIL\n */\n readonly unknownSnippets?: UnknownSnippetMode;\n}\n\n/**\n * Prepares transliterated versions of the designated assemblies into the\n * selected target 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"]}
@@ -147,22 +147,23 @@ function allSnippetSources(assembly) {
147
147
  }
148
148
  exports.allSnippetSources = allSnippetSources;
149
149
  async function allTypeScriptSnippets(assemblies, loose = false) {
150
- return Promise.all(assemblies
150
+ const sources = assemblies
151
151
  .flatMap((loaded) => allSnippetSources(loaded.assembly).map((source) => ({ source, loaded })))
152
152
  .flatMap(({ source, loaded }) => {
153
153
  switch (source.type) {
154
154
  case 'example':
155
155
  return [
156
156
  {
157
- snippet: (0, snippet_1.updateParameters)((0, snippet_1.typeScriptSnippetFromSource)(source.source, { api: source.location, field: { field: 'example' } }, isStrict(loaded)), source.metadata ?? {}),
157
+ snippet: (0, snippet_1.updateParameters)((0, snippet_1.typeScriptSnippetFromVisibleSource)(source.source, { api: source.location, field: { field: 'example' } }, isStrict(loaded)), source.metadata ?? {}),
158
158
  loaded,
159
159
  },
160
160
  ];
161
161
  case 'markdown':
162
162
  return (0, extract_snippets_1.extractTypescriptSnippetsFromMarkdown)(source.markdown, source.location, isStrict(loaded)).map((snippet) => ({ snippet, loaded }));
163
163
  }
164
- })
165
- .map(async ({ snippet, loaded }) => {
164
+ });
165
+ const fixtures = [];
166
+ for (let { snippet, loaded } of sources) {
166
167
  const isInfused = snippet.parameters?.infused != null;
167
168
  // Ignore fixturization errors if requested on this command, or if the snippet was infused
168
169
  const ignoreFixtureErrors = loose || isInfused;
@@ -171,8 +172,9 @@ async function allTypeScriptSnippets(assemblies, loose = false) {
171
172
  snippet = { ...snippet, strict: false };
172
173
  }
173
174
  snippet = await withDependencies(loaded, withProjectDirectory(loaded.directory, snippet));
174
- return (0, fixtures_1.fixturize)(snippet, ignoreFixtureErrors);
175
- }));
175
+ fixtures.push((0, fixtures_1.fixturize)(snippet, ignoreFixtureErrors));
176
+ }
177
+ return fixtures;
176
178
  }
177
179
  exports.allTypeScriptSnippets = allTypeScriptSnippets;
178
180
  const MAX_ASM_CACHE = 3;
@@ -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,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,OAA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,SAAS,EAAE,cAAc,CAAC,CAAC,EAAE,CAAC;QAC/D,uBAAuB,CAAC,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
+ {"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;AAC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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 updateParameters,\n SnippetParameters,\n ApiLocation,\n parseMetadataLine,\n CompilationDependency,\n INITIALIZER_METHOD_NAME,\n typeScriptSnippetFromVisibleSource,\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 const sources = 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 typeScriptSnippetFromVisibleSource(\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\n const fixtures = [];\n for (let { snippet, loaded } of sources) {\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 fixtures.push(fixturize(snippet, ignoreFixtureErrors));\n }\n\n return fixtures;\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"]}
@@ -195,10 +195,28 @@ async function prepareDependencyDirectory(deps) {
195
195
  }, undefined, 2), {
196
196
  encoding: 'utf-8',
197
197
  });
198
- // Run NPM install on this package.json. We need to include --force for packages
199
- // that have a symbolic version in the symlinked dev tree (like "0.0.0"), but have
200
- // actual version range dependencies from externally installed packages (like "^2.0.0").
201
- cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });
198
+ // Run NPM install on this package.json.
199
+ cp.execSync([
200
+ 'npm install',
201
+ // We need to include --force for packages
202
+ // that have a symbolic version in the symlinked dev tree (like "0.0.0"), but have
203
+ // actual version range dependencies from externally installed packages (like "^2.0.0").
204
+ '--force',
205
+ // this is critical from a security perspective to prevent
206
+ // code execution as part of the install command using npm hooks. (e.g postInstall)
207
+ '--ignore-scripts',
208
+ // save time by not running audit
209
+ '--no-audit',
210
+ // ensures npm does not insert anything in $PATH
211
+ '--no-bin-links',
212
+ // don't write or update a package-lock.json file
213
+ '--no-package-lock',
214
+ // only print errors
215
+ `--loglevel error`,
216
+ ].join(' '), {
217
+ cwd: tmpDir,
218
+ encoding: 'utf-8',
219
+ });
202
220
  return tmpDir;
203
221
  }
204
222
  exports.prepareDependencyDirectory = prepareDependencyDirectory;
@@ -1 +1 @@
1
- {"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;AACjE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,QAA6B;IAC/D,MAAM,GAAG,GAA0C,EAAE,CAAC;IACtD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,uBAAuB,IAAI,EAAE,CAAC,EAAE,CAAC;YACnF,GAAG,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AARD,kDAQC;AAED;;;;;GAKG;AACI,KAAK,UAAU,gCAAgC,CAAC,IAA2C;IAChG,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,UAAU,CAA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,cAAc,CAAC,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,UAAU,KAAK,SAAS,CAC3G,CAAC;IACF,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;QACpG,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,UAAU,EAAE,QAAQ,IAAI,EAAE,EAAE,CAAC;YACrD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACnB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json. We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n cp.execSync(`npm install --force --loglevel error`, { cwd: tmpDir, encoding: 'utf-8' });\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
1
+ {"version":3,"file":"snippet-dependencies.js","sourceRoot":"","sources":["../src/snippet-dependencies.ts"],"names":[],"mappings":";;;AAAA,yCAAyC;AACzC,qCAAiD;AACjD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAElC,sCAAsC;AACtC,iCAAiC;AAEjC,6CAAgF;AAChF,qCAAqC;AAErC,iCAAwD;AACxD,iEAAiE;AACjE,MAAM,EAAE,SAAS,EAAE,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;AAElD;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,QAA6B;IAC/D,MAAM,GAAG,GAA0C,EAAE,CAAC;IACtD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,KAAK,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,uBAAuB,IAAI,EAAE,CAAC,EAAE,CAAC;YACnF,GAAG,CAAC,IAAI,CAAC,GAAG,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;QACvD,CAAC;IACH,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AARD,kDAQC;AAED;;;;;GAKG;AACI,KAAK,UAAU,gCAAgC,CAAC,IAA2C;IAChG,MAAM,SAAS,GAAG,IAAI,GAAG,EAAU,CAAC;IACpC,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAErD,IAAI,IAAI,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC;IACzB,OAAO,IAAI,EAAE,CAAC;QACZ,MAAM,iBAA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ACX,KAAK,EAAE,GAAG,EAAE,EAAE,CACZ,CAAC,MAAM,IAAA,iBAAU,EAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,EAAE,UAAU,KAAK,SAAS,CAC3G,CAAC;IACF,IAAI,SAAS,EAAE,CAAC;QACd,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,kBAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC;QACpG,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,UAAU,EAAE,QAAQ,IAAI,EAAE,EAAE,CAAC;YACrD,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;IACH,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,UAAU,CAAC,CAAwB;IAC1C,OAAO,CAAC,CAAC,IAAI,KAAK,UAAU,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAI,EAAU,EAAE,EAAU;IAC1C,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,CAAC;QACnB,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;GAEG;AACH,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import * as cp from 'node:child_process';\nimport { promises as fsPromises } from 'node:fs';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson } from '@jsii/spec';\nimport * as fastGlob from 'fast-glob';\nimport * as semver from 'semver';\n\nimport { findDependencyDirectory, findUp, isBuiltinModule } from './find-utils';\nimport * as logging from './logging';\nimport { TypeScriptSnippet, CompilationDependency } from './snippet';\nimport { mkDict, formatList, pathExists } from './util';\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nconst { intersect } = require('semver-intersect');\n\n/**\n * Collect the dependencies of a bunch of snippets together in one declaration\n *\n * We assume here the dependencies will not conflict.\n */\nexport function collectDependencies(snippets: TypeScriptSnippet[]) {\n const ret: Record<string, CompilationDependency> = {};\n for (const snippet of snippets) {\n for (const [name, source] of Object.entries(snippet.compilationDependencies ?? {})) {\n ret[name] = resolveConflict(name, source, ret[name]);\n }\n }\n return ret;\n}\n\n/**\n * Add transitive dependencies of concrete dependencies to the array\n *\n * This is necessary to prevent multiple copies of transitive dependencies on disk, which\n * jsii-based packages might not deal with very well.\n */\nexport async function expandWithTransitiveDependencies(deps: Record<string, CompilationDependency>) {\n const pathsSeen = new Set<string>();\n const queue = Object.values(deps).filter(isConcrete);\n\n let next = queue.shift();\n while (next) {\n await addDependenciesOf(next.resolvedDirectory);\n next = queue.shift();\n }\n\n async function addDependenciesOf(dir: string) {\n if (pathsSeen.has(dir)) {\n return;\n }\n pathsSeen.add(dir);\n try {\n const pj: PackageJson = JSON.parse(\n await fsPromises.readFile(path.join(dir, 'package.json'), { encoding: 'utf-8' }),\n );\n for (const [name, dep] of Object.entries(await resolveDependenciesFromPackageJson(pj, dir))) {\n if (!deps[name]) {\n deps[name] = dep;\n queue.push(dep);\n }\n }\n } catch (e: any) {\n if (e.code === 'ENOENT') {\n return;\n }\n throw e;\n }\n }\n}\n\n/**\n * Find the corresponding package directories for all dependencies in a package.json\n */\nexport async function resolveDependenciesFromPackageJson(packageJson: PackageJson | undefined, directory: string) {\n return mkDict(\n await Promise.all(\n Object.keys({ ...packageJson?.dependencies, ...packageJson?.peerDependencies })\n .filter((name) => !isBuiltinModule(name))\n .filter(\n (name) =>\n !packageJson?.bundledDependencies?.includes(name) && !packageJson?.bundleDependencies?.includes(name),\n )\n .map(\n async (name) =>\n [\n name,\n {\n type: 'concrete',\n resolvedDirectory: await fsPromises.realpath(await findDependencyDirectory(name, directory)),\n },\n ] as const,\n ),\n ),\n );\n}\n\nfunction resolveConflict(\n name: string,\n a: CompilationDependency,\n b: CompilationDependency | undefined,\n): CompilationDependency {\n if (!b) {\n return a;\n }\n\n if (a.type === 'concrete' && b.type === 'concrete') {\n if (b.resolvedDirectory !== a.resolvedDirectory) {\n throw new Error(`Dependency conflict: ${name} can be either ${a.resolvedDirectory} or ${b.resolvedDirectory}`);\n }\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'symbolic') {\n // Intersect the ranges\n return {\n type: 'symbolic',\n versionRange: myVersionIntersect(a.versionRange, b.versionRange),\n };\n }\n\n if (a.type === 'concrete' && b.type === 'symbolic') {\n const concreteVersion: string = JSON.parse(\n fs.readFileSync(path.join(a.resolvedDirectory, 'package.json'), 'utf-8'),\n ).version;\n\n if (!semver.satisfies(concreteVersion, b.versionRange, { includePrerelease: true })) {\n throw new Error(\n `Dependency conflict: ${name} expected to match ${b.versionRange} but found ${concreteVersion} at ${a.resolvedDirectory}`,\n );\n }\n\n return a;\n }\n\n if (a.type === 'symbolic' && b.type === 'concrete') {\n // Reverse roles so we fall into the previous case\n return resolveConflict(name, b, a);\n }\n\n throw new Error('Cases should have been exhaustive');\n}\n\n/**\n * Check that the directory we were given has all the necessary dependencies in it\n *\n * It's a warning if this is not true, not an error.\n */\nexport async function validateAvailableDependencies(directory: string, deps: Record<string, CompilationDependency>) {\n logging.info(`Validating dependencies at ${directory}`);\n const failures = await Promise.all(\n Object.entries(deps).flatMap(async ([name, _dep]) => {\n try {\n await findDependencyDirectory(name, directory);\n return [];\n } catch {\n return [name];\n }\n }),\n );\n\n if (failures.length > 0) {\n logging.warn(\n `${directory}: packages necessary to compile examples missing from supplied directory: ${failures.join(', ')}`,\n );\n }\n}\n\n/**\n * Intersect two semver ranges\n *\n * The package we are using for this doesn't support all syntaxes yet.\n * Do some work on top.\n */\nfunction myVersionIntersect(a: string, b: string): string {\n if (a === '*') {\n return b;\n }\n if (b === '*') {\n return a;\n }\n\n try {\n return intersect(a, b);\n } catch (e: any) {\n throw new Error(`semver-intersect does not support either '${a}' or '${b}': ${e.message}`);\n }\n}\n\n/**\n * Prepare a temporary directory with symlinks to all the dependencies we need.\n *\n * - Symlinks the concrete dependencies\n * - Tries to first find the symbolic dependencies in a potential monorepo that might be present\n * (try both `lerna` and `yarn` monorepos).\n * - Installs the remaining symbolic dependencies using 'npm'.\n */\nexport async function prepareDependencyDirectory(deps: Record<string, CompilationDependency>): Promise<string> {\n const concreteDirs = Object.values(deps)\n .filter(isConcrete)\n .map((x) => x.resolvedDirectory);\n const monorepoPackages = await scanMonoRepos(concreteDirs);\n\n const tmpDir = await fsPromises.mkdtemp(path.join(os.tmpdir(), 'rosetta'));\n logging.info(`Preparing dependency closure at ${tmpDir} (-vv for more details)`);\n\n // Resolved symbolic packages against monorepo\n const resolvedDeps = mkDict(\n Object.entries(deps).map(([name, dep]) => [\n name,\n dep.type === 'concrete'\n ? dep\n : ((monorepoPackages[name]\n ? { type: 'concrete', resolvedDirectory: monorepoPackages[name] }\n : dep) as CompilationDependency),\n ]),\n );\n\n const dependencies: Record<string, string> = {};\n for (const [name, dep] of Object.entries(resolvedDeps)) {\n if (isConcrete(dep)) {\n logging.debug(`${name} -> ${dep.resolvedDirectory}`);\n dependencies[name] = `file:${dep.resolvedDirectory}`;\n } else {\n logging.debug(`${name} @ ${dep.versionRange}`);\n dependencies[name] = dep.versionRange;\n }\n }\n\n await fsPromises.writeFile(\n path.join(tmpDir, 'package.json'),\n JSON.stringify(\n {\n name: 'examples',\n version: '0.0.1',\n private: true,\n dependencies,\n },\n undefined,\n 2,\n ),\n {\n encoding: 'utf-8',\n },\n );\n\n // Run NPM install on this package.json.\n cp.execSync(\n [\n 'npm install',\n // We need to include --force for packages\n // that have a symbolic version in the symlinked dev tree (like \"0.0.0\"), but have\n // actual version range dependencies from externally installed packages (like \"^2.0.0\").\n '--force',\n // this is critical from a security perspective to prevent\n // code execution as part of the install command using npm hooks. (e.g postInstall)\n '--ignore-scripts',\n // save time by not running audit\n '--no-audit',\n // ensures npm does not insert anything in $PATH\n '--no-bin-links',\n // don't write or update a package-lock.json file\n '--no-package-lock',\n // only print errors\n `--loglevel error`,\n ].join(' '),\n {\n cwd: tmpDir,\n encoding: 'utf-8',\n },\n );\n\n return tmpDir;\n}\n\n/**\n * Map package name to directory\n */\nasync function scanMonoRepos(startingDirs: readonly string[]): Promise<Record<string, string>> {\n const globs = new Set<string>();\n for (const dir of startingDirs) {\n // eslint-disable-next-line no-await-in-loop\n setExtend(globs, await findMonoRepoGlobs(dir));\n }\n\n if (globs.size === 0) {\n return {};\n }\n\n logging.debug(`Monorepo package sources: ${Array.from(globs).join(', ')}`);\n\n const packageDirectories = await fastGlob(Array.from(globs).map(windowsToUnix), { onlyDirectories: true });\n const results = mkDict(\n (\n await Promise.all(\n packageDirectories.map(async (directory) => {\n const pjLocation = path.join(directory, 'package.json');\n return (await pathExists(pjLocation))\n ? [[JSON.parse(await fsPromises.readFile(pjLocation, 'utf-8')).name as string, directory] as const]\n : [];\n }),\n )\n ).flat(),\n );\n\n logging.debug(`Found ${Object.keys(results).length} packages in monorepo: ${formatList(Object.keys(results))}`);\n return results;\n}\n\nasync function findMonoRepoGlobs(startingDir: string): Promise<Set<string>> {\n const ret = new Set<string>();\n\n // Lerna monorepo\n const lernaJsonDir = await findUp(startingDir, async (dir) => pathExists(path.join(dir, 'lerna.json')));\n if (lernaJsonDir) {\n const lernaJson = JSON.parse(await fsPromises.readFile(path.join(lernaJsonDir, 'lerna.json'), 'utf-8'));\n for (const glob of lernaJson?.packages ?? []) {\n ret.add(path.join(lernaJsonDir, glob));\n }\n }\n\n // Yarn monorepo\n const yarnWsDir = await findUp(\n startingDir,\n async (dir) =>\n (await pathExists(path.join(dir, 'package.json'))) &&\n JSON.parse(await fsPromises.readFile(path.join(dir, 'package.json'), 'utf-8'))?.workspaces !== undefined,\n );\n if (yarnWsDir) {\n const yarnWs = JSON.parse(await fsPromises.readFile(path.join(yarnWsDir, 'package.json'), 'utf-8'));\n for (const glob of yarnWs.workspaces?.packages ?? []) {\n ret.add(path.join(yarnWsDir, glob));\n }\n }\n\n return ret;\n}\n\nfunction isConcrete(x: CompilationDependency): x is Extract<CompilationDependency, { type: 'concrete' }> {\n return x.type === 'concrete';\n}\n\nfunction setExtend<A>(xs: Set<A>, ys: Set<A>) {\n for (const y of ys) {\n xs.add(y);\n }\n return xs;\n}\n\n/**\n * Necessary for fastGlob\n */\nfunction windowsToUnix(x: string) {\n return x.replace(/\\\\/g, '/');\n}\n"]}
package/lib/snippet.js CHANGED
@@ -61,7 +61,7 @@ exports.renderApiLocation = renderApiLocation;
61
61
  */
62
62
  function typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters = {}) {
63
63
  const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);
64
- const visibleSource = source.trimRight();
64
+ const visibleSource = source.trimEnd();
65
65
  return {
66
66
  visibleSource,
67
67
  location,
@@ -1 +1 @@
1
- {"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAAA,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB,GAAG,eAAe,CAAC;AAiBvD;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAyB;IACtD,QAAQ,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC;QAC9B,KAAK,SAAS;YACZ,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;QACtD,KAAK,UAAU;YACb,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QACtE,KAAK,SA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,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;SAC1C,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACjC,CAAC;AAPD,gDAOC;AAED;;GAEG;AACH,IAAY,iBAgDX;AAhDD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,wCAAmB,CAAA;IAEnB;;OAEG;IACH,6CAAwB,CAAA;IAExB;;;;;OAKG;IACH,4CAAuB,CAAA;IAEvB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;;OAKG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EAhDW,iBAAiB,iCAAjB,iBAAiB,QAgD5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimRight();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
1
+ {"version":3,"file":"snippet.js","sourceRoot":"","sources":["../src/snippet.ts"],"names":[],"mappings":";;;AAAA,8DAAyE;AAuEzE;;;;;GAKG;AACU,QAAA,uBAAuB,GAAG,eAAe,CAAC;AAiBvD;;GAEG;AACH,SAAgB,cAAc,CAAC,QAAyB;IACtD,QAAQ,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC;QAC9B,KAAK,SAAS;YACZ,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC;QACtD,KAAK,UAAU;YACb,OAAO,GAAG,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QACtE,KAAK,SAAS;YACZ,OAAO,iBAAiB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC3C,CAAC;AACH,CAAC;AATD,wCASC;AAED;;;;;GAKG;AACH,SAAgB,iBAAiB,CAAC,MAAmB;IACnD,QAAQ,MAAM,CAAC,GAAG,EAAE,CAAC;QACnB,KAAK,MAAM;YACT,OAAO,MAAM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C,CAAC,GAAG,CAAC,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IAEb,OAAO,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;AACjC,CAAC;AAPD,gDAOC;AAED;;GAEG;AACH,IAAY,iBAgDX;AAhDD,WAAY,iBAAiB;IAC3B;;OAEG;IACH,wCAAmB,CAAA;IAEnB;;OAEG;IACH,6CAAwB,CAAA;IAExB;;;;;OAKG;IACH,4CAAuB,CAAA;IAEvB;;;;;;;;;;;OAWG;IACH,wCAAmB,CAAA;IAEnB;;;;;OAKG;IACH,sDAAiC,CAAA;IAEjC;;;;;OAKG;IACH,4DAAuC,CAAA;AACzC,CAAC,EAhDW,iBAAiB,iCAAjB,iBAAiB,QAgD5B","sourcesContent":["import { trimCompleteSourceToVisible } from './typescript/visible-spans';\n\n/**\n * A piece of TypeScript code found in an assembly, ready to be translated\n */\nexport interface TypeScriptSnippet {\n /**\n * The snippet code that ends up in the JSII assembly\n */\n readonly visibleSource: string;\n\n /**\n * Description of where the snippet was found\n */\n readonly location: SnippetLocation;\n\n /**\n * When enhanced with a fixture, the snippet's complete source code\n */\n readonly completeSource?: string;\n\n /**\n * Parameters for the conversion\n */\n readonly parameters?: Record<string, string>;\n\n /**\n * Whether this snippet must be processed as if `--strict` was always supplied.\n *\n * @default false\n */\n readonly strict?: boolean;\n\n /**\n * Dependencies necessary to compile this snippet\n *\n * Value is a regular { name -> semver } map like NPM's `dependencies`,\n * `devDependencies` etc.\n *\n * @default none\n */\n readonly compilationDependencies?: Record<string, CompilationDependency>;\n}\n\nexport type CompilationDependency =\n | { readonly type: 'concrete'; readonly resolvedDirectory: string }\n | { readonly type: 'symbolic'; readonly versionRange: string };\n\n/**\n * Description of a location where the snippet is found\n *\n * The location does not necessarily indicate an exact source file,\n * but it will generally refer to a location that can contain one or more\n * snippets.\n */\nexport interface SnippetLocation {\n /**\n * The jsii API with which this snippet is associated\n */\n readonly api: ApiLocation;\n\n /**\n * The API field in which the snippet is found, if any\n *\n * Absence of this field is appropriate for source files (or tests),\n * but for Markdown files 'field' should really be set to a Markdown\n * location.\n */\n readonly field?: FieldLocation;\n}\n\n/**\n * How to represent the initializer in a 'parameter' type.\n *\n * (Don't feel like making everyone's `case` statement worse by adding an\n * 'initializer-parameter' variant).\n */\nexport const INITIALIZER_METHOD_NAME = '<initializer>';\n\nexport type ApiLocation =\n | { readonly api: 'file'; readonly fileName: string }\n | { readonly api: 'moduleReadme'; readonly moduleFqn: string }\n | { readonly api: 'type'; readonly fqn: string }\n | { readonly api: 'initializer'; readonly fqn: string }\n | { readonly api: 'member'; readonly fqn: string; readonly memberName: string }\n | {\n readonly api: 'parameter';\n readonly fqn: string;\n readonly methodName: string | typeof INITIALIZER_METHOD_NAME;\n readonly parameterName: string;\n };\n\nexport type FieldLocation = { readonly field: 'markdown'; readonly line: number } | { readonly field: 'example' };\n\n/**\n * Render an API location to a human readable representation\n */\nexport function formatLocation(location: SnippetLocation): string {\n switch (location.field?.field) {\n case 'example':\n return `${renderApiLocation(location.api)}-example`;\n case 'markdown':\n return `${renderApiLocation(location.api)}-L${location.field.line}`;\n case undefined:\n return renderApiLocation(location.api);\n }\n}\n\n/**\n * Render an API location to an unique string\n *\n * This function is used in hashing examples for reuse, and so the formatting\n * here should not be changed lightly.\n */\nexport function renderApiLocation(apiLoc: ApiLocation): string {\n switch (apiLoc.api) {\n case 'file':\n return apiLoc.fileName;\n case 'moduleReadme':\n return `${apiLoc.moduleFqn}-README`;\n case 'type':\n return apiLoc.fqn;\n case 'initializer':\n return `${apiLoc.fqn}#initializer`;\n case 'member':\n return `${apiLoc.fqn}#${apiLoc.memberName}`;\n case 'parameter':\n return `${apiLoc.fqn}#${apiLoc.methodName}!#${apiLoc.parameterName}`;\n }\n}\n\n/**\n * Construct a TypeScript snippet from visible source\n *\n * Will parse parameters from a directive in the given source, but will not\n * interpret `/// !show` and `/// !hide` directives.\n *\n * `/// !show` and `/// !hide` directives WILL affect what gets displayed by\n * the translator, but they will NOT affect the snippet's cache key (i.e. the\n * cache key will be based on the full source given here).\n *\n * Use this if you are looking up a snippet in a tablet, which has been translated\n * previously using a fixture.\n */\nexport function typeScriptSnippetFromVisibleSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const visibleSource = source.trimEnd();\n\n return {\n visibleSource,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\n/**\n * Construct a TypeScript snippet from literal source\n *\n * @deprecated Use `typeScriptSnippetFromVisibleSource`\n */\nexport function typeScriptSnippetFromSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n return typeScriptSnippetFromVisibleSource(typeScriptSource, location, strict, parameters);\n}\n\n/**\n * Construct a TypeScript snippet from complete source\n *\n * Will parse parameters from a directive in the given source, and will\n * interpret `/// !show` and `/// !hide` directives.\n *\n * The snippet's cache key will be based on the source that remains after\n * these directives are processed.\n *\n * Use this if you are building a snippet to be translated, and take care\n * to store the return object's `visibleSource` in the assembly (not the original\n * source you passed in).\n */\nexport function typeScriptSnippetFromCompleteSource(\n typeScriptSource: string,\n location: SnippetLocation,\n strict: boolean,\n parameters: Record<string, string> = {},\n): TypeScriptSnippet {\n const [source, sourceParameters] = parametersFromSourceDirectives(typeScriptSource);\n const completeSrc = source.trimRight();\n\n const visibleSource = trimCompleteSourceToVisible(completeSrc);\n\n return {\n visibleSource,\n completeSource: visibleSource !== completeSrc ? completeSrc : undefined,\n location,\n parameters: Object.assign({}, parameters, sourceParameters),\n strict,\n };\n}\n\nexport function updateParameters(snippet: TypeScriptSnippet, params: Record<string, string>): TypeScriptSnippet {\n return {\n ...snippet,\n parameters: Object.assign(Object.create(null), snippet.parameters ?? {}, params),\n };\n}\n\n/**\n * Get the complete (compilable) source of a snippet\n */\nexport function completeSource(snippet: TypeScriptSnippet) {\n return snippet.completeSource ?? snippet.visibleSource;\n}\n\n/**\n * Extract snippet parameters from the first line of the source if it's a compiler directive\n */\nfunction parametersFromSourceDirectives(source: string): [string, Record<string, string>] {\n const [firstLine, ...rest] = source.split('\\n');\n // Also extract parameters from an initial line starting with '/// ' (getting rid of that line).\n const m = /[/]{3}(.*)$/.exec(firstLine);\n if (m) {\n return [rest.join('\\n'), parseMetadataLine(m[1])];\n }\n\n return [source, {}];\n}\n\n/**\n * Parse a set of 'param param=value' directives into an object\n */\nexport function parseKeyValueList(parameters: string[]): Record<string, string> {\n const ret: Record<string, string> = {};\n for (const param of parameters) {\n const parts = param.split('=', 2);\n if (parts.length === 2) {\n ret[parts[0]] = parts[1];\n } else {\n ret[parts[0]] = '';\n }\n }\n return ret;\n}\n\nexport function parseMetadataLine(metadata: string): Record<string, string> {\n return parseKeyValueList(parseMetadata(metadata));\n\n function parseMetadata(md: string): string[] {\n return md\n .trim()\n .split(' ')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n }\n}\n\nexport function renderMetadataline(metadata: Record<string, string> = {}): string | undefined {\n const line = Object.entries(metadata)\n .filter(([key, _]) => !key.startsWith('$'))\n .map(([key, value]) => (value !== '' ? `${key}=${value}` : key))\n .join(' ');\n\n return line ? line : undefined;\n}\n\n/**\n * Recognized snippet parameters\n */\nexport enum SnippetParameters {\n /**\n * Use fixture with the given name (author parameter)\n */\n FIXTURE = 'fixture',\n\n /**\n * Don't use a fixture (author parameter)\n */\n NO_FIXTURE = 'nofixture',\n\n /**\n * Snippet was extracted from this literate file (backwards compatibility)\n *\n * Parameter attached by 'jsii'; load the given file instead of any fixture,\n * process as usual.\n */\n LITERATE_SOURCE = 'lit',\n\n /**\n * This snippet has been infused\n *\n * This means it has been copied from a different location, and potentially\n * even from a different assembly. If so, we can't expect it to compile in\n * the future, and if doesn't, we ignore the errors.\n *\n * N.B: this shouldn't make a difference in normal operation, as the `infuse`\n * command will duplicate the translation to the target tablet. This only\n * matters if we remove the tablet and try to re-extract an assembly with\n * infused examples from somewher else.\n */\n INFUSED = 'infused',\n\n /**\n * What directory to resolve fixtures in for this snippet (system parameter)\n *\n * Attached during processing, should not be used by authors. Does NOT imply\n * anything about the directory where we pretend to compile this file.\n */\n $PROJECT_DIRECTORY = '$directory',\n\n /**\n * What directory to pretend the file is in (system parameter)\n *\n * Attached when compiling a literate file, as they compile in\n * the location where they are stored.\n */\n $COMPILATION_DIRECTORY = '$compilation',\n}\n"]}
package/package.json CHANGED
@@ -59,14 +59,14 @@
59
59
  "memfs": "^4.11.1",
60
60
  "mock-fs": "^5.2.0",
61
61
  "prettier": "^2.8.8",
62
- "projen": "^0.86.4",
62
+ "projen": "^0.86.5",
63
63
  "tar": "^6.2.1",
64
64
  "ts-jest": "^29.2.5",
65
65
  "ts-node": "^10.9.2"
66
66
  },
67
67
  "dependencies": {
68
- "@jsii/check-node": "1.102.0",
69
- "@jsii/spec": "^1.102.0",
68
+ "@jsii/check-node": "1.103.0",
69
+ "@jsii/spec": "^1.103.0",
70
70
  "@xmldom/xmldom": "^0.8.10",
71
71
  "chalk": "^4",
72
72
  "commonmark": "^0.31.1",
@@ -88,7 +88,7 @@
88
88
  "publishConfig": {
89
89
  "access": "public"
90
90
  },
91
- "version": "5.3.52-dev.0",
91
+ "version": "5.3.52",
92
92
  "types": "lib/index.d.ts",
93
93
  "exports": {
94
94
  ".": "./lib/index.js",