ghostimport 0.1.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/dist/index.cjs ADDED
@@ -0,0 +1,476 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ checkNpm: () => checkNpm,
34
+ checkScary: () => checkScary,
35
+ extractImports: () => extractImports,
36
+ loadCache: () => loadCache,
37
+ loadConfig: () => loadConfig,
38
+ readPackageJsonDeps: () => readPackageJsonDeps,
39
+ saveCache: () => saveCache,
40
+ scan: () => scan,
41
+ walkFiles: () => walkFiles
42
+ });
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // src/imports.ts
46
+ var IMPORT_PATTERNS = [
47
+ /import\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'".\n][^'"]*)['"]/g,
48
+ /require\s*\(\s*['"]([^'".\n][^'"]*)['"]\s*\)/g,
49
+ /import\s*\(\s*['"]([^'".\n][^'"]*)['"]\s*\)/g,
50
+ /export\s+(?:[\w*{}\s,]+\s+from\s+)?['"]([^'".\n][^'"]*)['"]/g
51
+ ];
52
+ var BUILTIN_MODULES = /* @__PURE__ */ new Set([
53
+ "assert",
54
+ "assert/strict",
55
+ "async_hooks",
56
+ "buffer",
57
+ "child_process",
58
+ "cluster",
59
+ "console",
60
+ "constants",
61
+ "crypto",
62
+ "dgram",
63
+ "diagnostics_channel",
64
+ "dns",
65
+ "dns/promises",
66
+ "domain",
67
+ "events",
68
+ "fs",
69
+ "fs/promises",
70
+ "http",
71
+ "http2",
72
+ "https",
73
+ "inspector",
74
+ "inspector/promises",
75
+ "module",
76
+ "net",
77
+ "os",
78
+ "path",
79
+ "path/posix",
80
+ "path/win32",
81
+ "perf_hooks",
82
+ "process",
83
+ "punycode",
84
+ "querystring",
85
+ "readline",
86
+ "readline/promises",
87
+ "repl",
88
+ "sea",
89
+ "stream",
90
+ "stream/consumers",
91
+ "stream/promises",
92
+ "stream/web",
93
+ "string_decoder",
94
+ "sys",
95
+ "test",
96
+ "timers",
97
+ "timers/promises",
98
+ "tls",
99
+ "trace_events",
100
+ "tty",
101
+ "url",
102
+ "util",
103
+ "util/types",
104
+ "v8",
105
+ "vm",
106
+ "wasi",
107
+ "worker_threads",
108
+ "zlib"
109
+ ]);
110
+ function isBuiltin(name) {
111
+ if (name.startsWith("node:")) return true;
112
+ return BUILTIN_MODULES.has(name);
113
+ }
114
+ function toPackageName(importPath) {
115
+ if (importPath.startsWith("@")) {
116
+ const parts = importPath.split("/");
117
+ if (parts.length < 2) return null;
118
+ return `${parts[0]}/${parts[1]}`;
119
+ }
120
+ return importPath.split("/")[0];
121
+ }
122
+ function extractImports(code) {
123
+ const found = /* @__PURE__ */ new Set();
124
+ for (const pattern of IMPORT_PATTERNS) {
125
+ pattern.lastIndex = 0;
126
+ let match;
127
+ while ((match = pattern.exec(code)) !== null) {
128
+ const raw = match[1];
129
+ const pkg = toPackageName(raw);
130
+ if (pkg && !isBuiltin(raw) && !isBuiltin(pkg)) {
131
+ found.add(pkg);
132
+ }
133
+ }
134
+ }
135
+ return [...found];
136
+ }
137
+
138
+ // src/cache.ts
139
+ var import_fs = __toESM(require("fs"), 1);
140
+ var import_path = __toESM(require("path"), 1);
141
+ var import_os = __toESM(require("os"), 1);
142
+ var CACHE_TTL = 24 * 60 * 60 * 1e3;
143
+ function getCacheDir() {
144
+ const dir = import_path.default.join(import_os.default.homedir(), ".ghostimport");
145
+ if (!import_fs.default.existsSync(dir)) import_fs.default.mkdirSync(dir, { recursive: true });
146
+ return dir;
147
+ }
148
+ function getCachePath() {
149
+ return import_path.default.join(getCacheDir(), "registry-cache.json");
150
+ }
151
+ function loadCache() {
152
+ const cachePath = getCachePath();
153
+ if (!import_fs.default.existsSync(cachePath)) return {};
154
+ try {
155
+ return JSON.parse(import_fs.default.readFileSync(cachePath, "utf8"));
156
+ } catch {
157
+ return {};
158
+ }
159
+ }
160
+ function saveCache(cache) {
161
+ import_fs.default.writeFileSync(getCachePath(), JSON.stringify(cache, null, 2), "utf8");
162
+ }
163
+ function getCached(cache, pkgName) {
164
+ const entry = cache[pkgName];
165
+ if (!entry) return null;
166
+ if (Date.now() - entry.ts > CACHE_TTL) return null;
167
+ return entry;
168
+ }
169
+
170
+ // src/config.ts
171
+ var import_fs2 = __toESM(require("fs"), 1);
172
+ var import_path2 = __toESM(require("path"), 1);
173
+ var defaults = { ignore: [], includeUndeclared: true };
174
+ function loadConfig(dir) {
175
+ const configPath = import_path2.default.join(dir, ".ghostimportrc.json");
176
+ if (!import_fs2.default.existsSync(configPath)) return { ...defaults };
177
+ try {
178
+ const raw = JSON.parse(import_fs2.default.readFileSync(configPath, "utf8"));
179
+ return { ...defaults, ...raw };
180
+ } catch {
181
+ return { ...defaults };
182
+ }
183
+ }
184
+ function matchesIgnore(pkg, patterns) {
185
+ for (const pattern of patterns) {
186
+ if (pattern === pkg) return true;
187
+ if (pattern.endsWith("/*")) {
188
+ const prefix = pattern.slice(0, -1);
189
+ if (pkg.startsWith(prefix)) return true;
190
+ }
191
+ }
192
+ return false;
193
+ }
194
+
195
+ // src/npm.ts
196
+ var import_https = __toESM(require("https"), 1);
197
+ function httpGetJson(url) {
198
+ return new Promise((resolve, reject) => {
199
+ const req = import_https.default.get(url, { headers: { Accept: "application/json" }, timeout: 8e3 }, (res) => {
200
+ let data = "";
201
+ res.on("data", (chunk) => {
202
+ data += chunk;
203
+ });
204
+ res.on("end", () => {
205
+ if (res.statusCode === 200) {
206
+ try {
207
+ resolve(JSON.parse(data));
208
+ } catch {
209
+ reject(new Error("Invalid JSON"));
210
+ }
211
+ } else if (res.statusCode === 404) {
212
+ resolve(null);
213
+ } else {
214
+ reject(new Error(`HTTP ${res.statusCode}`));
215
+ }
216
+ });
217
+ });
218
+ req.on("timeout", () => {
219
+ req.destroy();
220
+ reject(new Error("timeout"));
221
+ });
222
+ req.on("error", reject);
223
+ });
224
+ }
225
+ function encodePackageName(pkgName) {
226
+ return pkgName.startsWith("@") ? "@" + encodeURIComponent(pkgName.slice(1)) : encodeURIComponent(pkgName);
227
+ }
228
+ function checkNpm(pkgName) {
229
+ return new Promise((resolve) => {
230
+ const options = {
231
+ hostname: "registry.npmjs.org",
232
+ path: `/${encodePackageName(pkgName)}`,
233
+ method: "GET",
234
+ headers: { Accept: "application/json" },
235
+ timeout: 8e3
236
+ };
237
+ const req = import_https.default.request(options, (res) => {
238
+ res.resume();
239
+ if (res.statusCode === 200) {
240
+ resolve({ exists: true });
241
+ } else if (res.statusCode === 404) {
242
+ resolve({ exists: false });
243
+ } else {
244
+ resolve({ exists: null, error: `HTTP ${res.statusCode}` });
245
+ }
246
+ });
247
+ req.on("timeout", () => {
248
+ req.destroy();
249
+ resolve({ exists: null, error: "timeout" });
250
+ });
251
+ req.on("error", (err) => {
252
+ resolve({ exists: null, error: err.message });
253
+ });
254
+ req.end();
255
+ });
256
+ }
257
+ async function checkScary(pkgName) {
258
+ const encoded = encodePackageName(pkgName);
259
+ try {
260
+ const meta = await httpGetJson(`https://registry.npmjs.org/${encoded}`);
261
+ if (!meta) return { exists: false, squatRisk: "available" };
262
+ const created = meta.time?.created ? new Date(meta.time.created) : null;
263
+ const ageMs = created ? Date.now() - created.getTime() : Infinity;
264
+ const ageDays = Math.floor(ageMs / (1e3 * 60 * 60 * 24));
265
+ let downloads = null;
266
+ try {
267
+ const dl = await httpGetJson(`https://api.npmjs.org/downloads/point/last-week/${encoded}`);
268
+ downloads = dl?.downloads ?? null;
269
+ } catch {
270
+ }
271
+ const flags = [];
272
+ if (ageDays < 30) flags.push(`created ${ageDays} days ago`);
273
+ if (downloads !== null && downloads < 50) flags.push(`${downloads} weekly downloads`);
274
+ if (meta.versions && Object.keys(meta.versions).length <= 1) flags.push("single version published");
275
+ const risk = flags.length >= 2 ? "high" : flags.length === 1 ? "medium" : "low";
276
+ return {
277
+ exists: true,
278
+ created: created?.toISOString().slice(0, 10) ?? "unknown",
279
+ downloads,
280
+ versions: meta.versions ? Object.keys(meta.versions).length : 0,
281
+ risk,
282
+ flags
283
+ };
284
+ } catch (err) {
285
+ return { exists: null, error: err.message };
286
+ }
287
+ }
288
+
289
+ // src/files.ts
290
+ var import_fs3 = __toESM(require("fs"), 1);
291
+ var import_path3 = __toESM(require("path"), 1);
292
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", "dist", "build", ".next", "coverage", ".cache"]);
293
+ var CODE_EXTS = /* @__PURE__ */ new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
294
+ function walkFiles(dir) {
295
+ const results = [];
296
+ function walk(current) {
297
+ let entries;
298
+ try {
299
+ entries = import_fs3.default.readdirSync(current, { withFileTypes: true });
300
+ } catch {
301
+ return;
302
+ }
303
+ for (const entry of entries) {
304
+ if (entry.isDirectory()) {
305
+ if (!SKIP_DIRS.has(entry.name)) walk(import_path3.default.join(current, entry.name));
306
+ } else if (entry.isFile()) {
307
+ if (CODE_EXTS.has(import_path3.default.extname(entry.name))) results.push(import_path3.default.join(current, entry.name));
308
+ }
309
+ }
310
+ }
311
+ walk(dir);
312
+ return results;
313
+ }
314
+ function readPackageJsonDeps(dir) {
315
+ const pkgPath = import_path3.default.join(dir, "package.json");
316
+ if (!import_fs3.default.existsSync(pkgPath)) return /* @__PURE__ */ new Set();
317
+ try {
318
+ const pkg = JSON.parse(import_fs3.default.readFileSync(pkgPath, "utf8"));
319
+ return /* @__PURE__ */ new Set([
320
+ ...Object.keys(pkg.dependencies ?? {}),
321
+ ...Object.keys(pkg.devDependencies ?? {}),
322
+ ...Object.keys(pkg.peerDependencies ?? {}),
323
+ ...Object.keys(pkg.optionalDependencies ?? {})
324
+ ]);
325
+ } catch {
326
+ return /* @__PURE__ */ new Set();
327
+ }
328
+ }
329
+ function readWorkspacePackages(dir) {
330
+ const names = /* @__PURE__ */ new Set();
331
+ try {
332
+ const pkg = JSON.parse(import_fs3.default.readFileSync(import_path3.default.join(dir, "package.json"), "utf8"));
333
+ const workspaces = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages ?? [];
334
+ for (const pattern of workspaces) {
335
+ const base = pattern.replace(/\/?\*$/, "");
336
+ const wsDir = import_path3.default.join(dir, base);
337
+ if (!import_fs3.default.existsSync(wsDir)) continue;
338
+ for (const entry of import_fs3.default.readdirSync(wsDir, { withFileTypes: true })) {
339
+ if (!entry.isDirectory()) continue;
340
+ const wsPkgPath = import_path3.default.join(wsDir, entry.name, "package.json");
341
+ if (!import_fs3.default.existsSync(wsPkgPath)) continue;
342
+ try {
343
+ const wsPkg = JSON.parse(import_fs3.default.readFileSync(wsPkgPath, "utf8"));
344
+ if (wsPkg.name) names.add(wsPkg.name);
345
+ } catch {
346
+ }
347
+ }
348
+ }
349
+ } catch {
350
+ }
351
+ const pnpmPath = import_path3.default.join(dir, "pnpm-workspace.yaml");
352
+ if (!import_fs3.default.existsSync(pnpmPath)) return names;
353
+ try {
354
+ const content = import_fs3.default.readFileSync(pnpmPath, "utf8");
355
+ for (const m of content.matchAll(/- ['"]?([^'"\n]+)['"]?/g)) {
356
+ const base = m[1].replace(/\/?\*$/, "");
357
+ const wsDir = import_path3.default.join(dir, base);
358
+ if (!import_fs3.default.existsSync(wsDir)) continue;
359
+ for (const entry of import_fs3.default.readdirSync(wsDir, { withFileTypes: true })) {
360
+ if (!entry.isDirectory()) continue;
361
+ const wsPkgPath = import_path3.default.join(wsDir, entry.name, "package.json");
362
+ if (!import_fs3.default.existsSync(wsPkgPath)) continue;
363
+ try {
364
+ const wsPkg = JSON.parse(import_fs3.default.readFileSync(wsPkgPath, "utf8"));
365
+ if (wsPkg.name) names.add(wsPkg.name);
366
+ } catch {
367
+ }
368
+ }
369
+ }
370
+ } catch {
371
+ }
372
+ return names;
373
+ }
374
+
375
+ // src/scan.ts
376
+ var import_fs4 = __toESM(require("fs"), 1);
377
+ var import_path4 = __toESM(require("path"), 1);
378
+ var CONCURRENCY = 10;
379
+ async function scan(targetDir, { onProgress, useCache = true, scary = false, config } = {}) {
380
+ const conf = config ?? loadConfig(targetDir);
381
+ const files = walkFiles(targetDir);
382
+ const declaredDeps = readPackageJsonDeps(targetDir);
383
+ const workspacePkgs = readWorkspacePackages(targetDir);
384
+ const cache = useCache ? loadCache() : {};
385
+ let cacheHits = 0;
386
+ const importMap = /* @__PURE__ */ new Map();
387
+ for (const file of files) {
388
+ let code;
389
+ try {
390
+ code = import_fs4.default.readFileSync(file, "utf8");
391
+ } catch {
392
+ continue;
393
+ }
394
+ for (const pkg of extractImports(code)) {
395
+ if (!importMap.has(pkg)) importMap.set(pkg, []);
396
+ importMap.get(pkg).push(import_path4.default.relative(targetDir, file));
397
+ }
398
+ }
399
+ const allPkgs = [...importMap.keys()].filter(
400
+ (pkg) => !matchesIgnore(pkg, conf.ignore) && !workspacePkgs.has(pkg)
401
+ );
402
+ const results = {
403
+ scanned: files.length,
404
+ packages: allPkgs.length,
405
+ hallucinated: [],
406
+ notInPackageJson: [],
407
+ errors: [],
408
+ scary: [],
409
+ cacheHits: 0
410
+ };
411
+ for (let i = 0; i < allPkgs.length; i += CONCURRENCY) {
412
+ const batch = allPkgs.slice(i, i + CONCURRENCY);
413
+ const checks = await Promise.all(
414
+ batch.map((pkg) => {
415
+ const cached = getCached(cache, pkg);
416
+ if (cached) {
417
+ cacheHits++;
418
+ return Promise.resolve({ exists: cached.exists });
419
+ }
420
+ return checkNpm(pkg);
421
+ })
422
+ );
423
+ for (let j = 0; j < batch.length; j++) {
424
+ const pkg = batch[j];
425
+ const { exists, error } = checks[j];
426
+ const matchedFiles = importMap.get(pkg);
427
+ if (exists !== null && useCache) {
428
+ cache[pkg] = { exists, ts: Date.now() };
429
+ }
430
+ onProgress?.({ pkg, exists, error, total: allPkgs.length, done: i + j + 1 });
431
+ if (exists === false) {
432
+ results.hallucinated.push({ pkg, files: matchedFiles });
433
+ } else if (exists === null && error) {
434
+ results.errors.push({ pkg, error, files: matchedFiles });
435
+ } else if (exists === true && !declaredDeps.has(pkg)) {
436
+ results.notInPackageJson.push({ pkg, files: matchedFiles });
437
+ }
438
+ }
439
+ }
440
+ if (useCache) saveCache(cache);
441
+ results.cacheHits = cacheHits;
442
+ if (scary) {
443
+ for (const { pkg, files: matchedFiles } of results.hallucinated) {
444
+ results.scary.push({ pkg, files: matchedFiles, type: "available" });
445
+ }
446
+ for (const { pkg, files: matchedFiles } of results.notInPackageJson) {
447
+ const info = await checkScary(pkg);
448
+ if (info.exists === true && info.risk !== "low") {
449
+ results.scary.push({
450
+ pkg,
451
+ files: matchedFiles,
452
+ type: "suspicious",
453
+ exists: true,
454
+ created: info.created,
455
+ downloads: info.downloads,
456
+ versions: info.versions,
457
+ risk: info.risk,
458
+ flags: info.flags
459
+ });
460
+ }
461
+ }
462
+ }
463
+ return results;
464
+ }
465
+ // Annotate the CommonJS export names for ESM import in node:
466
+ 0 && (module.exports = {
467
+ checkNpm,
468
+ checkScary,
469
+ extractImports,
470
+ loadCache,
471
+ loadConfig,
472
+ readPackageJsonDeps,
473
+ saveCache,
474
+ scan,
475
+ walkFiles
476
+ });
@@ -0,0 +1,7 @@
1
+ export { extractImports } from './imports';
2
+ export { loadCache, saveCache } from './cache';
3
+ export { loadConfig } from './config';
4
+ export { checkNpm, checkScary } from './npm';
5
+ export { walkFiles, readPackageJsonDeps } from './files';
6
+ export { scan } from './scan';
7
+ export type { Config, ScanOptions, ScanProgress, ScanResult, PackageRef, PackageError, ScaryEntry, NpmCheckResult, ScaryCheckResult, CacheEntry, } from './types';