New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@vue-macros/api

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@vue-macros/api - npm Package Compare versions

Comparing version 0.9.7 to 0.10.0

dist/index.cjs

107

dist/index.d.ts

@@ -5,5 +5,4 @@ import { MagicStringAST, SFC } from '@vue-macros/common';

import { TypeScript, Declaration, Statement, TSModuleBlock, TSType, TSParenthesizedType, TSTypeAliasDeclaration, Node, Identifier, TSCallSignatureDeclaration, TSFunctionType, TSConstructSignatureDeclaration, TSMethodSignature, TSPropertySignature, TSMappedType, TSInterfaceDeclaration, TSInterfaceBody, TSTypeLiteral, TSIntersectionType, TemplateLiteral, StringLiteral, TSLiteralType, NumericLiteral, BooleanLiteral, BigIntLiteral, TSTypeElement, TSIndexedAccessType, TSUnionType, TSTypeOperator, CallExpression, LVal, VariableDeclaration, ExpressionStatement, TSTypeReference, ObjectMethod, ObjectProperty, Expression } from '@babel/types';
import * as vite from 'vite';
import { ModuleNode } from 'vite';
import { PluginContext } from 'rollup';
import { Plugin } from 'vite';

@@ -91,7 +90,7 @@ type TSDeclaration = TypeScript & Declaration;

type ResolveTSFileIdImpl = (id: string, importer: string) => Promise<string | undefined> | string | undefined;
declare function resolveTSFileId(id: string, importer: string): string | Promise<string | undefined> | undefined;
declare const resolveTSFileId: ResolveTSFileIdImpl;
/**
* @limitation don't node_modules and JavaScript file
*/
declare function resolveTSFileIdNode(id: string, importer: string): string | undefined;
declare const resolveTSFileIdNode: ResolveTSFileIdImpl;
declare function setResolveTSFileIdImpl(impl: ResolveTSFileIdImpl): void;

@@ -139,2 +138,51 @@

