Socket
Socket
Sign inDemoInstall

ast-kit

Package Overview
Dependencies
2
Maintainers
1
Versions
36
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 0.11.3 to 0.12.0

58

dist/index.d.ts
import * as t from '@babel/types';
import { Node } from '@babel/types';
import { ParseResult as ParseResult$1, ParserOptions } from '@babel/parser';
import { AttachedScope } from '@rollup/pluginutils';
export { AttachedScope } from '@rollup/pluginutils';
type NodeType = t.Node['type'] | 'Function' | 'Literal';
type NodeType = t.Node['type'] | 'Function' | 'Literal' | 'Expression';
type GetNode<K extends NodeType> = K extends 'Function' ? t.Function : K extends 'Literal' ? t.Literal : Extract<t.Node, {

@@ -15,2 +14,3 @@ type: K;

declare function isFunctionType(node: t.Node | undefined | null): node is t.Function;
declare function isExpressionType(node: t.Node | null | undefined): node is t.Expression;
/**

@@ -35,3 +35,3 @@ * Check if the input `node` is a reference to a bound variable.

declare const REGEX_LANG_JSX: RegExp;
declare function getLang(filename: string): any;
declare function getLang(filename: string): string;
declare function isDts(filename: string): boolean;

@@ -56,11 +56,40 @@ declare function isTs(lang?: string): boolean;

declare const attachScopes: <T>(ast: T, propertyName?: string) => AttachedScope;
interface AttachedScope {
parent?: AttachedScope;
isBlockScope: boolean;
declarations: {
[key: string]: boolean;
};
addDeclaration: (node: Node, isBlockDeclaration: boolean, isVar: boolean) => void;
contains: (name: string) => boolean;
}
type WithScope<T> = T & {
scope?: AttachedScope;
};
interface ScopeOptions {
parent?: AttachedScope;
block?: boolean;
params?: Node[];
}
declare class Scope implements AttachedScope {
parent?: AttachedScope;
isBlockScope: boolean;
declarations: {
[key: string]: boolean;
};
constructor(options?: ScopeOptions);
addDeclaration(node: Node, isBlockDeclaration: boolean, isVar: boolean): void;
contains(name: string): boolean;
}
declare function attachScopes(ast: Node, propertyName?: string): Scope;
type LiteralUnion<LiteralType, BaseType extends null | undefined | string | number | boolean | symbol | bigint = string> = LiteralType | (BaseType & Record<never, never>);
declare const TS_NODE_TYPES: readonly ["TSAsExpression", "TSTypeAssertion", "TSNonNullExpression", "TSInstantiationExpression", "TSSatisfiesExpression"];
declare const TS_NODE_TYPES: readonly [
'TSAsExpression',
'TSTypeAssertion',
'TSNonNullExpression',
'TSInstantiationExpression',
'TSSatisfiesExpression'
];
declare function unwrapTSNode(node: t.Node): t.Node;

@@ -83,4 +112,4 @@ declare function escapeKey(rawKey: string): string;

interface WalkSetup {
onEnter<T extends NodeType = NodeType>(type: T | T[] | SetupFilter<GetNode<T>> | WalkCallback<t.Node, void>, cb?: SetupCallback<T, GetNode<T>>): void;
onLeave<T extends NodeType = NodeType>(type: T | T[] | SetupFilter<GetNode<T>> | WalkCallback<t.Node, void>, cb?: SetupCallback<T, GetNode<T>>): void;
onEnter: <T extends NodeType = NodeType>(type: T | T[] | SetupFilter<GetNode<T>> | WalkCallback<t.Node, void>, cb?: SetupCallback<T, GetNode<T>>) => void;
onLeave: <T extends NodeType = NodeType>(type: T | T[] | SetupFilter<GetNode<T>> | WalkCallback<t.Node, void>, cb?: SetupCallback<T, GetNode<T>>) => void;
}

@@ -97,3 +126,12 @@ type SetupFilter<N extends t.Node = t.Node> = (this: WalkThis<t.Node>, node: t.Node, parent: t.Node | null | undefined, key: string | null | undefined, index: number | null | undefined) => node is N;

declare function walkImportDeclaration(imports: Record<string, ImportBinding>, node: t.ImportDeclaration): void;
interface ExportBinding {
local: string;
exported: LiteralUnion<'*' | 'default'>;
isType: boolean;
source: string | null;
specifier: t.ExportSpecifier | t.ExportDefaultSpecifier | t.ExportNamespaceSpecifier | null;
declaration: t.Declaration | t.ExportDefaultDeclaration['declaration'] | null;
}
declare function walkExportDeclaration(exports: Record<string, ExportBinding>, node: t.ExportDeclaration): void;
export { type GetNode, type ImportBinding, type LiteralUnion, type NodeType, type ObjectPropertyLike, type ParseResult, REGEX_DTS, REGEX_LANG_JSX, REGEX_LANG_TS, TS_NODE_TYPES, type WithScope, attachScopes, babelParse, babelParseExpression, createStringLiteral, createTSLiteralType, createTSUnionType, escapeKey, getLang, isCallOf, isDts, isFunctionType, isIdentifierOf, isLiteralType, isReferenced, isTs, isTypeOf, locateTrailingComma, resolveIdentifier, resolveLiteral, resolveObjectKey, resolveString, resolveTemplateLiteral, unwrapTSNode, walkAST, walkASTAsync, walkASTSetup, walkImportDeclaration };
export { type AttachedScope, type ExportBinding, type GetNode, type ImportBinding, type LiteralUnion, type NodeType, type ObjectPropertyLike, type ParseResult, REGEX_DTS, REGEX_LANG_JSX, REGEX_LANG_TS, TS_NODE_TYPES, type WithScope, attachScopes, babelParse, babelParseExpression, createStringLiteral, createTSLiteralType, createTSUnionType, escapeKey, getLang, isCallOf, isDts, isExpressionType, isFunctionType, isIdentifierOf, isLiteralType, isReferenced, isTs, isTypeOf, locateTrailingComma, resolveIdentifier, resolveLiteral, resolveObjectKey, resolveString, resolveTemplateLiteral, unwrapTSNode, walkAST, walkASTAsync, walkASTSetup, walkExportDeclaration, walkImportDeclaration };

@@ -10,2 +10,4 @@ // src/check.ts

return isLiteralType(node);
} else if (type === "Expression") {
return isExpressionType(node);
} else {

@@ -28,2 +30,16 @@ return node.type === type;

}
function isExpressionType(node) {
return !!node && (node.type.endsWith("Expression") || isLiteralType(node) || [
"Identifier",
"MetaProperty",
"Super",
"Import",
"JSXElement",
"JSXFragment",
"TopicReference",
"PipelineBareFunction",
"PipelinePrimaryTopicReference",
"TSTypeAssertion"
].includes(node.type));
}
function isReferenced(node, parent, grandparent) {

@@ -312,41 +328,2 @@ switch (parent.type) {

// src/scope.ts
import {
attachScopes as _attachScopes
} from "@rollup/pluginutils";
var attachScopes = _attachScopes;
// src/utils.ts
import { parseExpression as parseExpression2 } from "@babel/parser";
var TS_NODE_TYPES = [
"TSAsExpression",
// foo as number
"TSTypeAssertion",
// (<number>foo)
"TSNonNullExpression",
// foo!
"TSInstantiationExpression",
// foo<string>
"TSSatisfiesExpression"
// foo satisfies T
];
function unwrapTSNode(node) {
if (isTypeOf(node, TS_NODE_TYPES)) {
return unwrapTSNode(node.expression);
} else {
return node;
}
}
function escapeKey(rawKey) {
if (String(+rawKey) === rawKey)
return rawKey;
try {
const node = parseExpression2(`({${rawKey}: 1})`);
if (node.properties[0].key.type === "Identifier")
return rawKey;
} catch {
}
return JSON.stringify(rawKey);
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js

@@ -671,2 +648,241 @@ var WalkerBase = class {

}
function walkExportDeclaration(exports, node) {
let local;
let exported;
let isType;
let source;
let specifier;
let declaration;
function setExport() {
exports[exported] = {
source,
local,
exported,
specifier,
isType,
declaration
};
}
if (node.type === "ExportNamedDeclaration") {
if (node.specifiers.length > 0) {
for (const s of node.specifiers) {
const isExportSpecifier = s.type === "ExportSpecifier";
isType = node.exportKind === "type" || isExportSpecifier && s.exportKind === "type";
local = isExportSpecifier ? s.local.name : s.type === "ExportNamespaceSpecifier" ? "*" : "default";
source = node.source ? node.source.value : null;
exported = isExportSpecifier ? resolveString(s.exported) : s.exported.name;
declaration = null;
specifier = s;
setExport();
}
} else if (node.specifiers.length === 0 && !!node.declaration) {
if (node.declaration.type === "VariableDeclaration") {
for (const decl of node.declaration.declarations) {
if (decl.id.type !== "Identifier") {
continue;
}
local = resolveString(decl.id);
source = null;
exported = local;
isType = node.exportKind === "type";
declaration = node.declaration;
specifier = null;
setExport();
}
} else if ("id" in node.declaration && node.declaration.id && node.declaration.id.type === "Identifier") {
local = resolveString(node.declaration.id);
source = null;
exported = local;
isType = node.exportKind === "type";
declaration = node.declaration;
specifier = null;
setExport();
} else {
}
}
return;
} else if (node.type === "ExportDefaultDeclaration") {
if (isExpressionType(node.declaration)) {
local = "name" in node.declaration ? node.declaration.name : "default";
} else {
local = resolveString(node.declaration.id || "default");
}
source = null;
exported = "default";
isType = false;
declaration = node.declaration;
specifier = null;
} else {
local = "*";
source = resolveString(node.source);
exported = "*";
isType = node.exportKind === "type";
specifier = null;
declaration = null;
}
setExport();
}
// src/scope.ts
var extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() {
},
ObjectPattern(names, param) {
for (const prop of param.properties) {
if (prop.type === "RestElement") {
extractors.RestElement(names, prop);
} else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
var extractAssignedNames = function extractAssignedNames2(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
var blockDeclarations = {
const: true,
let: true
};
var Scope = class {
parent;
isBlockScope;
declarations;
constructor(options = {}) {
this.parent = options.parent;
this.isBlockScope = !!options.block;
this.declarations = /* @__PURE__ */ Object.create(null);
if (options.params) {
options.params.forEach((param) => {
extractAssignedNames(param).forEach((name) => {
this.declarations[name] = true;
});
});
}
}
addDeclaration(node, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
this.parent.addDeclaration(node, isBlockDeclaration, isVar);
} else if (node.id) {
extractAssignedNames(node.id).forEach((name) => {
this.declarations[name] = true;
});
}
}
contains(name) {
return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
}
};
function attachScopes(ast, propertyName = "scope") {
let scope = new Scope();
walkAST(ast, {
enter(n, parent) {
const node = n;
if (/(Function|Class)Declaration/.test(node.type)) {
scope.addDeclaration(node, false, false);
}
if (node.type === "VariableDeclaration") {
const { kind } = node;
const isBlockDeclaration = blockDeclarations[kind];
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
if (/Function/.test(node.type)) {
const func = node;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
if (func.type === "FunctionExpression" && func.id) {
newScope.addDeclaration(func, false, false);
}
}
if (/For(In|Of)?Statement/.test(node.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
if (node.type === "BlockStatement" && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
if (node.type === "CatchClause") {
newScope = new Scope({
parent: scope,
params: node.param ? [node.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n) {
const node = n;
if (node[propertyName])
scope = scope.parent;
}
});
return scope;
}
// src/utils.ts
import { parseExpression as parseExpression2 } from "@babel/parser";
var TS_NODE_TYPES = [
"TSAsExpression",
// foo as number
"TSTypeAssertion",
// (<number>foo)
"TSNonNullExpression",
// foo!
"TSInstantiationExpression",
// foo<string>
"TSSatisfiesExpression"
// foo satisfies T
];
function unwrapTSNode(node) {
if (isTypeOf(node, TS_NODE_TYPES)) {
return unwrapTSNode(node.expression);
} else {
return node;
}
}
function escapeKey(rawKey) {
if (String(+rawKey) === rawKey)
return rawKey;
try {
const node = parseExpression2(`({${rawKey}: 1})`);
if (node.properties[0].key.type === "Identifier")
return rawKey;
} catch {
}
return JSON.stringify(rawKey);
}
export {

@@ -687,2 +903,3 @@ REGEX_DTS,

isDts,
isExpressionType,
isFunctionType,

@@ -704,3 +921,4 @@ isIdentifierOf,

walkASTSetup,
walkExportDeclaration,
walkImportDeclaration
};

37

package.json
{
"name": "ast-kit",
"version": "0.11.3",
"packageManager": "pnpm@8.11.0",
"description": "AST Toolkit.",
"version": "0.12.0",
"packageManager": "pnpm@8.15.4",
"description": "A toolkit for easy AST generation and manipulation.",
"type": "module",

@@ -33,22 +33,21 @@ "license": "MIT",

"dependencies": {
"@babel/parser": "^7.23.5",
"@rollup/pluginutils": "^5.1.0",
"pathe": "^1.1.1"
"@babel/parser": "^7.23.9",
"pathe": "^1.1.2"
},
"devDependencies": {
"@babel/types": "^7.23.5",
"@sxzz/eslint-config": "^3.7.5",
"@babel/types": "^7.23.9",
"@sxzz/eslint-config": "^3.8.0",
"@sxzz/prettier-config": "^2.0.0",
"@types/node": "^20.10.3",
"@vitest/coverage-v8": "^0.34.6",
"@vitest/ui": "^0.34.7",
"bumpp": "^9.2.0",
"eslint": "^8.55.0",
"@types/node": "^20.11.20",
"@vitest/coverage-v8": "^1.3.1",
"@vitest/ui": "^1.3.1",
"bumpp": "^9.3.0",
"eslint": "^8.57.0",
"estree-walker": "^3.0.3",
"fast-glob": "^3.3.2",
"prettier": "^3.1.0",
"tsup": "^8.0.1",
"tsx": "^4.6.2",
"typescript": "^5.3.2",
"vitest": "^0.34.6"
"prettier": "^3.2.5",
"tsup": "^8.0.2",
"tsx": "^4.7.1",
"typescript": "^5.3.3",
"vitest": "^1.3.1"
},

@@ -64,5 +63,5 @@ "engines": {

"test": "vitest",
"release": "bumpp && pnpm publish",
"release": "bumpp package.json jsr.json && pnpm publish",
"typecheck": "tsc --noEmit"
}
}

@@ -1,9 +0,11 @@

# ast-kit [![npm](https://img.shields.io/npm/v/ast-kit.svg)](https://npmjs.com/package/ast-kit)
# ast-kit [![npm](https://img.shields.io/npm/v/ast-kit.svg)](https://npmjs.com/package/ast-kit) [![jsr](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fjsr-api.sxzz.moe%2Fversion%2F%40sxzz%2Fast-kit&query=version&prefix=v&label=jsr&color=%23faee4a)](https://jsr.io/@sxzz/ast-kit) [![Unit Test](https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml/badge.svg)](https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml) [![codecov](https://codecov.io/gh/sxzz/ast-kit/graph/badge.svg?token=MHTCPNMZAK)](https://codecov.io/gh/sxzz/ast-kit)
[![Unit Test](https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml/badge.svg)](https://github.com/sxzz/ast-kit/actions/workflows/unit-test.yml)
A toolkit for easy AST generation and manipulation.
A Babel AST Toolkit.
[API Reference](https://paka.dev/npm/ast-kit/api)
## Requirements
- Node.js >= 16.14.0
## Install

@@ -15,4 +17,2 @@

Node.js >= 16.14.0 required
## Sponsors

@@ -28,2 +28,2 @@

[MIT](./LICENSE) License © 2023 [三咲智子](https://github.com/sxzz)
[MIT](./LICENSE) License © 2023-PRESENT [三咲智子](https://github.com/sxzz)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

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

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc