Socket
Socket
Sign inDemoInstall

rollup-plugin-dts

Package Overview
Dependencies
Maintainers
1
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rollup-plugin-dts - npm Package Compare versions

Comparing version 0.1.1 to 0.2.0

101

dist/rollup-plugin-dts.cjs.js

@@ -134,5 +134,3 @@ 'use strict';

pushStatement(node) {
if (node) {
this.ast.body.push(node);
}
this.ast.body.push(node);
}

@@ -149,6 +147,6 @@ maybeMarkAsExported(node, id) {

}
removeExportModifier(node) {
removeExportModifier(node, removeDefault = false) {
const ret = [];
for (const mod of node.modifiers || []) {
if (mod.kind === ts.SyntaxKind.ExportKeyword) {
if (mod.kind === ts.SyntaxKind.ExportKeyword || (removeDefault && mod.kind === ts.SyntaxKind.DefaultKeyword)) {
const start = node.getStart();

@@ -165,4 +163,4 @@ const end = mod.end + 1;

}
if (ts.isInterfaceDeclaration(node)) {
return this.convertInterfaceDeclaration(node);
if (ts.isInterfaceDeclaration(node) || ts.isClassDeclaration(node)) {
return this.convertClassOrInterfaceDeclaration(node);
}

@@ -172,7 +170,10 @@ if (ts.isExportDeclaration(node) || ts.isExportAssignment(node)) {

}
// istanbul ignore else
if (ts.isImportDeclaration(node)) {
return this.convertImportDeclaration(node);
}
console.log({ code: node.getFullText() });
throw new Error(`unsupported node type`);
else {
console.log({ code: node.getFullText() });
throw new Error(`unsupported node type`);
}
}

@@ -185,4 +186,5 @@ createDeclaration(id, range) {

convertFunctionDeclaration(node) {
// istanbul ignore if
if (!node.name) {
console.log(node);
console.log({ code: node.getFullText() });
throw new Error(`FunctionDeclaration should have a name`);

@@ -193,2 +195,5 @@ }

body.push(...this.removeExportModifier(node));
this.convertParametersAndType(node, body);
}
convertParametersAndType(node, body) {
for (const param of node.parameters) {

@@ -203,10 +208,3 @@ if (param.type) {

}
convertInterfaceDeclaration(node) {
if (!node.name) {
console.log(node);
throw new Error(`InterfaceDeclaration should have a name`);
}
this.maybeMarkAsExported(node, node.name);
const body = this.createDeclaration(node.name, node);
body.push(...this.removeExportModifier(node));
convertHeritageClauses(node, body) {
for (const heritage of node.heritageClauses || []) {

@@ -217,8 +215,28 @@ for (const type of heritage.types) {

}
}
convertMembers(node, body) {
for (const member of node.members) {
if (ts.isPropertySignature(member) && member.type) {
if ((ts.isPropertyDeclaration(member) || ts.isPropertySignature(member)) && member.type) {
this.convertTypeNode(member.type, body);
}
else if (ts.isMethodDeclaration(member) ||
ts.isMethodSignature(member) ||
ts.isConstructorDeclaration(member) ||
ts.isConstructSignatureDeclaration(member)) {
this.convertParametersAndType(member, body);
}
}
}
convertClassOrInterfaceDeclaration(node) {
// istanbul ignore if
if (!node.name) {
console.log({ code: node.getFullText() });
throw new Error(`ClassDeclaration / InterfaceDeclaration should have a name`);
}
this.maybeMarkAsExported(node, node.name);
const body = this.createDeclaration(node.name, node);
body.push(...this.removeExportModifier(node, ts.isInterfaceDeclaration(node)));
this.convertHeritageClauses(node, body);
this.convertMembers(node, body);
}
convertExportDeclaration(node) {

@@ -249,9 +267,21 @@ if (ts.isExportAssignment(node)) {

convertImportDeclaration(node) {
if (!node.importClause || !node.importClause.namedBindings) {
const source = this.convertExpression(node.moduleSpecifier);
// istanbul ignore if
if (!node.importClause || (!node.importClause.name && !node.importClause.namedBindings)) {
console.log({ code: node.getFullText() });
throw new Error(`ImportDeclaration should have imports`);
}
const specifiers = node.importClause.namedBindings
? this.convertNamedImportBindings(node.importClause.namedBindings)
: [];
if (node.importClause.name) {
specifiers.push({
type: "ImportDefaultSpecifier",
local: createIdentifier(node.importClause.name),
});
}
this.pushStatement(withStartEnd({
type: "ImportDeclaration",
specifiers: this.convertNamedImportBindings(node.importClause.namedBindings),
source: this.convertExpression(node.moduleSpecifier),
specifiers,
source,
}, node));

@@ -308,7 +338,10 @@ }

}
// istanbul ignore else
if (ts.isIdentifier(node)) {
return createIdentifier(node);
}
console.log({ code: node.getFullText() });
throw new Error(`Unknown Expression`);
else {
console.log({ code: node.getFullText() });
throw new Error(`Unknown Expression`);
}
}

@@ -324,2 +357,3 @@ }

const configFileName = ts.findConfigFile(options.tsconfig, ts.sys.fileExists, path.extname(options.tsconfig) ? file : undefined);
// istanbul ignore if
if (!configFileName) {

@@ -334,4 +368,6 @@ throw new Error(`rollup-plugin-dts: Couldn't find tsconfig file`);

const configParseResult = ts.getParsedCommandLineOfConfigFile(configFileName, compilerOptions, Object.assign({}, ts.sys, { onUnRecoverableConfigFileDiagnostic(d) {
// istanbul ignore next
diagnostic = d;
} }));
// istanbul ignore if
if (!configParseResult) {

@@ -358,12 +394,12 @@ console.log(diagnostic);

return {
get compiler() {
return lazyCreate().compiler;
},
resolve(importee, importer) {
const { parsedCompilerOptions } = lazyCreate();
const result = ts.nodeModuleNameResolver(importee, importer, parsedCompilerOptions, ts.sys);
// istanbul ignore else
if (result.resolvedModule && result.resolvedModule.resolvedFileName) {
return result.resolvedModule.resolvedFileName;
}
return null;
else {
return null;
}
},

@@ -382,5 +418,5 @@ transform(fileName) {

}
if (fileName === `${baseFileName}.d.ts.map`) {
map = data;
}
// if (fileName === `${baseFileName}.d.ts.map`) {
// map = data;
// }
});

@@ -395,3 +431,3 @@ const dtsSource = ts.createSourceFile(dtsFilename, code, ts.ScriptTarget.Latest, true);

// Well luckily both words have the same length, haha :-D
code = code.replace(/(export\s+)default(\s+function)/m, "$1declare$2");
code = code.replace(/(export\s+)default(\s+(function|class))/m, "$1declare$2");
return { code, ast, map };

@@ -419,2 +455,3 @@ },

async transform(_code, id) {
// istanbul ignore if
if (!filter(id)) {

@@ -421,0 +458,0 @@ return;

import { createFilter } from 'rollup-pluginutils';
import { findConfigFile, sys, getParsedCommandLineOfConfigFile, createProgram, nodeModuleNameResolver, createSourceFile, ScriptTarget, ModifierFlags, SyntaxKind, isFunctionDeclaration, isInterfaceDeclaration, isExportDeclaration, isExportAssignment, isImportDeclaration, isPropertySignature, isNamedImports, isTypeReferenceNode, isIdentifier, isLiteralExpression, getCombinedModifierFlags } from 'typescript';
import { findConfigFile, sys, getParsedCommandLineOfConfigFile, createProgram, nodeModuleNameResolver, createSourceFile, ScriptTarget, ModifierFlags, SyntaxKind, isFunctionDeclaration, isInterfaceDeclaration, isClassDeclaration, isExportDeclaration, isExportAssignment, isImportDeclaration, isPropertyDeclaration, isPropertySignature, isMethodDeclaration, isMethodSignature, isConstructorDeclaration, isConstructSignatureDeclaration, isNamedImports, isTypeReferenceNode, isIdentifier, isLiteralExpression, getCombinedModifierFlags } from 'typescript';
import path from 'path';

@@ -130,5 +130,3 @@

pushStatement(node) {
if (node) {
this.ast.body.push(node);
}
this.ast.body.push(node);
}

@@ -145,6 +143,6 @@ maybeMarkAsExported(node, id) {

}
removeExportModifier(node) {
removeExportModifier(node, removeDefault = false) {
const ret = [];
for (const mod of node.modifiers || []) {
if (mod.kind === SyntaxKind.ExportKeyword) {
if (mod.kind === SyntaxKind.ExportKeyword || (removeDefault && mod.kind === SyntaxKind.DefaultKeyword)) {
const start = node.getStart();

@@ -161,4 +159,4 @@ const end = mod.end + 1;

}
if (isInterfaceDeclaration(node)) {
return this.convertInterfaceDeclaration(node);
if (isInterfaceDeclaration(node) || isClassDeclaration(node)) {
return this.convertClassOrInterfaceDeclaration(node);
}

@@ -168,7 +166,10 @@ if (isExportDeclaration(node) || isExportAssignment(node)) {

}
// istanbul ignore else
if (isImportDeclaration(node)) {
return this.convertImportDeclaration(node);
}
console.log({ code: node.getFullText() });
throw new Error(`unsupported node type`);
else {
console.log({ code: node.getFullText() });
throw new Error(`unsupported node type`);
}
}

@@ -181,4 +182,5 @@ createDeclaration(id, range) {

convertFunctionDeclaration(node) {
// istanbul ignore if
if (!node.name) {
console.log(node);
console.log({ code: node.getFullText() });
throw new Error(`FunctionDeclaration should have a name`);

@@ -189,2 +191,5 @@ }

body.push(...this.removeExportModifier(node));
this.convertParametersAndType(node, body);
}
convertParametersAndType(node, body) {
for (const param of node.parameters) {

@@ -199,10 +204,3 @@ if (param.type) {

}
convertInterfaceDeclaration(node) {
if (!node.name) {
console.log(node);
throw new Error(`InterfaceDeclaration should have a name`);
}
this.maybeMarkAsExported(node, node.name);
const body = this.createDeclaration(node.name, node);
body.push(...this.removeExportModifier(node));
convertHeritageClauses(node, body) {
for (const heritage of node.heritageClauses || []) {

@@ -213,8 +211,28 @@ for (const type of heritage.types) {

}
}
convertMembers(node, body) {
for (const member of node.members) {
if (isPropertySignature(member) && member.type) {
if ((isPropertyDeclaration(member) || isPropertySignature(member)) && member.type) {
this.convertTypeNode(member.type, body);
}
else if (isMethodDeclaration(member) ||
isMethodSignature(member) ||
isConstructorDeclaration(member) ||
isConstructSignatureDeclaration(member)) {
this.convertParametersAndType(member, body);
}
}
}
convertClassOrInterfaceDeclaration(node) {
// istanbul ignore if
if (!node.name) {
console.log({ code: node.getFullText() });
throw new Error(`ClassDeclaration / InterfaceDeclaration should have a name`);
}
this.maybeMarkAsExported(node, node.name);
const body = this.createDeclaration(node.name, node);
body.push(...this.removeExportModifier(node, isInterfaceDeclaration(node)));
this.convertHeritageClauses(node, body);
this.convertMembers(node, body);
}
convertExportDeclaration(node) {

@@ -245,9 +263,21 @@ if (isExportAssignment(node)) {

convertImportDeclaration(node) {
if (!node.importClause || !node.importClause.namedBindings) {
const source = this.convertExpression(node.moduleSpecifier);
// istanbul ignore if
if (!node.importClause || (!node.importClause.name && !node.importClause.namedBindings)) {
console.log({ code: node.getFullText() });
throw new Error(`ImportDeclaration should have imports`);
}
const specifiers = node.importClause.namedBindings
? this.convertNamedImportBindings(node.importClause.namedBindings)
: [];
if (node.importClause.name) {
specifiers.push({
type: "ImportDefaultSpecifier",
local: createIdentifier(node.importClause.name),
});
}
this.pushStatement(withStartEnd({
type: "ImportDeclaration",
specifiers: this.convertNamedImportBindings(node.importClause.namedBindings),
source: this.convertExpression(node.moduleSpecifier),
specifiers,
source,
}, node));

@@ -304,7 +334,10 @@ }

}
// istanbul ignore else
if (isIdentifier(node)) {
return createIdentifier(node);
}
console.log({ code: node.getFullText() });
throw new Error(`Unknown Expression`);
else {
console.log({ code: node.getFullText() });
throw new Error(`Unknown Expression`);
}
}

@@ -320,2 +353,3 @@ }

const configFileName = findConfigFile(options.tsconfig, sys.fileExists, path.extname(options.tsconfig) ? file : undefined);
// istanbul ignore if
if (!configFileName) {

@@ -330,4 +364,6 @@ throw new Error(`rollup-plugin-dts: Couldn't find tsconfig file`);

const configParseResult = getParsedCommandLineOfConfigFile(configFileName, compilerOptions, Object.assign({}, sys, { onUnRecoverableConfigFileDiagnostic(d) {
// istanbul ignore next
diagnostic = d;
} }));
// istanbul ignore if
if (!configParseResult) {

@@ -354,12 +390,12 @@ console.log(diagnostic);

return {
get compiler() {
return lazyCreate().compiler;
},
resolve(importee, importer) {
const { parsedCompilerOptions } = lazyCreate();
const result = nodeModuleNameResolver(importee, importer, parsedCompilerOptions, sys);
// istanbul ignore else
if (result.resolvedModule && result.resolvedModule.resolvedFileName) {
return result.resolvedModule.resolvedFileName;
}
return null;
else {
return null;
}
},

@@ -378,5 +414,5 @@ transform(fileName) {

}
if (fileName === `${baseFileName}.d.ts.map`) {
map = data;
}
// if (fileName === `${baseFileName}.d.ts.map`) {
// map = data;
// }
});

@@ -391,3 +427,3 @@ const dtsSource = createSourceFile(dtsFilename, code, ScriptTarget.Latest, true);

// Well luckily both words have the same length, haha :-D
code = code.replace(/(export\s+)default(\s+function)/m, "$1declare$2");
code = code.replace(/(export\s+)default(\s+(function|class))/m, "$1declare$2");
return { code, ast, map };

@@ -415,2 +451,3 @@ },

async transform(_code, id) {
// istanbul ignore if
if (!filter(id)) {

@@ -417,0 +454,0 @@ return;

{
"name": "rollup-plugin-dts",
"version": "0.1.1",
"version": "0.2.0",
"description": "An experiment to generate .d.ts rollup files",

@@ -29,4 +29,4 @@ "keywords": [

"scripts": {
"build": "rollup -c",
"prepublishOnly": "rimraf dist && npm run test && npm run build",
"build": "rimraf dist && rollup -c",
"prepublishOnly": "npm run test && npm run build",
"test": "jest --runInBand"

@@ -33,0 +33,0 @@ },

# rollup-plugin-dts
[![Build Status](https://img.shields.io/travis/Swatinem/rollup-plugin-dts.svg)](https://travis-ci.org/Swatinem/rollup-plugin-dts)
[![Coverage Status](https://img.shields.io/codecov/c/github/Swatinem/rollup-plugin-dts.svg)](https://codecov.io/gh/Swatinem/rollup-plugin-dts)
This is an **EXPERIMENT** to generate roll-upd `.d.ts` definition files from

@@ -39,20 +42,118 @@ your `.ts` files.

We can use this knowledge to specifically direct rollup to _keep_, _change_ and
_remove_ parts of our input file.
We can use this knowledge to specifically direct rollup to _keep_ and
_remove_ parts of our input file, and to rename the correct Identifiers.
What we do, is to transform the Typescript code into a _virtual AST_, that is in
itself just really strange code, but it makes rollup do what we would like it
to do.
### Marking code for removal
For things on the top-level that we want removed from our source, we generate
an `IfStatement` that is always false. Rollup will figure this out and just
remove that statement altogether.
```
if (false) {}
```
[See it live](https://rollupjs.org/repl?version=0.67.1&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMmlmJTIwKGZhbHNlKSUyMCU3QiU3RCUyMiU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJlc20lMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCU3RCUyQyUyMmV4YW1wbGUlMjIlM0FudWxsJTdE)
The trick here is to annotate this `IfStatement` with a certain `start` and `end`.
Rollup will then just remove all the bytes between `start` and `end`, without
even looking into what those bytes actually are.
**TODO**: actually, it should be easier to just generate any identifier without
a side-effect, like I do for nested code.
### Creating declarations
For each export (`class`, `function`, `interface` or `type`), we will create
a bogus `FunctionDeclaration` for rollup. Again, we annotate the
`FunctionDeclaration` with a set of `start` and `end` markers, so that rollup
will remove the correct parts of our code if it figures out the declaration is
not referenced.
```
function foo() {}
export function bar() {}
```
[See it live](https://rollupjs.org/repl?version=0.67.1&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMmZ1bmN0aW9uJTIwZm9vKCklMjAlN0IlN0QlNUNuZXhwb3J0JTIwZnVuY3Rpb24lMjBiYXIoKSUyMCU3QiU3RCUyMiU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJlc20lMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCU3RCUyQyUyMmV4YW1wbGUlMjIlM0FudWxsJTdE)
### Creating side-effects
Rollup will actually analyze functions for side-effects and happily remove
functions which are side-effect free, even though they are referenced in other
parts of your code.
In order for rollup to at least consider putting a function into our bundle,
we have to introduce a side-effect into the function. How do we do that?
The answer is to generate code that rollup can not see inside. For example
by calling an unreferenced identifier. That identifier could potentially live
in `window` and rollup does not know that. So it does not touch that code.
```
_()
```
[See it live](https://rollupjs.org/repl?version=0.67.1&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMl8oKSUyMiU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJlc20lMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCU3RCUyQyUyMmV4YW1wbGUlMjIlM0FudWxsJTdE)
### Creating references
If someone has looked very carefully at the previous example, you will see
that rollup actually inserts a semicolon after the `CallExpression`.
This one took me a long time to figure out and work around.
In the end I decided to create references between different declarations
as function argument defaults. That way rollup will not insert semicolons that
would otherwise mess with out TypeScript code.
Again, all the `Identifier`s are annotated with correct `start` and `end`
markers. So if rollup decides to rename them, it will touch the correct parts
of the code. Also, the function name itself is part of the identifier list,
because there might be identifiers _before_ the function name, such as type
parameters and maybe things we would want to remove.
```
function foo(_0 = foo) {}
function bar(_0 = bar, _1 = foo) {}
function baz(_0 = baz) {}
export function foobar(_0 = foobar, _1 = bar, _2 = baz) {}
```
[See it live](https://rollupjs.org/repl?version=0.67.1&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMmZ1bmN0aW9uJTIwZm9vKF8wJTIwJTNEJTIwZm9vKSUyMCU3QiU3RCU1Q25mdW5jdGlvbiUyMGJhcihfMCUyMCUzRCUyMGJhciUyQyUyMF8xJTIwJTNEJTIwZm9vKSUyMCU3QiU3RCU1Q25mdW5jdGlvbiUyMGJheihfMCUyMCUzRCUyMGJheiklMjAlN0IlN0QlNUNuZXhwb3J0JTIwZnVuY3Rpb24lMjBmb29iYXIoXzAlMjAlM0QlMjBmb29iYXIlMkMlMjBfMSUyMCUzRCUyMGJhciUyQyUyMF8yJTIwJTNEJTIwYmF6KSUyMCU3QiU3RCUyMiU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJlc20lMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCU3RCUyQyUyMmV4YW1wbGUlMjIlM0FudWxsJTdE)
### Removing nested code
Building on the previous example, we can use the list of function argument
defaults to, and the thing we learned before about removing top-level code to
mark nested code for deletion.
For this case, we create an arrow function with some dead code inside. As you
will see in the example, rollup will remove that code. Again, annotating it with
`start` and `end` markers and you are done.
```
function foo(_0 = foo, _1 = () => {removeme}) {}
export function bar(_0 = bar, _1 = foo) {}
```
[See it live](https://rollupjs.org/repl?version=0.67.1&shareable=JTdCJTIybW9kdWxlcyUyMiUzQSU1QiU3QiUyMm5hbWUlMjIlM0ElMjJtYWluLmpzJTIyJTJDJTIyY29kZSUyMiUzQSUyMmZ1bmN0aW9uJTIwZm9vKF8wJTIwJTNEJTIwZm9vJTJDJTIwXzElMjAlM0QlMjAoKSUyMCUzRCUzRSUyMCU3QnJlbW92ZW1lJTdEKSUyMCU3QiU3RCU1Q25leHBvcnQlMjBmdW5jdGlvbiUyMGJhcihfMCUyMCUzRCUyMGJhciUyQyUyMF8xJTIwJTNEJTIwZm9vKSUyMCU3QiU3RCUyMiU3RCU1RCUyQyUyMm9wdGlvbnMlMjIlM0ElN0IlMjJmb3JtYXQlMjIlM0ElMjJlc20lMjIlMkMlMjJuYW1lJTIyJTNBJTIybXlCdW5kbGUlMjIlMkMlMjJhbWQlMjIlM0ElN0IlMjJpZCUyMiUzQSUyMiUyMiU3RCU3RCUyQyUyMmV4YW1wbGUlMjIlM0FudWxsJTdE)
With that, we have all the tools to create roll-upd `.d.ts` files.
# TODO
- explain how I abuse rollup to do what I want :-D
## Things to test:
- `export default`
- function arguments
- function return values
- make sure overrides work correctly
- make sure tsdoc and other type of comments work correctly
- [ ] function arguments
- [ ] function return values
- [ ] make sure overrides work correctly
- [ ] make sure tsdoc and other type of comments work correctly
## Things to implement:
- classes
- maybe removing things from the bundle marked with `@internal` or `@hidden`
- [ ] export type aliases and things like mapped types and conditional types
- [ ] type parameters with correct shadowing
- [ ] maybe removing things from the bundle marked with `@internal` or `@hidden`
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc