UNPKG

@sizium/core

Version:

Get the actual size of any local or remote package

88 lines (83 loc) 2.49 kB
'use strict'; const promises = require('node:fs/promises'); const node_path = require('node:path'); const _super = require('./core.-Ai0yTLh.cjs'); const isUrl = (value) => { try { new URL(value); return true; } catch { return false; } }; const isJsonString = (value) => { try { JSON.parse(value); return true; } catch { return false; } }; const isPath = (value) => { if (node_path.isAbsolute(value) || /^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(value)) { if (node_path.isAbsolute(value) || /^(\.\/|\.\.\/|[A-Za-z]:\\|\/)/.test(value)) { if (/\s(?!\\)/.test(value) && !/\\\s/.test(value)) return false; try { const normalizedPath = node_path.join(value); return normalizedPath !== ""; } catch { return false; } } } return false; }; const isString = (value) => { return typeof value === "string" && value.trim().length > 0; }; const getInputType = (value) => { if (!isString(value)) throw new Error("Input is not a valid string"); if (isUrl(value)) return "url"; if (isJsonString(value)) return "json"; if (isPath(value)) return "path"; return "string"; }; class SiziumLocal extends _super.PackageSuper { async #getPackage() { try { if (isUrl(this.input)) { const response = await fetch(this.input); if (!response.ok) throw new Error(`Failed to fetch package file from URL: ${response.statusText}`); const content = await response.text(); return JSON.parse(content); } else if (isJsonString(this.input)) { return JSON.parse(this.input); } else { let filePath = node_path.resolve(this.input); const stats = await promises.stat(filePath); if (stats.isDirectory()) filePath = node_path.join(filePath, "package.json"); const content = await promises.readFile(filePath, "utf-8"); return JSON.parse(content); } } catch (e) { throw new this.Error( this.ERROR_ID.GETTING_LOCAL_DATA, { msg: `Error processing package file: ${e instanceof Error ? e.message : ""}`, e } ); } } async get() { const packageData = await this.#getPackage(); const mainPackage = await this.getPkgData(packageData, 0); const allPackages = await this.getPackagesData(mainPackage); return this.getMainPkgData(allPackages); } } exports.SiziumLocal = SiziumLocal; exports.getInputType = getInputType;