declare function handleTSEmitsDefinition({ s, file, offset, defineEmitsAst, typeDeclRaw, declId, statement, }: {
s: MagicStringAST;
file: TSFile;
sfc: SFC;
offset: number;
defineEmitsAst: CallExpression;
typeDeclRaw: TSType;
statement: DefineEmitsStatement;
declId?: LVal;
}): Promise<TSEmits>;
type Emits = TSEmits | undefined;
type DefineEmitsStatement = VariableDeclaration | ExpressionStatement;
interface EmitsBase {
declId?: LVal;
statementAst: DefineEmitsStatement;
defineEmitsAst: CallExpression;
}
interface TSEmits extends EmitsBase {
kind: DefinitionKind.TS;
definitions: Record<string, ASTDefinition<TSCallSignatureDeclaration | TSFunctionType | TSPropertySignature | TSMappedType>[]>;
definitionsAst: ASTDefinition<TSTypeLiteral | TSIntersectionType | TSInterfaceDeclaration | TSFunctionType>;
/**
* Adds a new emit to the definitions. `definitions` will updated after this call.
*
* Added definition cannot be set and removed again.
*
* @example add('change', '(evt: "change", value: string): void')
*/
addEmit: (name: string | StringLiteral, signature: string) => void;
/**
* Modify a definition of a emit. `definitions` will updated after this call.
*
* @limitation Cannot set the emit added by `addEmit`.
*
* @example setEmit('foo', 0, '(evt: "change", value: string): void')
*
* @returns false if the definition does not exist.
*/
setEmit: (name: string | StringLiteral, index: number, signature: string) => boolean;
/**
* Removes specified emit from TS interface. `definitions` will updated after this call.
*
* @limitation Cannot remove emit added by `addEmit`. (it will be removed in definitions though)
*
* @returns `true` if emit was removed, `false` if emit was not found.
*/
removeEmit: (name: string | StringLiteral, index: number) => boolean;
}
declare function handleTSPropsDefinition({ s, file, offset, definePropsAst, typeDeclRaw, withDefaultsAst, defaultsDeclRaw, statement, declId, }: {

@@ -227,51 +275,2 @@ s: MagicStringAST;

declare function handleTSEmitsDefinition({ s, file, offset, defineEmitsAst, typeDeclRaw, declId, statement, }: {
s: MagicStringAST;
file: TSFile;
sfc: SFC;
offset: number;
defineEmitsAst: CallExpression;
typeDeclRaw: TSType;
statement: DefineEmitsStatement;
declId?: LVal;
}): Promise<TSEmits>;
type Emits = TSEmits | undefined;
type DefineEmitsStatement = VariableDeclaration | ExpressionStatement;
interface EmitsBase {
declId?: LVal;
statementAst: DefineEmitsStatement;
defineEmitsAst: CallExpression;
}
interface TSEmits extends EmitsBase {
kind: DefinitionKind.TS;
definitions: Record<string, ASTDefinition<TSCallSignatureDeclaration | TSFunctionType | TSPropertySignature | TSMappedType>[]>;
definitionsAst: ASTDefinition<TSTypeLiteral | TSIntersectionType | TSInterfaceDeclaration | TSFunctionType>;
/**
* Adds a new emit to the definitions. `definitions` will updated after this call.
*
* Added definition cannot be set and removed again.
*
* @example add('change', '(evt: "change", value: string): void')
*/
addEmit: (name: string | StringLiteral, signature: string) => void;
/**
* Modify a definition of a emit. `definitions` will updated after this call.
*
* @limitation Cannot set the emit added by `addEmit`.
*
* @example setEmit('foo', 0, '(evt: "change", value: string): void')
*
* @returns false if the definition does not exist.
*/
setEmit: (name: string | StringLiteral, index: number, signature: string) => boolean;
/**
* Removes specified emit from TS interface. `definitions` will updated after this call.
*
* @limitation Cannot remove emit added by `addEmit`. (it will be removed in definitions though)
*
* @returns `true` if emit was removed, `false` if emit was not found.
*/
removeEmit: (name: string | StringLiteral, index: number) => boolean;
}
interface AnalyzeResult {

@@ -291,5 +290,5 @@ props: Props;

resolve: (ctx: PluginContext) => ResolveTSFileIdImpl;
handleHotUpdate: (this: void, ctx: vite.HmrContext) => void | ModuleNode[] | Promise<void | ModuleNode[]>;
handleHotUpdate: NonNullable<Plugin["handleHotUpdate"]>;
};
export { type ASTDefinition, type AnalyzeResult, type DefaultsASTRaw, type DefineEmitsStatement, type DefinePropsStatement, DefinitionKind, type Emits, type EmitsBase, type Props, type PropsBase, type ResolveTSFileIdImpl, RollupResolve, type RuntimePropDefinition, type TSDeclaration, type TSEmits, type TSFile, type TSModule, type TSNamespace, type TSProperties, type TSProps, type TSPropsMethod, type TSPropsProperty, type TSResolvedType, type TSScope, type TSScopeBase, UNKNOWN_TYPE, analyzeSFC, attachNodeLoc, checkForTSProperties, deepImportRE, genRuntimePropDefinition, getTSFile, getTSPropertiesKeys, handleTSEmitsDefinition, handleTSPropsDefinition, inferRuntimeType, isSupportedForTSReferencedType, isTSDeclaration, isTSNamespace, mergeTSProperties, namespaceSymbol, resolveMaybeTSUnion, resolveTSFileId, resolveTSFileIdNode, resolveTSIndexedAccessType, resolveTSLiteralType, resolveTSNamespace, resolveTSProperties, resolveTSReferencedType, resolveTSScope, resolveTSTemplateLiteral, resolveTSTypeOperator, resolveTypeElements, setResolveTSFileIdImpl, tsFileCache };

@@ -1,92 +0,62 @@

"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
DefinitionKind: () => DefinitionKind,
RollupResolve: () => RollupResolve,
UNKNOWN_TYPE: () => UNKNOWN_TYPE,
analyzeSFC: () => analyzeSFC,
attachNodeLoc: () => attachNodeLoc,
checkForTSProperties: () => checkForTSProperties,
deepImportRE: () => deepImportRE,
genRuntimePropDefinition: () => genRuntimePropDefinition,
getTSFile: () => getTSFile,
getTSPropertiesKeys: () => getTSPropertiesKeys,
handleTSEmitsDefinition: () => handleTSEmitsDefinition,
handleTSPropsDefinition: () => handleTSPropsDefinition,
inferRuntimeType: () => inferRuntimeType,
isSupportedForTSReferencedType: () => isSupportedForTSReferencedType,
isTSDeclaration: () => isTSDeclaration,
isTSNamespace: () => isTSNamespace,
mergeTSProperties: () => mergeTSProperties,
namespaceSymbol: () => namespaceSymbol,
parseSFC: () => import_common8.parseSFC,
resolveMaybeTSUnion: () => resolveMaybeTSUnion,
resolveTSFileId: () => resolveTSFileId,
resolveTSFileIdNode: () => resolveTSFileIdNode,
resolveTSIndexedAccessType: () => resolveTSIndexedAccessType,
resolveTSLiteralType: () => resolveTSLiteralType,
resolveTSNamespace: () => resolveTSNamespace,
resolveTSProperties: () => resolveTSProperties,
resolveTSReferencedType: () => resolveTSReferencedType,
resolveTSScope: () => resolveTSScope,
resolveTSTemplateLiteral: () => resolveTSTemplateLiteral,
resolveTSTypeOperator: () => resolveTSTypeOperator,
resolveTypeElements: () => resolveTypeElements,
setResolveTSFileIdImpl: () => setResolveTSFileIdImpl,
tsFileCache: () => tsFileCache
});
module.exports = __toCommonJS(src_exports);
__reExport(src_exports, require("@vue-macros/common"), module.exports);
export * from "@vue-macros/common";
// src/vue/analyze.ts
var import_common7 = require("@vue-macros/common");
import {
babelParse as babelParse4,
DEFINE_EMITS,
DEFINE_PROPS,
isCallOf,
WITH_DEFAULTS
} from "@vue-macros/common";
// src/vue/props.ts
var import_common5 = require("@vue-macros/common");
// src/vue/emits.ts
import {
babelParse as babelParse2,
isStaticExpression,
resolveLiteral as resolveLiteral3,
resolveString
} from "@vue-macros/common";
// src/ts/is.ts
var import_types = require("@babel/types");
import { isDeclaration } from "@babel/types";
function isTSDeclaration(node) {
return (0, import_types.isDeclaration)(node) && node.type.startsWith("TS");
return isDeclaration(node) && node.type.startsWith("TS");
}
// src/ts/resolve-file.ts
import { existsSync } from "node:fs";
import path from "node:path";
var resolveTSFileId = (id, importer) => {
return resolveTSFileIdImpl(id, importer);
};
var resolveTSFileIdNode = (id, importer) => {
function tryResolve(id2, importer2) {
const filePath = path.resolve(importer2, "..", id2);
if (!existsSync(filePath)) return;
return filePath;
}
return tryResolve(id, importer) || tryResolve(`${id}.ts`, importer) || tryResolve(`${id}.d.ts`, importer) || tryResolve(`${id}/index`, importer) || tryResolve(`${id}/index.ts`, importer) || tryResolve(`${id}/index.d.ts`, importer);
};
var resolveTSFileIdImpl = resolveTSFileIdNode;
function setResolveTSFileIdImpl(impl) {
resolveTSFileIdImpl = impl;
}
// src/ts/resolve-reference.ts
var import_common4 = require("@vue-macros/common");
var import_types2 = require("@babel/types");
import {
isTSType
} from "@babel/types";
import { resolveIdentifier } from "@vue-macros/common";
// src/ts/resolve.ts
var import_common2 = require("@vue-macros/common");
import {
createStringLiteral,
createTSUnionType,
resolveLiteral as resolveLiteral2,
resolveObjectKey
} from "@vue-macros/common";
// src/ts/property.ts
var import_common = require("@vue-macros/common");
import { resolveLiteral } from "@vue-macros/common";
function mergeTSProperties(a, b) {

@@ -151,4 +121,3 @@ return {

});
if (!filterValidExtends(resolved))
continue;
if (!filterValidExtends(resolved)) continue;
properties = mergeTSProperties(

@@ -168,4 +137,3 @@ properties,

};
if (!type.typeParameter.constraint)
return properties;
if (!type.typeParameter.constraint) return properties;
const constraint = await resolveTSReferencedType({

@@ -175,8 +143,6 @@ type: type.typeParameter.constraint,

});
if (!constraint || isTSNamespace(constraint))
return properties;
if (!constraint || isTSNamespace(constraint)) return properties;
const types = resolveMaybeTSUnion(constraint.type);
for (const subType of types) {
if (subType.type !== "TSLiteralType")
continue;
if (subType.type !== "TSLiteralType") continue;
const literal = await resolveTSLiteralType({

@@ -186,6 +152,5 @@ type: subType,

});
if (!literal)
continue;
if (!literal) continue;
const keys = resolveMaybeTSUnion(literal).map(
(literal2) => String((0, import_common.resolveLiteral)(literal2))
(literal2) => String(resolveLiteral(literal2))
);

@@ -233,3 +198,3 @@ for (const key of keys) {

const types = (await resolveKeys("", type.quasis, type.expressions)).map(
(k) => (0, import_common2.createStringLiteral)(k)
(k) => createStringLiteral(k)
);

@@ -246,4 +211,3 @@ return types;

for (const type2 of subTypes) {
if (!isSupportedForTSReferencedType(type2))
continue;
if (!isSupportedForTSReferencedType(type2)) continue;
const resolved = await resolveTSReferencedType({

@@ -253,13 +217,10 @@ type: type2,

});
if (!resolved || isTSNamespace(resolved))
continue;
if (!resolved || isTSNamespace(resolved)) continue;
const types2 = resolveMaybeTSUnion(resolved.type);
for (const type3 of types2) {
if (type3.type !== "TSLiteralType")
continue;
if (type3.type !== "TSLiteralType") continue;
const literal = await resolveTSLiteralType({ type: type3, scope });
if (!literal)
continue;
if (!literal) continue;
const subKeys = resolveMaybeTSUnion(literal).map(
(literal2) => String((0, import_common2.resolveLiteral)(literal2))
(literal2) => String(resolveLiteral2(literal2))
);

@@ -279,4 +240,3 @@ for (const key of subKeys) {

}) {
if (type.literal.type === "UnaryExpression")
return;
if (type.literal.type === "UnaryExpression") return;
if (type.literal.type === "TemplateLiteral") {

@@ -297,3 +257,3 @@ const types = await resolveTSTemplateLiteral({ type: type.literal, scope });

try {
return (0, import_common2.resolveObjectKey)(element);
return resolveObjectKey(element);
} catch {

@@ -312,8 +272,5 @@ }

const key = tryGetKey(element);
if (!key)
continue;
if (properties.properties[key])
continue;
if (!properties.methods[key])
properties.methods[key] = [];
if (!key) continue;
if (properties.properties[key]) continue;
if (!properties.methods[key]) properties.methods[key] = [];
if (element.typeAnnotation) {

@@ -326,4 +283,3 @@ properties.methods[key].push({ scope, type: element });

const key = tryGetKey(element);
if (!key)
continue;
if (!key) continue;
if (!properties.properties[key] && !properties.methods[key]) {

@@ -350,4 +306,3 @@ const type = element.typeAnnotation?.typeAnnotation;

);
if (!object || isTSNamespace(object))
return void 0;
if (!object || isTSNamespace(object)) return void 0;
const objectType = object.type;

@@ -367,3 +322,3 @@ if (type.indexType.type === "TSNumberKeyword") {

}
return { type: (0, import_common2.createTSUnionType)(types), scope };
return { type: createTSUnionType(types), scope };
} else if (objectType.type !== "TSInterfaceDeclaration" && objectType.type !== "TSTypeLiteral" && objectType.type !== "TSIntersectionType" && objectType.type !== "TSMappedType" && objectType.type !== "TSFunctionType")

@@ -385,6 +340,5 @@ return void 0;

});
if (!literal)
continue;
if (!literal) continue;
keys = resolveMaybeTSUnion(literal).map(
(literal2) => String((0, import_common2.resolveLiteral)(literal2))
(literal2) => String(resolveLiteral2(literal2))
);

@@ -396,9 +350,7 @@ } else if (index.type === "TSTypeOperator") {

});
if (!keysStrings)
continue;
if (!keysStrings) continue;
keys = resolveMaybeTSUnion(keysStrings).map(
(literal) => String((0, import_common2.resolveLiteral)(literal))
(literal) => String(resolveLiteral2(literal))
);
} else
continue;
} else continue;
for (const key of keys) {

@@ -409,4 +361,3 @@ const property = properties.properties[key];

const propertyType = properties.properties[key].value;
if (propertyType)
indexes.push(propertyType.type);
if (propertyType) indexes.push(propertyType.type);
}

