jsii 5.9.59 → 5.9.61-dev.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/assembler.js +47 -13
- package/lib/assembler.js.map +1 -1
- package/lib/docs.js +67 -1
- package/lib/docs.js.map +1 -1
- package/lib/helpers.js +5 -1
- package/lib/helpers.js.map +1 -1
- package/lib/jsii-diagnostic.d.ts +1 -1
- package/lib/jsii-diagnostic.js +2 -2
- package/lib/jsii-diagnostic.js.map +1 -1
- package/lib/transforms/deprecation-warnings.d.ts +0 -5
- package/lib/transforms/deprecation-warnings.js +28 -17
- package/lib/transforms/deprecation-warnings.js.map +1 -1
- package/lib/tsconfig/rulesets/configurable-options.js +2 -0
- package/lib/tsconfig/rulesets/configurable-options.js.map +1 -1
- package/lib/version.d.ts +2 -2
- package/lib/version.js +2 -2
- package/lib/version.js.map +1 -1
- package/package.json +4 -3
package/lib/docs.js
CHANGED
|
@@ -63,7 +63,7 @@ const RECOGNIZED_TAGS = new Set(Object.values(DocTag));
|
|
|
63
63
|
* Parse all doc comments that apply to a symbol into JSIIDocs format
|
|
64
64
|
*/
|
|
65
65
|
function parseSymbolDocumentation(sym, typeChecker) {
|
|
66
|
-
const comment = ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim();
|
|
66
|
+
const comment = rejoinMultilineInlineLinks(ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim(), sym);
|
|
67
67
|
const tags = reabsorbExampleTags(sym.getJsDocTags());
|
|
68
68
|
// Right here we'll just guess that the first declaration site is the most important one.
|
|
69
69
|
return parseDocParts(comment, tags);
|
|
@@ -231,6 +231,72 @@ function parseStability(s, diagnostics) {
|
|
|
231
231
|
diagnostics.push(`Unrecognized @stability: '${s}'`);
|
|
232
232
|
return undefined;
|
|
233
233
|
}
|
|
234
|
+
/**
|
|
235
|
+
* TypeScript's JSDoc parser terminates `{@link}` / `{@linkcode}` / `{@linkplain}` at a newline
|
|
236
|
+
* (`parseJSDocLink` stops on `NewLineTrivia`). It still emits a closing `}` for the truncated
|
|
237
|
+
* tag, so a label continued on the next JSDoc line leaks as `} * rest}`.
|
|
238
|
+
*
|
|
239
|
+
* Rejoin those labels from source while leaving TypeScript's rendering of well-formed
|
|
240
|
+
* single-line links unchanged.
|
|
241
|
+
*/
|
|
242
|
+
function rejoinMultilineInlineLinks(comment, symbol) {
|
|
243
|
+
if (!/\{@link(?:code|plain)?\b/.test(comment)) {
|
|
244
|
+
return comment;
|
|
245
|
+
}
|
|
246
|
+
for (const declaration of symbol.getDeclarations() ?? []) {
|
|
247
|
+
for (const jsdoc of ts.getJSDocCommentsAndTags(declaration)) {
|
|
248
|
+
if (!ts.isJSDoc(jsdoc) || !Array.isArray(jsdoc.comment)) {
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
comment = rejoinTruncatedLinksFromParts(comment, jsdoc.comment);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return comment;
|
|
255
|
+
}
|
|
256
|
+
function rejoinTruncatedLinksFromParts(comment, parts) {
|
|
257
|
+
let searchFrom = 0;
|
|
258
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
259
|
+
const part = parts[i];
|
|
260
|
+
const rest = parts[i + 1];
|
|
261
|
+
if (!ts.isJSDocLinkLike(part) || rest.kind !== ts.SyntaxKind.JSDocText) {
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
// A truncated tag's source does not include the closing `}`.
|
|
265
|
+
if (part.getText().includes('}')) {
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const leakedClose = rest.text.indexOf('}');
|
|
269
|
+
if (leakedClose < 0) {
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
const leaked = rest.text.slice(0, leakedClose + 1);
|
|
273
|
+
const leakedAt = comment.indexOf(`}${leaked}`, searchFrom);
|
|
274
|
+
if (leakedAt < 0) {
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
const linkStart = comment.lastIndexOf('{@', leakedAt);
|
|
278
|
+
if (linkStart < searchFrom) {
|
|
279
|
+
continue;
|
|
280
|
+
}
|
|
281
|
+
const repaired = formatInlineLinkFromSource(part);
|
|
282
|
+
comment = comment.slice(0, linkStart) + repaired + comment.slice(leakedAt + 1 + leaked.length);
|
|
283
|
+
searchFrom = linkStart + repaired.length;
|
|
284
|
+
}
|
|
285
|
+
return comment;
|
|
286
|
+
}
|
|
287
|
+
function formatInlineLinkFromSource(link) {
|
|
288
|
+
const source = link.getSourceFile().text;
|
|
289
|
+
const open = source.indexOf('{@', link.pos);
|
|
290
|
+
const close = open >= 0 ? source.indexOf('}', open) : -1;
|
|
291
|
+
const raw = close >= 0 ? source.slice(open, close + 1) : link.getText();
|
|
292
|
+
const flattened = raw
|
|
293
|
+
.replace(/\r?\n\s*\*\s?/g, ' ')
|
|
294
|
+
.replace(/\s+/g, ' ')
|
|
295
|
+
.trim();
|
|
296
|
+
// TypeScript drops `|` and inserts a space even when the source has no whitespace:
|
|
297
|
+
// `{@link URL|label}` and `{@link URL | label}` both become `{@link URL label}`.
|
|
298
|
+
return flattened.replace(/^\{@(link|linkcode|linkplain)\s+([^|]+?)\s*\|\s*/i, '{@$1 $2 ').replace(/\s+}/, '}');
|
|
299
|
+
}
|
|
234
300
|
/**
|
|
235
301
|
* Unrecognized tags that follow an '@ example' tag will be absorbed back into the example value
|
|
236
302
|
*
|
package/lib/docs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"docs.js","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":";;AA8DA,4DAMC;AAKD,wDASC;AA4GD,oCAOC;AArMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,mCAAmC;AACnC,iCAAiC;AAEjC;;GAEG;AACH,IAAK,MAiBJ;AAjBD,WAAK,MAAM;IACT,yBAAe,CAAA;IACf,6BAAmB,CAAA;IACnB,wCAA8B,CAAA;IAC9B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EAAE,CAAC;QACtB,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAC9B,OAAO,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,MAAM,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;gBACnE,2DAA2D;gBAC3D,MAAA,GAAG,CAAC,CAAC,CAAC,EAAC,IAAI,QAAJ,IAAI,GAAK,EAAE,EAAC;gBACnB,GAAG,CAAC,CAAC,CAAC,CAAC,IAAK,CAAC,IAAI,CAAC;oBAChB,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE;oBAC7C,IAAI,EAAE,EAAE;iBACT,CAAC,CAAC;gBACH,GAAG,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;YACvB,CAAC;QACH,CAAC;QACD,CAAC,EAAE,CAAC;IACN,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Doc Comment parsing\n *\n * I tried using TSDoc here.\n *\n * Pro:\n * - Future standard.\n * - Does validating parsing and complains on failure.\n * - Has a more flexible interpretation of the @example tag (starts in text mode).\n *\n * Con:\n * - Different tags from JSDoc (@defaultValue instead of @default, \"@param name\n * description\" instead \"@param name description\".\n * - @example tag has a different interpretation than VSCode and JSDoc\n * (VSCode/JSDoc starts in code mode), which is confusing for syntax\n * highlighting in the editor.\n * - Allows no unknown tags.\n * - Wants to be in charge of parsing TypeScript, integrating into other build is\n * possible but harder.\n * - Parse to a DOM with no easy way to roundtrip back to equivalent MarkDown.\n *\n * Especially the last point: while parsing to and storing the parsed docs DOM\n * in the jsii assembly is superior in the long term (for example for\n * converting to different output formats, JavaDoc, C# docs, refdocs which all\n * accept slightly different syntaxes), right now we can get 80% of the bang\n * for 10% of the buck by just reading, storing and reproducing MarkDown, which\n * is Readable Enough(tm).\n *\n * If we ever want to attempt TSDoc again, this would be a good place to look at:\n *\n * https://github.com/Microsoft/tsdoc/blob/master/api-demo/src/advancedDemo.ts\n */\nimport * as spec from '@jsii/spec';\nimport * as ts from 'typescript';\n\n/**\n * Tags that we recognize\n */\nenum DocTag {\n PARAM = 'param',\n DEFAULT = 'default',\n DEFAULT_VALUE = 'defaultValue',\n DEPRECATED = 'deprecated',\n RETURNS = 'returns',\n RETURN = 'return',\n STABLE = 'stable',\n EXPERIMENTAL = 'experimental',\n SEE = 'see',\n SUBCLASSABLE = 'subclassable',\n EXAMPLE = 'example',\n STABILITY = 'stability',\n STRUCT = 'struct',\n\n // Not forwarded, this is compiler-internal.\n JSII = 'jsii',\n}\n\nconst RECOGNIZED_TAGS: ReadonlySet<String> = new Set(Object.values(DocTag));\n\n/**\n * Parse all doc comments that apply to a symbol into JSIIDocs format\n */\nexport function parseSymbolDocumentation(sym: ts.Symbol, typeChecker: ts.TypeChecker): DocsParsingResult {\n const comment = ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim();\n const tags = reabsorbExampleTags(sym.getJsDocTags());\n\n // Right here we'll just guess that the first declaration site is the most important one.\n return parseDocParts(comment, tags);\n}\n\n/**\n * Return the list of parameter names that are referenced in the docstring for this symbol\n */\nexport function getReferencedDocParams(sym: ts.Symbol): string[] {\n const ret = new Array<string>();\n for (const tag of sym.getJsDocTags()) {\n if (tag.name === DocTag.PARAM) {\n const parts = ts.displayPartsToString(tag.text).split(' ');\n ret.push(parts[0]);\n }\n }\n return ret;\n}\n\nfunction parseDocParts(comments: string | undefined, tags: ts.JSDocTagInfo[]): DocsParsingResult {\n const diagnostics = new Array<string>();\n const docs: spec.Docs = {};\n const hints: TypeSystemHints = {};\n\n [docs.summary, docs.remarks] = splitSummary(comments);\n\n const tagNames = new Map<string, string | undefined>();\n for (const tag of tags) {\n // 'param' gets parsed as a tag and as a comment for a method\n // 'jsii' is internal-only and shouldn't surface in the API doc\n if (tag.name !== DocTag.PARAM && tag.name !== DocTag.JSII) {\n tagNames.set(tag.name, tag.text && ts.displayPartsToString(tag.text));\n }\n }\n\n function eatTag(...names: string[]): string | undefined {\n for (const name of names) {\n if (tagNames.has(name)) {\n const ret = tagNames.get(name);\n tagNames.delete(name);\n return ret ?? '';\n }\n }\n return undefined;\n }\n\n if (eatTag(DocTag.STRUCT) != null) {\n hints.struct = true;\n }\n\n docs.default = eatTag(DocTag.DEFAULT, DocTag.DEFAULT_VALUE);\n docs.deprecated = eatTag(DocTag.DEPRECATED);\n docs.example = eatTag(DocTag.EXAMPLE);\n docs.returns = eatTag(DocTag.RETURNS, DocTag.RETURN);\n docs.see = eatTag(DocTag.SEE);\n docs.subclassable = eatTag(DocTag.SUBCLASSABLE) !== undefined ? true : undefined;\n\n docs.stability = parseStability(eatTag(DocTag.STABILITY), diagnostics);\n // @experimental is a shorthand for '@stability experimental', same for '@stable'\n const experimental = eatTag(DocTag.EXPERIMENTAL) !== undefined;\n const stable = eatTag(DocTag.STABLE) !== undefined;\n // Can't combine them\n if (countBools(docs.stability !== undefined, experimental, stable) > 1) {\n diagnostics.push('Use only one of @stability, @experimental or @stable');\n }\n if (experimental) {\n docs.stability = spec.Stability.Experimental;\n }\n if (stable) {\n docs.stability = spec.Stability.Stable;\n }\n\n // Can combine '@stability deprecated' with '@deprecated <reason>'\n if (docs.deprecated !== undefined) {\n if (docs.stability !== undefined && docs.stability !== spec.Stability.Deprecated) {\n diagnostics.push(\"@deprecated tag requires '@stability deprecated' or no @stability at all.\");\n }\n docs.stability = spec.Stability.Deprecated;\n }\n\n if (docs.example?.includes('```')) {\n // This is currently what the JSDoc standard expects, and VSCode highlights it in\n // this way as well. TSDoc disagrees and says that examples start in text mode\n // which I tend to agree with, but that hasn't become a widely used standard yet.\n //\n // So we conform to existing reality.\n diagnostics.push('@example must be code only, no code block fences allowed.');\n }\n\n if (docs.deprecated?.trim() === '') {\n diagnostics.push('@deprecated tag needs a reason and/or suggested alternatives.');\n }\n\n if (tagNames.size > 0) {\n docs.custom = {};\n for (const [key, value] of tagNames.entries()) {\n docs.custom[key] = value ?? 'true'; // Key must have a value or it will be stripped from the assembly\n }\n }\n\n return { docs, diagnostics, hints };\n}\n\nexport interface DocsParsingResult {\n docs: spec.Docs;\n hints: TypeSystemHints;\n diagnostics?: string[];\n}\n\nexport interface TypeSystemHints {\n /**\n * Only present on interfaces. This indicates that interface must be handled as a struct/data type\n * even through it's name starts with a capital letter `I`.\n */\n struct?: boolean;\n}\n\n/**\n * Split the doc comment into summary and remarks\n *\n * Normally, we'd expect people to split into a summary line and detail lines using paragraph\n * markers. However, a LOT of people do not do this, and just paste a giant comment block into\n * the docstring. If we detect that situation, we will try and extract the first sentence (using\n * a period) as the summary.\n */\nexport function splitSummary(docBlock: string | undefined): [string | undefined, string | undefined] {\n if (!docBlock) {\n return [undefined, undefined];\n }\n const summary = summaryLine(docBlock);\n const remarks = uberTrim(docBlock.slice(summary.length));\n return [endWithPeriod(noNewlines(summary.trim())), remarks];\n}\n\n/**\n * Replace newlines with spaces for use in tables\n */\nfunction noNewlines(s: string) {\n return s.replace(/\\r?\\n/g, ' ');\n}\n\nfunction endWithPeriod(s: string) {\n return ENDS_WITH_PUNCTUATION_REGEX.test(s) ? s : `${s}.`;\n}\n\n/**\n * Trims a string and turns it into `undefined` if the result would have been an\n * empty string.\n */\nfunction uberTrim(str: string): string | undefined {\n str = str.trim();\n return str === '' ? undefined : str;\n}\n\nconst SUMMARY_MAX_WORDS = 20;\n\n/**\n * Find the summary line for a doc comment\n *\n * In principle we'll take the first paragraph, but if there are no paragraphs\n * (because people don't put in paragraph breaks) or the first paragraph is too\n * long, we'll take the first sentence (terminated by a punctuation).\n */\nfunction summaryLine(str: string) {\n const paras = str.split(/(\\r?\\n){2}/);\n if (paras.length > 1 && paras[0].split(' ').length < SUMMARY_MAX_WORDS) {\n return paras[0];\n }\n\n const m = FIRST_SENTENCE_REGEX.exec(str);\n if (m) {\n return m[1];\n }\n\n return paras[0];\n}\n\nconst PUNCTUATION = ['!', '?', '.', ';'].map((s) => `\\\\${s}`).join('');\nconst ENDS_WITH_PUNCTUATION_REGEX = new RegExp(`[${PUNCTUATION}]$`);\nconst FIRST_SENTENCE_REGEX = new RegExp(`^([^${PUNCTUATION}]+[${PUNCTUATION}][ \\n\\r])`); // Needs a whitespace after the punctuation.\n\nfunction intBool(x: boolean): number {\n return x ? 1 : 0;\n}\n\nfunction countBools(...x: boolean[]) {\n return x.map(intBool).reduce((a, b) => a + b, 0);\n}\n\nfunction parseStability(s: string | undefined, diagnostics: string[]): spec.Stability | undefined {\n if (s === undefined) {\n return undefined;\n }\n\n switch (s) {\n case 'stable':\n return spec.Stability.Stable;\n case 'experimental':\n return spec.Stability.Experimental;\n case 'external':\n return spec.Stability.External;\n case 'deprecated':\n return spec.Stability.Deprecated;\n }\n diagnostics.push(`Unrecognized @stability: '${s}'`);\n return undefined;\n}\n\n/**\n * Unrecognized tags that follow an '@ example' tag will be absorbed back into the example value\n *\n * The TypeScript parser by itself is naive and will start parsing a new tag there.\n *\n * We do this until we encounter a supported @ keyword.\n */\nfunction reabsorbExampleTags(tags: ts.JSDocTagInfo[]): ts.JSDocTagInfo[] {\n const ret = [...tags];\n\n let i = 0;\n while (i < ret.length) {\n if (ret[i].name === 'example') {\n while (i + 1 < ret.length && !RECOGNIZED_TAGS.has(ret[i + 1].name)) {\n // Incorrectly classified as @tag, absorb back into example\n ret[i].text ??= [];\n ret[i].text!.push({\n text: `@${ret[i + 1].name}${ret[i + 1].text}`,\n kind: '',\n });\n ret.splice(i + 1, 1);\n }\n }\n i++;\n }\n\n return ret;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"docs.js","sourceRoot":"","sources":["../src/docs.ts"],"names":[],"mappings":";;AA8DA,4DASC;AAKD,wDASC;AA4GD,oCAOC;AAxMD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+B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,CAAC;QACH,CAAC;QACD,CAAC,EAAE,CAAC;IACN,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Doc Comment parsing\n *\n * I tried using TSDoc here.\n *\n * Pro:\n * - Future standard.\n * - Does validating parsing and complains on failure.\n * - Has a more flexible interpretation of the @example tag (starts in text mode).\n *\n * Con:\n * - Different tags from JSDoc (@defaultValue instead of @default, \"@param name\n * description\" instead \"@param name description\".\n * - @example tag has a different interpretation than VSCode and JSDoc\n * (VSCode/JSDoc starts in code mode), which is confusing for syntax\n * highlighting in the editor.\n * - Allows no unknown tags.\n * - Wants to be in charge of parsing TypeScript, integrating into other build is\n * possible but harder.\n * - Parse to a DOM with no easy way to roundtrip back to equivalent MarkDown.\n *\n * Especially the last point: while parsing to and storing the parsed docs DOM\n * in the jsii assembly is superior in the long term (for example for\n * converting to different output formats, JavaDoc, C# docs, refdocs which all\n * accept slightly different syntaxes), right now we can get 80% of the bang\n * for 10% of the buck by just reading, storing and reproducing MarkDown, which\n * is Readable Enough(tm).\n *\n * If we ever want to attempt TSDoc again, this would be a good place to look at:\n *\n * https://github.com/Microsoft/tsdoc/blob/master/api-demo/src/advancedDemo.ts\n */\nimport * as spec from '@jsii/spec';\nimport * as ts from 'typescript';\n\n/**\n * Tags that we recognize\n */\nenum DocTag {\n PARAM = 'param',\n DEFAULT = 'default',\n DEFAULT_VALUE = 'defaultValue',\n DEPRECATED = 'deprecated',\n RETURNS = 'returns',\n RETURN = 'return',\n STABLE = 'stable',\n EXPERIMENTAL = 'experimental',\n SEE = 'see',\n SUBCLASSABLE = 'subclassable',\n EXAMPLE = 'example',\n STABILITY = 'stability',\n STRUCT = 'struct',\n\n // Not forwarded, this is compiler-internal.\n JSII = 'jsii',\n}\n\nconst RECOGNIZED_TAGS: ReadonlySet<String> = new Set(Object.values(DocTag));\n\n/**\n * Parse all doc comments that apply to a symbol into JSIIDocs format\n */\nexport function parseSymbolDocumentation(sym: ts.Symbol, typeChecker: ts.TypeChecker): DocsParsingResult {\n const comment = rejoinMultilineInlineLinks(\n ts.displayPartsToString(sym.getDocumentationComment(typeChecker)).trim(),\n sym,\n );\n const tags = reabsorbExampleTags(sym.getJsDocTags());\n\n // Right here we'll just guess that the first declaration site is the most important one.\n return parseDocParts(comment, tags);\n}\n\n/**\n * Return the list of parameter names that are referenced in the docstring for this symbol\n */\nexport function getReferencedDocParams(sym: ts.Symbol): string[] {\n const ret = new Array<string>();\n for (const tag of sym.getJsDocTags()) {\n if (tag.name === DocTag.PARAM) {\n const parts = ts.displayPartsToString(tag.text).split(' ');\n ret.push(parts[0]);\n }\n }\n return ret;\n}\n\nfunction parseDocParts(comments: string | undefined, tags: ts.JSDocTagInfo[]): DocsParsingResult {\n const diagnostics = new Array<string>();\n const docs: spec.Docs = {};\n const hints: TypeSystemHints = {};\n\n [docs.summary, docs.remarks] = splitSummary(comments);\n\n const tagNames = new Map<string, string | undefined>();\n for (const tag of tags) {\n // 'param' gets parsed as a tag and as a comment for a method\n // 'jsii' is internal-only and shouldn't surface in the API doc\n if (tag.name !== DocTag.PARAM && tag.name !== DocTag.JSII) {\n tagNames.set(tag.name, tag.text && ts.displayPartsToString(tag.text));\n }\n }\n\n function eatTag(...names: string[]): string | undefined {\n for (const name of names) {\n if (tagNames.has(name)) {\n const ret = tagNames.get(name);\n tagNames.delete(name);\n return ret ?? '';\n }\n }\n return undefined;\n }\n\n if (eatTag(DocTag.STRUCT) != null) {\n hints.struct = true;\n }\n\n docs.default = eatTag(DocTag.DEFAULT, DocTag.DEFAULT_VALUE);\n docs.deprecated = eatTag(DocTag.DEPRECATED);\n docs.example = eatTag(DocTag.EXAMPLE);\n docs.returns = eatTag(DocTag.RETURNS, DocTag.RETURN);\n docs.see = eatTag(DocTag.SEE);\n docs.subclassable = eatTag(DocTag.SUBCLASSABLE) !== undefined ? true : undefined;\n\n docs.stability = parseStability(eatTag(DocTag.STABILITY), diagnostics);\n // @experimental is a shorthand for '@stability experimental', same for '@stable'\n const experimental = eatTag(DocTag.EXPERIMENTAL) !== undefined;\n const stable = eatTag(DocTag.STABLE) !== undefined;\n // Can't combine them\n if (countBools(docs.stability !== undefined, experimental, stable) > 1) {\n diagnostics.push('Use only one of @stability, @experimental or @stable');\n }\n if (experimental) {\n docs.stability = spec.Stability.Experimental;\n }\n if (stable) {\n docs.stability = spec.Stability.Stable;\n }\n\n // Can combine '@stability deprecated' with '@deprecated <reason>'\n if (docs.deprecated !== undefined) {\n if (docs.stability !== undefined && docs.stability !== spec.Stability.Deprecated) {\n diagnostics.push(\"@deprecated tag requires '@stability deprecated' or no @stability at all.\");\n }\n docs.stability = spec.Stability.Deprecated;\n }\n\n if (docs.example?.includes('```')) {\n // This is currently what the JSDoc standard expects, and VSCode highlights it in\n // this way as well. TSDoc disagrees and says that examples start in text mode\n // which I tend to agree with, but that hasn't become a widely used standard yet.\n //\n // So we conform to existing reality.\n diagnostics.push('@example must be code only, no code block fences allowed.');\n }\n\n if (docs.deprecated?.trim() === '') {\n diagnostics.push('@deprecated tag needs a reason and/or suggested alternatives.');\n }\n\n if (tagNames.size > 0) {\n docs.custom = {};\n for (const [key, value] of tagNames.entries()) {\n docs.custom[key] = value ?? 'true'; // Key must have a value or it will be stripped from the assembly\n }\n }\n\n return { docs, diagnostics, hints };\n}\n\nexport interface DocsParsingResult {\n docs: spec.Docs;\n hints: TypeSystemHints;\n diagnostics?: string[];\n}\n\nexport interface TypeSystemHints {\n /**\n * Only present on interfaces. This indicates that interface must be handled as a struct/data type\n * even through it's name starts with a capital letter `I`.\n */\n struct?: boolean;\n}\n\n/**\n * Split the doc comment into summary and remarks\n *\n * Normally, we'd expect people to split into a summary line and detail lines using paragraph\n * markers. However, a LOT of people do not do this, and just paste a giant comment block into\n * the docstring. If we detect that situation, we will try and extract the first sentence (using\n * a period) as the summary.\n */\nexport function splitSummary(docBlock: string | undefined): [string | undefined, string | undefined] {\n if (!docBlock) {\n return [undefined, undefined];\n }\n const summary = summaryLine(docBlock);\n const remarks = uberTrim(docBlock.slice(summary.length));\n return [endWithPeriod(noNewlines(summary.trim())), remarks];\n}\n\n/**\n * Replace newlines with spaces for use in tables\n */\nfunction noNewlines(s: string) {\n return s.replace(/\\r?\\n/g, ' ');\n}\n\nfunction endWithPeriod(s: string) {\n return ENDS_WITH_PUNCTUATION_REGEX.test(s) ? s : `${s}.`;\n}\n\n/**\n * Trims a string and turns it into `undefined` if the result would have been an\n * empty string.\n */\nfunction uberTrim(str: string): string | undefined {\n str = str.trim();\n return str === '' ? undefined : str;\n}\n\nconst SUMMARY_MAX_WORDS = 20;\n\n/**\n * Find the summary line for a doc comment\n *\n * In principle we'll take the first paragraph, but if there are no paragraphs\n * (because people don't put in paragraph breaks) or the first paragraph is too\n * long, we'll take the first sentence (terminated by a punctuation).\n */\nfunction summaryLine(str: string) {\n const paras = str.split(/(\\r?\\n){2}/);\n if (paras.length > 1 && paras[0].split(' ').length < SUMMARY_MAX_WORDS) {\n return paras[0];\n }\n\n const m = FIRST_SENTENCE_REGEX.exec(str);\n if (m) {\n return m[1];\n }\n\n return paras[0];\n}\n\nconst PUNCTUATION = ['!', '?', '.', ';'].map((s) => `\\\\${s}`).join('');\nconst ENDS_WITH_PUNCTUATION_REGEX = new RegExp(`[${PUNCTUATION}]$`);\nconst FIRST_SENTENCE_REGEX = new RegExp(`^([^${PUNCTUATION}]+[${PUNCTUATION}][ \\n\\r])`); // Needs a whitespace after the punctuation.\n\nfunction intBool(x: boolean): number {\n return x ? 1 : 0;\n}\n\nfunction countBools(...x: boolean[]) {\n return x.map(intBool).reduce((a, b) => a + b, 0);\n}\n\nfunction parseStability(s: string | undefined, diagnostics: string[]): spec.Stability | undefined {\n if (s === undefined) {\n return undefined;\n }\n\n switch (s) {\n case 'stable':\n return spec.Stability.Stable;\n case 'experimental':\n return spec.Stability.Experimental;\n case 'external':\n return spec.Stability.External;\n case 'deprecated':\n return spec.Stability.Deprecated;\n }\n diagnostics.push(`Unrecognized @stability: '${s}'`);\n return undefined;\n}\n\n/**\n * TypeScript's JSDoc parser terminates `{@link}` / `{@linkcode}` / `{@linkplain}` at a newline\n * (`parseJSDocLink` stops on `NewLineTrivia`). It still emits a closing `}` for the truncated\n * tag, so a label continued on the next JSDoc line leaks as `} * rest}`.\n *\n * Rejoin those labels from source while leaving TypeScript's rendering of well-formed\n * single-line links unchanged.\n */\nfunction rejoinMultilineInlineLinks(comment: string, symbol: ts.Symbol): string {\n if (!/\\{@link(?:code|plain)?\\b/.test(comment)) {\n return comment;\n }\n\n for (const declaration of symbol.getDeclarations() ?? []) {\n for (const jsdoc of ts.getJSDocCommentsAndTags(declaration)) {\n if (!ts.isJSDoc(jsdoc) || !Array.isArray(jsdoc.comment)) {\n continue;\n }\n comment = rejoinTruncatedLinksFromParts(comment, jsdoc.comment);\n }\n }\n\n return comment;\n}\n\nfunction rejoinTruncatedLinksFromParts(comment: string, parts: readonly ts.JSDocComment[]): string {\n let searchFrom = 0;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const rest = parts[i + 1];\n if (!ts.isJSDocLinkLike(part) || rest.kind !== ts.SyntaxKind.JSDocText) {\n continue;\n }\n // A truncated tag's source does not include the closing `}`.\n if (part.getText().includes('}')) {\n continue;\n }\n const leakedClose = rest.text.indexOf('}');\n if (leakedClose < 0) {\n continue;\n }\n const leaked = rest.text.slice(0, leakedClose + 1);\n const leakedAt = comment.indexOf(`}${leaked}`, searchFrom);\n if (leakedAt < 0) {\n continue;\n }\n const linkStart = comment.lastIndexOf('{@', leakedAt);\n if (linkStart < searchFrom) {\n continue;\n }\n const repaired = formatInlineLinkFromSource(part);\n comment = comment.slice(0, linkStart) + repaired + comment.slice(leakedAt + 1 + leaked.length);\n searchFrom = linkStart + repaired.length;\n }\n return comment;\n}\n\nfunction formatInlineLinkFromSource(link: ts.JSDocLink | ts.JSDocLinkCode | ts.JSDocLinkPlain): string {\n const source = link.getSourceFile().text;\n const open = source.indexOf('{@', link.pos);\n const close = open >= 0 ? source.indexOf('}', open) : -1;\n const raw = close >= 0 ? source.slice(open, close + 1) : link.getText();\n const flattened = raw\n .replace(/\\r?\\n\\s*\\*\\s?/g, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n // TypeScript drops `|` and inserts a space even when the source has no whitespace:\n // `{@link URL|label}` and `{@link URL | label}` both become `{@link URL label}`.\n return flattened.replace(/^\\{@(link|linkcode|linkplain)\\s+([^|]+?)\\s*\\|\\s*/i, '{@$1 $2 ').replace(/\\s+}/, '}');\n}\n\n/**\n * Unrecognized tags that follow an '@ example' tag will be absorbed back into the example value\n *\n * The TypeScript parser by itself is naive and will start parsing a new tag there.\n *\n * We do this until we encounter a supported @ keyword.\n */\nfunction reabsorbExampleTags(tags: ts.JSDocTagInfo[]): ts.JSDocTagInfo[] {\n const ret = [...tags];\n\n let i = 0;\n while (i < ret.length) {\n if (ret[i].name === 'example') {\n while (i + 1 < ret.length && !RECOGNIZED_TAGS.has(ret[i + 1].name)) {\n // Incorrectly classified as @tag, absorb back into example\n ret[i].text ??= [];\n ret[i].text!.push({\n text: `@${ret[i + 1].name}${ret[i + 1].text}`,\n kind: '',\n });\n ret.splice(i + 1, 1);\n }\n }\n i++;\n }\n\n return ret;\n}\n"]}
|
package/lib/helpers.js
CHANGED
|
@@ -22,7 +22,11 @@ const utils_1 = require("./utils");
|
|
|
22
22
|
/**
|
|
23
23
|
* Assembly features supported by this compiler
|
|
24
24
|
*/
|
|
25
|
-
exports.ASSEMBLY_FEATURES_SUPPORTED = [
|
|
25
|
+
exports.ASSEMBLY_FEATURES_SUPPORTED = [
|
|
26
|
+
'intersection-types',
|
|
27
|
+
'class-covariant-overrides',
|
|
28
|
+
'interface-member-doc-overrides',
|
|
29
|
+
];
|
|
26
30
|
/**
|
|
27
31
|
* Compile a piece of source and return the JSII assembly for it
|
|
28
32
|
*
|
package/lib/helpers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],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,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["/**\n * Helper routines for use with the jsii compiler\n *\n * These are mostly used for testing, but all projects that need to exercise\n * the JSII compiler to test something need to share this code, so might as\n * well put it in one reusable place.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson, loadAssemblyFromPath, writeAssembly } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { Diagnostic, DiagnosticCategory } from 'typescript';\n\nimport { Compiler, CompilerOptions } from './compiler';\nimport { loadProjectInfo, ProjectInfo } from './project-info';\nimport { formatDiagnostic, JsiiError } from './utils';\n\n/**\n * A set of source files for `sourceToAssemblyHelper`, at least containing 'index.ts'\n */\nexport type MultipleSourceFiles = {\n 'index.ts': string;\n [name: string]: string;\n};\n\n/**\n * Assembly features supported by this compiler\n */\nexport const ASSEMBLY_FEATURES_SUPPORTED: spec.JsiiFeature[] = ['intersection-types', 'class-covariant-overrides'];\n\n/**\n * Compile a piece of source and return the JSII assembly for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function sourceToAssemblyHelper(\n source: string | MultipleSourceFiles,\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n): spec.Assembly {\n const result = compileJsiiForTest(source, options);\n if (result.type !== 'success') {\n throw new Error('Compilation failed');\n }\n return result.assembly;\n}\n\nexport type HelperCompilationOut = HelperCompilationResult | HelperCompilationFailure;\n\n/**\n * Successful output of a compilation command (for testing)\n *\n * A better name would have been `HelperCompilationSuccess`, but the name is part of\n * the public API surface, so we keep it like this.\n */\nexport interface HelperCompilationResult {\n readonly type: 'success';\n\n /**\n * The generated assembly\n */\n readonly assembly: spec.Assembly;\n\n /**\n * Generated .js/.d.ts file(s)\n */\n readonly files: Record<string, string>;\n\n /**\n * The packageInfo used\n */\n readonly packageJson: PackageJson;\n\n /**\n * Whether to compress the assembly file\n */\n readonly compressAssembly: boolean;\n\n /**\n * Diagnostics that occurred during compilation\n */\n readonly diagnostics: readonly Diagnostic[];\n}\n\nexport interface HelperCompilationFailure {\n readonly type: 'failure';\n\n /**\n * Diagnostics that occurred during compilation\n *\n * Contains at least one error.\n */\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Compile a piece of source and return the assembly and compiled sources for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function compileJsiiForTest<O extends TestCompilationOptions>(\n source: string | { 'index.ts': string; [name: string]: string },\n options?: O | ((obj: PackageJson) => void),\n compilerOptions?: Omit<CompilerOptions, 'projectInfo' | 'watch'>,\n): ResultOrSuccess<O> {\n if (typeof source === 'string') {\n source = { 'index.ts': source };\n }\n\n const inSomeLocation =\n isOptionsObject(options) && options.compilationDirectory ? inOtherDir(options.compilationDirectory) : inTempDir;\n\n // Easiest way to get the source into the compiler is to write it to disk somewhere.\n // I guess we could make an in-memory compiler host but that seems like work...\n return inSomeLocation(() => {\n for (const [fileName, content] of Object.entries(source)) {\n fs.mkdirSync(path.dirname(fileName), { recursive: true });\n fs.writeFileSync(fileName, content, { encoding: 'utf-8' });\n }\n const { projectInfo, packageJson } = makeProjectInfo(\n 'index.ts',\n typeof options === 'function'\n ? options\n : (pi) => {\n Object.assign(pi, options?.packageJson ?? options?.projectInfo ?? {});\n },\n );\n const compiler = new Compiler({\n projectInfo,\n ...compilerOptions,\n });\n const emitResult = compiler.emit();\n\n const errors = emitResult.diagnostics.filter((d) => d.category === DiagnosticCategory.Error);\n\n if (typeof options !== 'object' || !options?.captureDiagnostics) {\n for (const error of errors) {\n console.error(formatDiagnostic(error, projectInfo.projectRoot));\n // logDiagnostic() doesn't work out of the box, so console.error() it is.\n }\n }\n\n if (errors.length > 0 || emitResult.emitSkipped) {\n if (typeof options === 'object' && options?.captureDiagnostics) {\n return {\n type: 'failure',\n diagnostics: emitResult.diagnostics,\n } satisfies HelperCompilationFailure;\n }\n throw new JsiiError('There were compiler errors');\n }\n\n const assembly = loadAssemblyFromPath(process.cwd(), false, ASSEMBLY_FEATURES_SUPPORTED);\n const files: Record<string, string> = {};\n\n for (const filename of Object.keys(source)) {\n let jsFile = filename.replace(/\\.ts$/, '.js');\n let dtsFile = filename.replace(/\\.ts$/, '.d.ts');\n if (projectInfo.tsc?.outDir && filename !== 'README.md') {\n jsFile = path.join(projectInfo.tsc.outDir, jsFile);\n dtsFile = path.join(projectInfo.tsc.outDir, dtsFile);\n }\n\n // eslint-disable-next-line no-await-in-loop\n files[jsFile] = fs.readFileSync(jsFile, { encoding: 'utf-8' });\n // eslint-disable-next-line no-await-in-loop\n files[dtsFile] = fs.readFileSync(dtsFile, { encoding: 'utf-8' });\n\n const warningsFileName = '.warnings.jsii.js';\n if (fs.existsSync(warningsFileName)) {\n // eslint-disable-next-line no-await-in-loop\n files[warningsFileName] = fs.readFileSync(warningsFileName, {\n encoding: 'utf-8',\n });\n }\n }\n\n return {\n type: 'success',\n assembly,\n files,\n packageJson,\n compressAssembly: isOptionsObject(options) && options.compressAssembly ? true : false,\n diagnostics: emitResult.diagnostics,\n } satisfies HelperCompilationResult;\n }) as ResultOrSuccess<O>;\n}\n\ntype ResultOrSuccess<O extends TestCompilationOptions> = O['captureDiagnostics'] extends true\n ? HelperCompilationOut\n : HelperCompilationResult;\n\nfunction inTempDir<T>(block: () => T): T {\n const origDir = process.cwd();\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii'));\n process.chdir(tmpDir);\n const ret = block();\n process.chdir(origDir);\n fs.rmSync(tmpDir, { force: true, recursive: true });\n return ret;\n}\n\nfunction inOtherDir(dir: string) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\n return <T extends unknown>(block: () => T): T => {\n const origDir = process.cwd();\n process.chdir(dir);\n try {\n return block();\n } finally {\n process.chdir(origDir);\n }\n };\n}\n\n/**\n * Obtain project info so we can call the compiler\n *\n * Creating this directly in-memory leads to slightly different behavior from calling\n * jsii from the command-line, and I don't want to figure out right now.\n *\n * Most consistent behavior seems to be to write a package.json to disk and\n * then calling the same functions as the CLI would.\n */\nfunction makeProjectInfo(\n types: string,\n cb?: (obj: PackageJson) => void,\n): { projectInfo: ProjectInfo; packageJson: PackageJson } {\n const packageJson: PackageJson = {\n types,\n main: types.replace(/(?:\\.d)?\\.ts(x?)/, '.js$1'),\n name: 'testpkg', // That's what package.json would tell if we look up...\n version: '0.0.1',\n license: 'Apache-2.0',\n author: { name: 'John Doe' },\n repository: { type: 'git', url: 'https://github.com/aws/jsii.git' },\n jsii: {},\n };\n\n if (cb) {\n cb(packageJson);\n }\n\n fs.writeFileSync(\n 'package.json',\n JSON.stringify(packageJson, (_: string, v: any) => v, 2),\n 'utf-8',\n );\n\n const { projectInfo } = loadProjectInfo(path.resolve(process.cwd(), '.'));\n return { projectInfo, packageJson };\n}\n\nexport interface TestCompilationOptions {\n /**\n * The directory in which we write and compile the files\n */\n readonly compilationDirectory?: string;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @deprecated Prefer using `packageJson` instead.\n */\n readonly projectInfo?: Partial<PackageJson>;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @default - Use some default values\n */\n readonly packageJson?: Partial<PackageJson>;\n\n /**\n * Whether to compress the assembly file.\n *\n * @default false\n */\n readonly compressAssembly?: boolean;\n\n /**\n * Whether or not to print the diagnostics\n *\n * @default false\n */\n readonly captureDiagnostics?: boolean;\n}\n\nfunction isOptionsObject(\n x: TestCompilationOptions | ((obj: PackageJson) => void) | undefined,\n): x is TestCompilationOptions {\n return x ? typeof x === 'object' : false;\n}\n\n/**\n * An NPM-ready workspace where we can install test-compile dependencies and compile new assemblies\n */\nexport class TestWorkspace {\n /**\n * Create a new workspace.\n *\n * Creates a temporary directory, don't forget to call cleanUp\n */\n public static create(): TestWorkspace {\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii-testworkspace'));\n fs.mkdirSync(tmpDir, { recursive: true });\n return new TestWorkspace(tmpDir);\n }\n\n /**\n * Execute a block with a temporary workspace\n */\n public static withWorkspace<A>(block: (ws: TestWorkspace) => A): A {\n const ws = TestWorkspace.create();\n try {\n return block(ws);\n } finally {\n ws.cleanup();\n }\n }\n\n private readonly installed = new Set<string>();\n\n private constructor(public readonly rootDirectory: string) {}\n\n /**\n * Add a test-compiled jsii assembly as a dependency\n */\n public addDependency(dependencyAssembly: HelperCompilationOut) {\n if (dependencyAssembly.type !== 'success') {\n throw new JsiiError('Cannot add dependency: assembly compilation failed');\n }\n\n if (this.installed.has(dependencyAssembly.assembly.name)) {\n throw new JsiiError(\n `A dependency with name '${dependencyAssembly.assembly.name}' was already installed. Give one a different name.`,\n );\n }\n this.installed.add(dependencyAssembly.assembly.name);\n\n // The following is silly, however: the helper has compiled the given source to\n // an assembly, and output files, and then removed their traces from disk.\n // We need those files back on disk, so write them back out again.\n //\n // We will drop them in 'node_modules/<name>' so they can be imported\n // as if they were installed.\n const modDir = path.join(this.rootDirectory, 'node_modules', dependencyAssembly.assembly.name);\n fs.mkdirSync(modDir, { recursive: true });\n\n writeAssembly(modDir, dependencyAssembly.assembly, {\n compress: dependencyAssembly.compressAssembly,\n });\n fs.writeFileSync(\n path.join(modDir, 'package.json'),\n JSON.stringify(dependencyAssembly.packageJson, null, 2),\n 'utf-8',\n );\n\n for (const [fileName, fileContents] of Object.entries(dependencyAssembly.files)) {\n fs.mkdirSync(path.dirname(path.join(modDir, fileName)), {\n recursive: true,\n });\n fs.writeFileSync(path.join(modDir, fileName), fileContents);\n }\n }\n\n public dependencyDir(name: string) {\n if (!this.installed.has(name)) {\n throw new JsiiError(`No dependency with name '${name}' has been installed`);\n }\n return path.join(this.rootDirectory, 'node_modules', name);\n }\n\n public cleanup() {\n fs.rmSync(this.rootDirectory, { force: true, recursive: true });\n }\n}\n\n// Alias for backwards compatibility\nexport type PackageInfo = PackageJson;\n\n/**\n * TSConfig paths can either be relative to the project or absolute.\n * This function normalizes paths to be relative to the provided root.\n * After normalization, code using these paths can be much simpler.\n *\n * @param root the project root\n * @param pathToNormalize the path to normalize, might be empty\n */\nexport function normalizeConfigPath(root: string, pathToNormalize?: string): string | undefined {\n if (pathToNormalize == null || !path.isAbsolute(pathToNormalize)) {\n return pathToNormalize;\n }\n return path.relative(root, pathToNormalize);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../src/helpers.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAwCH,wDASC;AA4DD,gDAsFC;AA2MD,kDAKC;AAjZD,8BAA8B;AAC9B,8BAA8B;AAC9B,kCAAkC;AAClC,qCAA8E;AAE9E,2CAA4D;AAE5D,yCAAuD;AACvD,iDAA8D;AAC9D,mCAAsD;AAUtD;;GAEG;AACU,QAAA,2BAA2B,GAAuB;IAC7D,oBAAoB;IACpB,2BAA2B;IAC3B,gCAAgC;CACjC,CAAC;AAEF;;;;;;;;;GASG;AACH,SAAgB,sBAAsB,CACpC,MAAoC,EACpC,OAA+D;IAE/D,MAAM,MAAM,GAAG,kBAAkB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACnD,IAAI,MAAM,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;IACxC,CAAC;IACD,OAAO,MAAM,CAAC,QAAQ,CAAC;AACzB,CAAC;AAkDD;;;;;;;;;GASG;AACH,SAAgB,kBAAkB,CAChC,MAA+D,EAC/D,OAA0C,EAC1C,eAAgE;IAEhE,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC/B,MAAM,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IAClC,CAAC;IAED,MAAM,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IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,cAAc,EAAE,IAAI,CAAC,CAAC;IAC7D,CAAC;IAEM,OAAO;QACZ,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAClE,CAAC;CACF;AA/ED,sCA+EC;AAKD;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAC,IAAY,EAAE,eAAwB;IACxE,IAAI,eAAe,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,EAAE,CAAC;QACjE,OAAO,eAAe,CAAC;IACzB,CAAC;IACD,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["/**\n * Helper routines for use with the jsii compiler\n *\n * These are mostly used for testing, but all projects that need to exercise\n * the JSII compiler to test something need to share this code, so might as\n * well put it in one reusable place.\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { PackageJson, loadAssemblyFromPath, writeAssembly } from '@jsii/spec';\nimport * as spec from '@jsii/spec';\nimport { Diagnostic, DiagnosticCategory } from 'typescript';\n\nimport { Compiler, CompilerOptions } from './compiler';\nimport { loadProjectInfo, ProjectInfo } from './project-info';\nimport { formatDiagnostic, JsiiError } from './utils';\n\n/**\n * A set of source files for `sourceToAssemblyHelper`, at least containing 'index.ts'\n */\nexport type MultipleSourceFiles = {\n 'index.ts': string;\n [name: string]: string;\n};\n\n/**\n * Assembly features supported by this compiler\n */\nexport const ASSEMBLY_FEATURES_SUPPORTED: spec.JsiiFeature[] = [\n 'intersection-types',\n 'class-covariant-overrides',\n 'interface-member-doc-overrides',\n];\n\n/**\n * Compile a piece of source and return the JSII assembly for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function sourceToAssemblyHelper(\n source: string | MultipleSourceFiles,\n options?: TestCompilationOptions | ((obj: PackageJson) => void),\n): spec.Assembly {\n const result = compileJsiiForTest(source, options);\n if (result.type !== 'success') {\n throw new Error('Compilation failed');\n }\n return result.assembly;\n}\n\nexport type HelperCompilationOut = HelperCompilationResult | HelperCompilationFailure;\n\n/**\n * Successful output of a compilation command (for testing)\n *\n * A better name would have been `HelperCompilationSuccess`, but the name is part of\n * the public API surface, so we keep it like this.\n */\nexport interface HelperCompilationResult {\n readonly type: 'success';\n\n /**\n * The generated assembly\n */\n readonly assembly: spec.Assembly;\n\n /**\n * Generated .js/.d.ts file(s)\n */\n readonly files: Record<string, string>;\n\n /**\n * The packageInfo used\n */\n readonly packageJson: PackageJson;\n\n /**\n * Whether to compress the assembly file\n */\n readonly compressAssembly: boolean;\n\n /**\n * Diagnostics that occurred during compilation\n */\n readonly diagnostics: readonly Diagnostic[];\n}\n\nexport interface HelperCompilationFailure {\n readonly type: 'failure';\n\n /**\n * Diagnostics that occurred during compilation\n *\n * Contains at least one error.\n */\n readonly diagnostics: readonly Diagnostic[];\n}\n\n/**\n * Compile a piece of source and return the assembly and compiled sources for it\n *\n * Only usable for trivial cases and tests.\n *\n * @param source can either be a single `string` (the content of `index.ts`), or\n * a map of fileName to content, which *must* include `index.ts`.\n * @param options accepts a callback for historical reasons but really expects to\n * take an options object.\n */\nexport function compileJsiiForTest<O extends TestCompilationOptions>(\n source: string | { 'index.ts': string; [name: string]: string },\n options?: O | ((obj: PackageJson) => void),\n compilerOptions?: Omit<CompilerOptions, 'projectInfo' | 'watch'>,\n): ResultOrSuccess<O> {\n if (typeof source === 'string') {\n source = { 'index.ts': source };\n }\n\n const inSomeLocation =\n isOptionsObject(options) && options.compilationDirectory ? inOtherDir(options.compilationDirectory) : inTempDir;\n\n // Easiest way to get the source into the compiler is to write it to disk somewhere.\n // I guess we could make an in-memory compiler host but that seems like work...\n return inSomeLocation(() => {\n for (const [fileName, content] of Object.entries(source)) {\n fs.mkdirSync(path.dirname(fileName), { recursive: true });\n fs.writeFileSync(fileName, content, { encoding: 'utf-8' });\n }\n const { projectInfo, packageJson } = makeProjectInfo(\n 'index.ts',\n typeof options === 'function'\n ? options\n : (pi) => {\n Object.assign(pi, options?.packageJson ?? options?.projectInfo ?? {});\n },\n );\n const compiler = new Compiler({\n projectInfo,\n ...compilerOptions,\n });\n const emitResult = compiler.emit();\n\n const errors = emitResult.diagnostics.filter((d) => d.category === DiagnosticCategory.Error);\n\n if (typeof options !== 'object' || !options?.captureDiagnostics) {\n for (const error of errors) {\n console.error(formatDiagnostic(error, projectInfo.projectRoot));\n // logDiagnostic() doesn't work out of the box, so console.error() it is.\n }\n }\n\n if (errors.length > 0 || emitResult.emitSkipped) {\n if (typeof options === 'object' && options?.captureDiagnostics) {\n return {\n type: 'failure',\n diagnostics: emitResult.diagnostics,\n } satisfies HelperCompilationFailure;\n }\n throw new JsiiError('There were compiler errors');\n }\n\n const assembly = loadAssemblyFromPath(process.cwd(), false, ASSEMBLY_FEATURES_SUPPORTED);\n const files: Record<string, string> = {};\n\n for (const filename of Object.keys(source)) {\n let jsFile = filename.replace(/\\.ts$/, '.js');\n let dtsFile = filename.replace(/\\.ts$/, '.d.ts');\n if (projectInfo.tsc?.outDir && filename !== 'README.md') {\n jsFile = path.join(projectInfo.tsc.outDir, jsFile);\n dtsFile = path.join(projectInfo.tsc.outDir, dtsFile);\n }\n\n // eslint-disable-next-line no-await-in-loop\n files[jsFile] = fs.readFileSync(jsFile, { encoding: 'utf-8' });\n // eslint-disable-next-line no-await-in-loop\n files[dtsFile] = fs.readFileSync(dtsFile, { encoding: 'utf-8' });\n\n const warningsFileName = '.warnings.jsii.js';\n if (fs.existsSync(warningsFileName)) {\n // eslint-disable-next-line no-await-in-loop\n files[warningsFileName] = fs.readFileSync(warningsFileName, {\n encoding: 'utf-8',\n });\n }\n }\n\n return {\n type: 'success',\n assembly,\n files,\n packageJson,\n compressAssembly: isOptionsObject(options) && options.compressAssembly ? true : false,\n diagnostics: emitResult.diagnostics,\n } satisfies HelperCompilationResult;\n }) as ResultOrSuccess<O>;\n}\n\ntype ResultOrSuccess<O extends TestCompilationOptions> = O['captureDiagnostics'] extends true\n ? HelperCompilationOut\n : HelperCompilationResult;\n\nfunction inTempDir<T>(block: () => T): T {\n const origDir = process.cwd();\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii'));\n process.chdir(tmpDir);\n const ret = block();\n process.chdir(origDir);\n fs.rmSync(tmpDir, { force: true, recursive: true });\n return ret;\n}\n\nfunction inOtherDir(dir: string) {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\n return <T extends unknown>(block: () => T): T => {\n const origDir = process.cwd();\n process.chdir(dir);\n try {\n return block();\n } finally {\n process.chdir(origDir);\n }\n };\n}\n\n/**\n * Obtain project info so we can call the compiler\n *\n * Creating this directly in-memory leads to slightly different behavior from calling\n * jsii from the command-line, and I don't want to figure out right now.\n *\n * Most consistent behavior seems to be to write a package.json to disk and\n * then calling the same functions as the CLI would.\n */\nfunction makeProjectInfo(\n types: string,\n cb?: (obj: PackageJson) => void,\n): { projectInfo: ProjectInfo; packageJson: PackageJson } {\n const packageJson: PackageJson = {\n types,\n main: types.replace(/(?:\\.d)?\\.ts(x?)/, '.js$1'),\n name: 'testpkg', // That's what package.json would tell if we look up...\n version: '0.0.1',\n license: 'Apache-2.0',\n author: { name: 'John Doe' },\n repository: { type: 'git', url: 'https://github.com/aws/jsii.git' },\n jsii: {},\n };\n\n if (cb) {\n cb(packageJson);\n }\n\n fs.writeFileSync(\n 'package.json',\n JSON.stringify(packageJson, (_: string, v: any) => v, 2),\n 'utf-8',\n );\n\n const { projectInfo } = loadProjectInfo(path.resolve(process.cwd(), '.'));\n return { projectInfo, packageJson };\n}\n\nexport interface TestCompilationOptions {\n /**\n * The directory in which we write and compile the files\n */\n readonly compilationDirectory?: string;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @deprecated Prefer using `packageJson` instead.\n */\n readonly projectInfo?: Partial<PackageJson>;\n\n /**\n * Parts of projectInfo to override (package name etc)\n *\n * @default - Use some default values\n */\n readonly packageJson?: Partial<PackageJson>;\n\n /**\n * Whether to compress the assembly file.\n *\n * @default false\n */\n readonly compressAssembly?: boolean;\n\n /**\n * Whether or not to print the diagnostics\n *\n * @default false\n */\n readonly captureDiagnostics?: boolean;\n}\n\nfunction isOptionsObject(\n x: TestCompilationOptions | ((obj: PackageJson) => void) | undefined,\n): x is TestCompilationOptions {\n return x ? typeof x === 'object' : false;\n}\n\n/**\n * An NPM-ready workspace where we can install test-compile dependencies and compile new assemblies\n */\nexport class TestWorkspace {\n /**\n * Create a new workspace.\n *\n * Creates a temporary directory, don't forget to call cleanUp\n */\n public static create(): TestWorkspace {\n const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'jsii-testworkspace'));\n fs.mkdirSync(tmpDir, { recursive: true });\n return new TestWorkspace(tmpDir);\n }\n\n /**\n * Execute a block with a temporary workspace\n */\n public static withWorkspace<A>(block: (ws: TestWorkspace) => A): A {\n const ws = TestWorkspace.create();\n try {\n return block(ws);\n } finally {\n ws.cleanup();\n }\n }\n\n private readonly installed = new Set<string>();\n\n private constructor(public readonly rootDirectory: string) {}\n\n /**\n * Add a test-compiled jsii assembly as a dependency\n */\n public addDependency(dependencyAssembly: HelperCompilationOut) {\n if (dependencyAssembly.type !== 'success') {\n throw new JsiiError('Cannot add dependency: assembly compilation failed');\n }\n\n if (this.installed.has(dependencyAssembly.assembly.name)) {\n throw new JsiiError(\n `A dependency with name '${dependencyAssembly.assembly.name}' was already installed. Give one a different name.`,\n );\n }\n this.installed.add(dependencyAssembly.assembly.name);\n\n // The following is silly, however: the helper has compiled the given source to\n // an assembly, and output files, and then removed their traces from disk.\n // We need those files back on disk, so write them back out again.\n //\n // We will drop them in 'node_modules/<name>' so they can be imported\n // as if they were installed.\n const modDir = path.join(this.rootDirectory, 'node_modules', dependencyAssembly.assembly.name);\n fs.mkdirSync(modDir, { recursive: true });\n\n writeAssembly(modDir, dependencyAssembly.assembly, {\n compress: dependencyAssembly.compressAssembly,\n });\n fs.writeFileSync(\n path.join(modDir, 'package.json'),\n JSON.stringify(dependencyAssembly.packageJson, null, 2),\n 'utf-8',\n );\n\n for (const [fileName, fileContents] of Object.entries(dependencyAssembly.files)) {\n fs.mkdirSync(path.dirname(path.join(modDir, fileName)), {\n recursive: true,\n });\n fs.writeFileSync(path.join(modDir, fileName), fileContents);\n }\n }\n\n public dependencyDir(name: string) {\n if (!this.installed.has(name)) {\n throw new JsiiError(`No dependency with name '${name}' has been installed`);\n }\n return path.join(this.rootDirectory, 'node_modules', name);\n }\n\n public cleanup() {\n fs.rmSync(this.rootDirectory, { force: true, recursive: true });\n }\n}\n\n// Alias for backwards compatibility\nexport type PackageInfo = PackageJson;\n\n/**\n * TSConfig paths can either be relative to the project or absolute.\n * This function normalizes paths to be relative to the provided root.\n * After normalization, code using these paths can be much simpler.\n *\n * @param root the project root\n * @param pathToNormalize the path to normalize, might be empty\n */\nexport function normalizeConfigPath(root: string, pathToNormalize?: string): string | undefined {\n if (pathToNormalize == null || !path.isAbsolute(pathToNormalize)) {\n return pathToNormalize;\n }\n return path.relative(root, pathToNormalize);\n}\n"]}
|
package/lib/jsii-diagnostic.d.ts
CHANGED
|
@@ -119,7 +119,7 @@ export declare class JsiiDiagnostic implements ts.Diagnostic {
|
|
|
119
119
|
readonly name: string;
|
|
120
120
|
}) => string>;
|
|
121
121
|
static readonly JSII_3003_SYMBOL_IS_EXPORTED_TWICE: Code<(ns1: string, ns2: string) => string>;
|
|
122
|
-
static readonly JSII_3004_INVALID_SUPERTYPE: Code<(clause: ts.HeritageClause, badDeclaration
|
|
122
|
+
static readonly JSII_3004_INVALID_SUPERTYPE: Code<(clause: ts.HeritageClause, badDeclaration?: ts.Declaration) => string>;
|
|
123
123
|
static readonly JSII_3005_TYPE_USED_AS_INTERFACE: Code<(badType: spec.TypeReference) => string>;
|
|
124
124
|
static readonly JSII_3006_TYPE_USED_AS_CLASS: Code<(badType: spec.TypeReference) => string>;
|
|
125
125
|
static readonly JSII_3007_ILLEGAL_STRUCT_EXTENSION: Code<(offender: spec.Type, struct: spec.InterfaceType) => string>;
|
package/lib/jsii-diagnostic.js
CHANGED
|
@@ -419,7 +419,7 @@ JsiiDiagnostic.JSII_3003_SYMBOL_IS_EXPORTED_TWICE = Code.error({
|
|
|
419
419
|
JsiiDiagnostic.JSII_3004_INVALID_SUPERTYPE = Code.error({
|
|
420
420
|
code: 3004,
|
|
421
421
|
formatter: (clause, badDeclaration) => {
|
|
422
|
-
return `Illegal ${clauseType(clause.token)} clause for an exported API: ${ts.SyntaxKind[badDeclaration.kind]}`;
|
|
422
|
+
return `Illegal ${clauseType(clause.token)} clause for an exported API: ${badDeclaration ? ts.SyntaxKind[badDeclaration.kind] : 'unnamed base type'}`;
|
|
423
423
|
function clauseType(token) {
|
|
424
424
|
switch (token) {
|
|
425
425
|
case ts.SyntaxKind.ExtendsKeyword:
|
|
@@ -565,7 +565,7 @@ JsiiDiagnostic.JSII_5014_INHERITED_STATIC_CONFLICT = Code.error({
|
|
|
565
565
|
});
|
|
566
566
|
JsiiDiagnostic.JSII_5015_REDECLARED_INTERFACE_MEMBER = Code.error({
|
|
567
567
|
code: 5015,
|
|
568
|
-
formatter: (memberName, iface) => `Interface "${iface.fqn}" re-declares member "${memberName}".
|
|
568
|
+
formatter: (memberName, iface) => `Interface "${iface.fqn}" re-declares member "${memberName}" with a different type or signature. Re-declared members must match the inherited declaration exactly, as C# interfaces cannot narrow inherited members.`,
|
|
569
569
|
name: 'language-compatibility/redeclared-interface-member',
|
|
570
570
|
});
|
|
571
571
|
JsiiDiagnostic.JSII_5016_PROHIBITED_MEMBER_NAME = Code.error({
|