@@ -427,11 +378,8 @@ const methods = properties.methods[key];

}
if (indexes.length === 0)
return void 0;
if (optional)
indexes.push({ type: "TSUndefinedKeyword" });
return { type: (0, import_common2.createTSUnionType)(indexes), scope };
if (indexes.length === 0) return void 0;
if (optional) indexes.push({ type: "TSUndefinedKeyword" });
return { type: createTSUnionType(indexes), scope };
}
async function resolveTSTypeOperator({ scope, type }, stacks = []) {
if (type.operator !== "keyof")
return void 0;
if (type.operator !== "keyof") return void 0;
const resolved = await resolveTSReferencedType(

@@ -444,7 +392,5 @@ {

);
if (!resolved || isTSNamespace(resolved))
return void 0;
if (!resolved || isTSNamespace(resolved)) return void 0;
const { type: resolvedType, scope: resolvedScope } = resolved;
if (!checkForTSProperties(resolvedType))
return void 0;
if (!checkForTSProperties(resolvedType)) return void 0;
const properties = await resolveTSProperties({

@@ -454,7 +400,6 @@ type: resolvedType,

});
return getTSPropertiesKeys(properties).map((k) => (0, import_common2.createStringLiteral)(k));
return getTSPropertiesKeys(properties).map((k) => createStringLiteral(k));
}
function resolveMaybeTSUnion(node) {
if (Array.isArray(node))
return node;
if (Array.isArray(node)) return node;
if (node.type === "TSUnionType")

@@ -466,10 +411,13 @@ return node.types.flatMap((t) => resolveMaybeTSUnion(t));

// src/ts/scope.ts
var import_promises = require("fs/promises");
var import_common3 = require("@vue-macros/common");
import { readFile } from "node:fs/promises";
import {
babelParse,
getFileCodeAndLang,
REGEX_SUPPORTED_EXT
} from "@vue-macros/common";
var tsFileCache = /* @__PURE__ */ Object.create(null);
async function getTSFile(filePath) {
if (tsFileCache[filePath])
return tsFileCache[filePath];
const content = await (0, import_promises.readFile)(filePath, "utf-8");
const { code, lang } = (0, import_common3.getFileCodeAndLang)(content, filePath);
if (tsFileCache[filePath]) return tsFileCache[filePath];
const content = await readFile(filePath, "utf-8");
const { code, lang } = getFileCodeAndLang(content, filePath);
return tsFileCache[filePath] = {

@@ -479,3 +427,3 @@ kind: "file",

content,
ast: import_common3.REGEX_SUPPORTED_EXT.test(filePath) ? (0, import_common3.babelParse)(code, lang).body : void 0
ast: REGEX_SUPPORTED_EXT.test(filePath) ? babelParse(code, lang).body : void 0
};

@@ -486,7 +434,6 @@ }

let parentScope;
if (!isFile)
parentScope = resolveTSScope(scope.scope);
if (!isFile) parentScope = resolveTSScope(scope.scope);
const file = isFile ? scope : parentScope.file;
const body = isFile ? scope.ast : scope.ast.body;
const exports3 = scope.exports;
const exports2 = scope.exports;
const declarations = isFile ? scope.declarations : { ...resolveTSScope(scope.scope).declarations, ...scope.declarations };

@@ -498,3 +445,3 @@ return {

declarations,
exports: exports3
exports: exports2
};

@@ -505,3 +452,3 @@ }

function isSupportedForTSReferencedType(node) {
return (0, import_types2.isTSType)(node) || node.type === "Identifier" || isTSDeclaration(node);
return isTSType(node) || node.type === "Identifier" || isTSDeclaration(node);
}

@@ -539,3 +486,3 @@ async function resolveTSReferencedType(ref, stacks = []) {

await resolveTSNamespace(scope);
const refNames = (0, import_common4.resolveIdentifier)(
const refNames = resolveIdentifier(
type.type === "TSTypeReference" ? type.typeName : type

@@ -554,22 +501,2 @@ );

// src/ts/resolve-file.ts
var import_node_fs = require("fs");
var import_node_path = __toESM(require("path"));
var resolveTSFileIdImpl = resolveTSFileIdNode;
function resolveTSFileId(id, importer) {
return resolveTSFileIdImpl(id, importer);
}
function resolveTSFileIdNode(id, importer) {
function tryResolve(id2, importer2) {
const filePath = import_node_path.default.resolve(importer2, "..", id2);
if (!(0, import_node_fs.existsSync)(filePath))
return;
return filePath;
}
return tryResolve(id, importer) || tryResolve(`${id}.ts`, importer) || tryResolve(`${id}.d.ts`, importer) || tryResolve(`${id}/index`, importer) || tryResolve(`${id}/index.ts`, importer) || tryResolve(`${id}/index.d.ts`, importer);
}
function setResolveTSFileIdImpl(impl) {
resolveTSFileIdImpl = impl;
}
// src/ts/namespace.ts

@@ -581,8 +508,7 @@ var namespaceSymbol = Symbol("namespace");

async function resolveTSNamespace(scope) {
if (scope.exports)
return;
const exports3 = {
if (scope.exports) return;
const exports2 = {
[namespaceSymbol]: true
};
scope.exports = exports3;
scope.exports = exports2;
const declarations = {

@@ -596,3 +522,3 @@ [namespaceSymbol]: true,

if (stmt.type === "ExportDefaultDeclaration" && isTSDeclaration(stmt.declaration)) {
exports3.default = await resolveTSReferencedType({
exports2.default = await resolveTSReferencedType({
scope,

@@ -603,7 +529,6 @@ type: stmt.declaration

const resolved = await resolveTSFileId(stmt.source.value, file.filePath);
if (!resolved)
continue;
if (!resolved) continue;
const sourceScope = await getTSFile(resolved);
await resolveTSNamespace(sourceScope);
Object.assign(exports3, sourceScope.exports);
Object.assign(exports2, sourceScope.exports);
} else if (stmt.type === "ExportNamedDeclaration") {

@@ -613,4 +538,3 @@ let sourceExports;

const resolved = await resolveTSFileId(stmt.source.value, file.filePath);
if (!resolved)
continue;
if (!resolved) continue;
const scope2 = await getTSFile(resolved);

@@ -634,3 +558,3 @@ await resolveTSNamespace(scope2);

const name = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
exports3[name] = exported;
exports2[name] = exported;
}

@@ -641,3 +565,3 @@ if (isTSDeclaration(stmt.declaration)) {

const exportedName = decl.id.name;
declarations[exportedName] = exports3[exportedName] = await resolveTSReferencedType({
declarations[exportedName] = exports2[exportedName] = await resolveTSReferencedType({
scope,

@@ -649,4 +573,3 @@ type: decl

} else if (isTSDeclaration(stmt)) {
if (stmt.id?.type !== "Identifier")
continue;
if (stmt.id?.type !== "Identifier") continue;
declarations[stmt.id.name] = await resolveTSReferencedType({

@@ -658,7 +581,6 @@ scope,

const resolved = await resolveTSFileId(stmt.source.value, file.filePath);
if (!resolved)
continue;
if (!resolved) continue;
const importScope = await getTSFile(resolved);
await resolveTSNamespace(importScope);
const exports4 = importScope.exports;
const exports3 = importScope.exports;
for (const specifier of stmt.specifiers) {

@@ -668,8 +590,8 @@ const local = specifier.local.name;

if (specifier.type === "ImportDefaultSpecifier") {
imported = exports4.default;
imported = exports3.default;
} else if (specifier.type === "ImportNamespaceSpecifier") {
imported = exports4;
imported = exports3;
} else if (specifier.type === "ImportSpecifier") {
const name = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
imported = exports4[name];
imported = exports3[name];
} else {

@@ -695,4 +617,3 @@ throw new Error(`Unknown import type: ${specifier.type}`);

async function inferRuntimeType(node) {
if (isTSNamespace(node))
return ["Object"];
if (isTSNamespace(node)) return ["Object"];
switch (node.type.type) {

@@ -764,4 +685,3 @@ case "TSStringKeyword":

});
if (t)
return inferRuntimeType(t);
if (t) return inferRuntimeType(t);
}

@@ -775,4 +695,3 @@ break;

});
if (t)
return inferRuntimeType(t);
if (t) return inferRuntimeType(t);
}

@@ -825,6 +744,4 @@ break;

const pairs = [];
if (type)
pairs.push(`type: ${type}`);
if (skipCheck)
pairs.push(`skipCheck: true`);
if (type) pairs.push(`type: ${type}`);
if (skipCheck) pairs.push(`skipCheck: true`);
pairs.push(...properties);

@@ -834,3 +751,136 @@ return pairs.length > 0 ? `{ ${pairs.join(", ")} }` : "null";

// src/vue/emits.ts
async function handleTSEmitsDefinition({
s,
file,
offset,
defineEmitsAst,
typeDeclRaw,
declId,
statement
}) {
const { definitions, definitionsAst } = await resolveDefinitions({
type: typeDeclRaw,
scope: file
});
const addEmit = (name, signature) => {
const key = resolveString(name);
if (definitionsAst.scope === file) {
if (definitionsAst.ast.type === "TSIntersectionType") {
s.appendLeft(definitionsAst.ast.end + offset, ` & { ${signature} }`);
} else {
s.appendLeft(definitionsAst.ast.end + offset - 1, ` ${signature}
`);
}
}
if (!definitions[key]) definitions[key] = [];
const ast = parseSignature(signature);
definitions[key].push({
code: signature,
ast,
scope: void 0
});
};
const setEmit = (name, idx, signature) => {
const key = resolveString(name);
const def = definitions[key][idx];
if (!def) return false;
const ast = parseSignature(signature);
attachNodeLoc(def.ast, ast);
if (def.scope === file) s.overwriteNode(def.ast, signature, { offset });
definitions[key][idx] = {
code: signature,
ast,
scope: void 0
};
return true;
};
const removeEmit = (name, idx) => {
const key = resolveString(name);
const def = definitions[key][idx];
if (!def) return false;
if (def.scope === file) s.removeNode(def.ast, { offset });
definitions[key].splice(idx, 1);
return true;
};
return {
kind: "TS" /* TS */,
definitions,
definitionsAst,
declId,
addEmit,
setEmit,
removeEmit,
statementAst: statement,
defineEmitsAst
};
function parseSignature(signature) {
return babelParse2(`interface T {${signature}}`, "ts").body[0].body.body[0];
}
async function resolveDefinitions(typeDeclRaw2) {
const resolved = await resolveTSReferencedType(typeDeclRaw2);
if (!resolved || isTSNamespace(resolved))
throw new SyntaxError(`Cannot resolve TS definition.`);
const { type: definitionsAst2, scope } = resolved;
if (definitionsAst2.type !== "TSInterfaceDeclaration" && definitionsAst2.type !== "TSTypeLiteral" && definitionsAst2.type !== "TSIntersectionType" && definitionsAst2.type !== "TSFunctionType")
throw new SyntaxError(
`Cannot resolve TS definition: ${definitionsAst2.type}`
);
const properties = await resolveTSProperties({
scope,
type: definitionsAst2
});
const definitions2 = /* @__PURE__ */ Object.create(null);
for (const signature of properties.callSignatures) {
const evtArg = signature.type.parameters[0];
if (!evtArg || evtArg.type !== "Identifier" || evtArg.typeAnnotation?.type !== "TSTypeAnnotation")
continue;
const evtType = await resolveTSReferencedType({
type: evtArg.typeAnnotation.typeAnnotation,
scope: signature.scope
});
if (isTSNamespace(evtType) || !evtType?.type) continue;
const types = evtType.type.type === "TSUnionType" ? evtType.type.types : [evtType.type];
for (const type of types) {
if (type.type !== "TSLiteralType") continue;
const literal = type.literal;
if (!isStaticExpression(literal)) continue;
const evt = String(
resolveLiteral3(literal)
);
if (!definitions2[evt]) definitions2[evt] = [];
definitions2[evt].push(buildDefinition(signature));
}
}
for (const evt of Object.keys(properties.properties)) {
if (!definitions2[evt]) definitions2[evt] = [];
definitions2[evt].push(
buildDefinition(properties.properties[evt].signature)
);
}
return {
definitions: definitions2,
definitionsAst: buildDefinition({ scope, type: definitionsAst2 })
};
}
function buildDefinition({
type,
scope
}) {
return {
code: resolveTSScope(scope).file.content.slice(type.start, type.end),
ast: type,
scope
};
}
}
// src/vue/props.ts
import {
babelParse as babelParse3,
isStaticObjectKey,
resolveIdentifier as resolveIdentifier2,
resolveObjectExpression,
resolveString as resolveString2
} from "@vue-macros/common";
var builtInTypesHandlers = {

@@ -888,4 +938,3 @@ Partial: {

);
if (definitions[key])
return false;
if (definitions[key]) return false;
if (definitionsAst.scope === file) {

@@ -923,4 +972,3 @@ if (definitionsAst.ast.type === "TSIntersectionType") {

const def = definitions[key];
if (!definitions[key])
return false;
if (!definitions[key]) return false;
switch (def.type) {

@@ -964,5 +1012,4 @@ case "method": {

const removeProp = (name) => {
const key = (0, import_common5.resolveString)(name);
if (!definitions[key])
return false;
const key = resolveString2(name);
if (!definitions[key]) return false;
const def = definitions[key];

@@ -978,4 +1025,3 @@ switch (def.type) {

def.methods.forEach((method) => {
if (method.scope === file)
s.removeNode(method.ast, { offset });
if (method.scope === file) s.removeNode(method.ast, { offset });
});

@@ -1187,3 +1233,3 @@ break;

throw new SyntaxError(
`Cannot resolve TS type: ${(0, import_common5.resolveIdentifier)(
`Cannot resolve TS type: ${resolveIdentifier2(
definitionsAst2.typeName

@@ -1210,17 +1256,14 @@ ).join(".")}`

function resolveDefaults(defaultsAst2) {
if (!defaultsAst2)
return {};
const isStatic = defaultsAst2.type === "ObjectExpression" && (0, import_common5.isStaticObjectKey)(defaultsAst2);
if (!isStatic)
return { defaultsAst: defaultsAst2 };
const defaults2 = (0, import_common5.resolveObjectExpression)(defaultsAst2);
if (!defaults2)
return { defaultsAst: defaultsAst2 };
if (!defaultsAst2) return {};
const isStatic = defaultsAst2.type === "ObjectExpression" && isStaticObjectKey(defaultsAst2);
if (!isStatic) return { defaultsAst: defaultsAst2 };
const defaults2 = resolveObjectExpression(defaultsAst2);
if (!defaults2) return { defaultsAst: defaultsAst2 };
return { defaults: defaults2, defaultsAst: defaultsAst2 };
}
function buildNewProp(name, value, optional) {
const key = (0, import_common5.resolveString)(name);
const key = resolveString2(name);
const signature = `${name}${optional ? "?" : ""}: ${value}`;
const valueAst = (0, import_common5.babelParse)(`type T = (${value})`, "ts").body[0].typeAnnotation.typeAnnotation;
const signatureAst = (0, import_common5.babelParse)(`interface T {${signature}}`, "ts").body[0].body.body[0];
const valueAst = babelParse3(`type T = (${value})`, "ts").body[0].typeAnnotation.typeAnnotation;
const signatureAst = babelParse3(`interface T {${signature}}`, "ts").body[0].body.body[0];
return { key, signature, signatureAst, valueAst };

@@ -1240,146 +1283,8 @@ }

// src/vue/emits.ts
var import_common6 = require("@vue-macros/common");
async function handleTSEmitsDefinition({
s,
file,
offset,
defineEmitsAst,
typeDeclRaw,
declId,
statement
}) {
const { definitions, definitionsAst } = await resolveDefinitions({
type: typeDeclRaw,
scope: file
});
const addEmit = (name, signature) => {
const key = (0, import_common6.resolveString)(name);
if (definitionsAst.scope === file) {
if (definitionsAst.ast.type === "TSIntersectionType") {
s.appendLeft(definitionsAst.ast.end + offset, ` & { ${signature} }`);
} else {
s.appendLeft(definitionsAst.ast.end + offset - 1, ` ${signature}
`);
}
}
if (!definitions[key])
definitions[key] = [];
const ast = parseSignature(signature);
definitions[key].push({
code: signature,
ast,
scope: void 0
});
};
const setEmit = (name, idx, signature) => {
const key = (0, import_common6.resolveString)(name);
const def = definitions[key][idx];
if (!def)
return false;
const ast = parseSignature(signature);
attachNodeLoc(def.ast, ast);
if (def.scope === file)
s.overwriteNode(def.ast, signature, { offset });
definitions[key][idx] = {
code: signature,
ast,
scope: void 0
};
return true;
};
const removeEmit = (name, idx) => {
const key = (0, import_common6.resolveString)(name);
const def = definitions[key][idx];
if (!def)
return false;
if (def.scope === file)
s.removeNode(def.ast, { offset });
definitions[key].splice(idx, 1);
return true;
};
return {
kind: "TS" /* TS */,
definitions,
definitionsAst,
declId,
addEmit,
setEmit,
removeEmit,
statementAst: statement,
defineEmitsAst
};
function parseSignature(signature) {
return (0, import_common6.babelParse)(`interface T {${signature}}`, "ts").body[0].body.body[0];
}
async function resolveDefinitions(typeDeclRaw2) {
const resolved = await resolveTSReferencedType(typeDeclRaw2);
if (!resolved || isTSNamespace(resolved))
throw new SyntaxError(`Cannot resolve TS definition.`);
const { type: definitionsAst2, scope } = resolved;
if (definitionsAst2.type !== "TSInterfaceDeclaration" && definitionsAst2.type !== "TSTypeLiteral" && definitionsAst2.type !== "TSIntersectionType" && definitionsAst2.type !== "TSFunctionType")
throw new SyntaxError(
`Cannot resolve TS definition: ${definitionsAst2.type}`
);
const properties = await resolveTSProperties({
scope,
type: definitionsAst2
});
const definitions2 = /* @__PURE__ */ Object.create(null);
for (const signature of properties.callSignatures) {
const evtArg = signature.type.parameters[0];
if (!evtArg || evtArg.type !== "Identifier" || evtArg.typeAnnotation?.type !== "TSTypeAnnotation")
continue;
const evtType = await resolveTSReferencedType({
type: evtArg.typeAnnotation.typeAnnotation,
scope: signature.scope
});
if (isTSNamespace(evtType) || !evtType?.type)
continue;
const types = evtType.type.type === "TSUnionType" ? evtType.type.types : [evtType.type];
for (const type of types) {
if (type.type !== "TSLiteralType")
continue;
const literal = type.literal;
if (!(0, import_common6.isStaticExpression)(literal))
continue;
const evt = String(
(0, import_common6.resolveLiteral)(literal)
);
if (!definitions2[evt])
definitions2[evt] = [];
definitions2[evt].push(buildDefinition(signature));
}
}
for (const evt of Object.keys(properties.properties)) {
if (!definitions2[evt])
definitions2[evt] = [];
definitions2[evt].push(
buildDefinition(properties.properties[evt].signature)
);
}
return {
definitions: definitions2,
definitionsAst: buildDefinition({ scope, type: definitionsAst2 })
};
}
function buildDefinition({
type,
scope
}) {
return {
code: resolveTSScope(scope).file.content.slice(type.start, type.end),
ast: type,
scope
};
}
}
// src/vue/analyze.ts
var import_common8 = require("@vue-macros/common");
import { parseSFC } from "@vue-macros/common";
async function analyzeSFC(s, sfc) {
if (!sfc.scriptSetup)
throw new Error("Only <script setup> is supported");
if (!sfc.scriptSetup) throw new Error("Only <script setup> is supported");
const { scriptSetup } = sfc;
const body = (0, import_common7.babelParse)(
const body = babelParse4(
scriptSetup.content,

@@ -1413,4 +1318,3 @@ sfc.scriptSetup.lang || "js"

for (const decl of node.declarations) {
if (!decl.init)
continue;
if (!decl.init) continue;
await processDefineProps({

@@ -1445,4 +1349,3 @@ statement: node,

}) {
if (!(0, import_common7.isCallOf)(defineProps, import_common7.DEFINE_PROPS) || props)
return false;
if (!isCallOf(defineProps, DEFINE_PROPS) || props) return false;
const typeDeclRaw = defineProps.typeParameters?.params[0];

@@ -1472,7 +1375,6 @@ if (typeDeclRaw) {

}) {
if (!(0, import_common7.isCallOf)(withDefaults, import_common7.WITH_DEFAULTS))
return false;
if (!(0, import_common7.isCallOf)(withDefaults.arguments[0], import_common7.DEFINE_PROPS)) {
if (!isCallOf(withDefaults, WITH_DEFAULTS)) return false;
if (!isCallOf(withDefaults.arguments[0], DEFINE_PROPS)) {
throw new SyntaxError(
`${import_common7.WITH_DEFAULTS}: first argument must be a ${import_common7.DEFINE_PROPS} call.`
`${WITH_DEFAULTS}: first argument must be a ${DEFINE_PROPS} call.`
);

@@ -1487,4 +1389,3 @@ }

});
if (!isDefineProps)
return false;
if (!isDefineProps) return false;
return true;

@@ -1497,4 +1398,3 @@ }

}) {
if (!(0, import_common7.isCallOf)(defineEmits, import_common7.DEFINE_EMITS) || emits)
return false;
if (!isCallOf(defineEmits, DEFINE_EMITS) || emits) return false;
const typeDeclRaw = defineEmits.typeParameters?.params[0];

@@ -1520,7 +1420,7 @@ if (typeDeclRaw) {

// src/resolve.ts
var import_node_fs2 = require("fs");
var import_promises2 = require("fs/promises");
var import_node_path2 = __toESM(require("path"));
var import_resolve3 = require("resolve.exports");
var import_common9 = require("@vue-macros/common");
import { existsSync as existsSync2 } from "node:fs";
import { readFile as readFile2 } from "node:fs/promises";
import path2 from "node:path";
import { isDts } from "@vue-macros/common";
import { exports } from "resolve.exports";
var deepImportRE = /^([^@][^/]*)\/|^(@[^/]+\/[^/]+)\//;

@@ -1530,4 +1430,3 @@ var RollupResolve = () => {

function collectReferencedFile(importer, file) {
if (!importer)
return;
if (!importer) return;
if (!referencedFiles.has(file)) {

@@ -1554,6 +1453,5 @@ referencedFiles.set(file, /* @__PURE__ */ new Set([importer]));

const pkgPath = (await ctx.resolve(`${pkgId}/package.json`, importer))?.id;
if (!pkgPath)
return;
const pkg = JSON.parse(await (0, import_promises2.readFile)(pkgPath, "utf-8"));
const pkgRoot = import_node_path2.default.resolve(pkgPath, "..");
if (!pkgPath) return;
const pkg = JSON.parse(await readFile2(pkgPath, "utf-8"));
const pkgRoot = path2.resolve(pkgPath, "..");
if (deepMatch) {

@@ -1566,11 +1464,9 @@ if (pkg.typesVersions) {

)) {
if (pkgPath2 !== entry.replace("*", pkgPath2))
continue;
if (pkgPath2 !== entry.replace("*", pkgPath2)) continue;
for (const subpath of subpaths) {
const resolved2 = import_node_path2.default.resolve(
const resolved2 = path2.resolve(
pkgRoot,
subpath.replace("*", pkgPath2)
);
if ((0, import_common9.isDts)(resolved2) && (0, import_node_fs2.existsSync)(resolved2))
return resolved2;
if (isDts(resolved2) && existsSync2(resolved2)) return resolved2;
}

@@ -1580,15 +1476,11 @@ }

}
const resolvedIds = (0, import_resolve3.exports)(pkg, id, { conditions: ["types"] });
if (!resolvedIds)
return;
const resolved = resolvedIds.find((id2) => (0, import_common9.isDts)(id2) && (0, import_node_fs2.existsSync)(id2));
if (resolved)
return resolved;
const resolvedIds = exports(pkg, id, { conditions: ["types"] });
if (!resolvedIds) return;
const resolved = resolvedIds.find((id2) => isDts(id2) && existsSync2(id2));
if (resolved) return resolved;
} else {
const types = pkg.types || pkg.typings;
if (!types)
return;
const entry = import_node_path2.default.resolve(pkgRoot, types);
if ((0, import_node_fs2.existsSync)(entry))
return entry;
if (!types) return;
const entry = path2.resolve(pkgRoot, types);
if (existsSync2(entry)) return entry;
}

@@ -1607,13 +1499,10 @@ } catch {

const cached = resolveCache.get(importer)?.get(id);
if (cached)
return cached;
if (cached) return cached;
if (id[0] !== "." && id[0] !== "/") {
const entry = await tryPkgEntry(id, importer);
if (entry)
return withResolveCache(id, importer, entry);
if (entry) return withResolveCache(id, importer, entry);
}
let resolved = await tryResolve(id, importer);
if (!resolved)
return;
if ((0, import_node_fs2.existsSync)(resolved)) {
if (!resolved) return;
if (existsSync2(resolved)) {
collectReferencedFile(importer, resolved);

@@ -1623,3 +1512,3 @@ return withResolveCache(id, importer, resolved);

resolved = await tryResolve(resolved, importer);
if (resolved && (0, import_node_fs2.existsSync)(resolved)) {
if (resolved && existsSync2(resolved)) {
collectReferencedFile(importer, resolved);

@@ -1637,6 +1526,4 @@ return withResolveCache(id, importer, resolved);

function getAffectedModules(file2) {
if (cache.has(file2))
return cache.get(file2);
if (!referencedFiles.has(file2))
return /* @__PURE__ */ new Set([]);
if (cache.has(file2)) return cache.get(file2);
if (!referencedFiles.has(file2)) return /* @__PURE__ */ new Set([]);
const modules2 = /* @__PURE__ */ new Set([]);

@@ -1646,4 +1533,3 @@ cache.set(file2, modules2);

const mods = server.moduleGraph.getModulesByFile(importer);
if (mods)
mods.forEach((m) => modules2.add(m));
if (mods) mods.forEach((m) => modules2.add(m));
getAffectedModules(importer).forEach((m) => modules2.add(m));

@@ -1653,4 +1539,3 @@ }

}
if (tsFileCache[file])
delete tsFileCache[file];
if (tsFileCache[file]) delete tsFileCache[file];
const affected = getAffectedModules(file);

@@ -1664,4 +1549,3 @@ return [...modules, ...affected];

};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
export {
DefinitionKind,

@@ -1699,4 +1583,3 @@ RollupResolve,

setResolveTSFileIdImpl,
tsFileCache,
...require("@vue-macros/common")
});
tsFileCache
};
{
"name": "@vue-macros/api",
"version": "0.9.7",
"version": "0.10.0",
"description": "General API for Vue Macros.",
"type": "module",
"keywords": [

@@ -28,4 +29,4 @@ "vue-macros",

],
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "./dist/index.d.ts",

@@ -35,14 +36,11 @@ "exports": {

"dev": "./src/index.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
"require": "./dist/index.cjs",
"import": "./dist/index.js"
},
"./*": [
"./*",
"./*.d.ts"
]
"./*": "./*"
},
"dependencies": {
"@babel/types": "^7.24.5",
"@babel/types": "^7.24.9",
"resolve.exports": "^2.0.2",
"@vue-macros/common": "1.10.4"
"@vue-macros/common": "1.11.0"
},

@@ -49,0 +47,0 @@ "engines": {

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