Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
const main = async lock => {
for (const [loc, meta] of Object.entries(lock.packages)) {
if (!loc || meta.link || !nm.test(loc))
continue
const name = meta.name || loc.replace(nm, '$1')
console.error('FETCHING', name)
const paku = await pacote.packument(name)
const saveTo = resolve(dir, name.replace(/^@/, '') + '.json')
mkdirp.sync(dirname(saveTo))
writeFileSync(saveTo, JSON.stringify(paku, 0, 2))
// bundled deps sometimes don't have a resolved value
if (!meta.resolved)
continue
const path = url.parse(meta.resolved).pathname.replace(/^\/@?/, '')
const tgzFile = resolve(dir, path)
await pacote.tarball.file(meta.resolved, tgzFile)
}
console.log('OK!')
}
async isLatestDatabase() {
// Read package.json database semver and database package file
const [ remotePackage, localPackage ] = await Promise.all( [
manifest( databasePackage ),
readJSON( join( DATABASE_FOLDER, 'package.json' ), 'utf-8' ),
] )
const { version: local } = localPackage
const { version: remote } = remotePackage
this.emit( 'database-version', { local, remote } )
logger.info( 'Local Database Version:', local )
logger.info( 'Remote Database Version:', remote )
return localPackage.version === remotePackage.version
}
function getManifest(depString) {
if (cache[depString]) {
// Only use it if it's not expired
if (cache[depString].ttl + MAX_TTL > Date.now()) {
return cache[depString].promise;
}
}
const promise = pacote.manifest(depString);
cache[depString] = promise;
return promise;
}
newNodeFromSpec (name, spec, parent) {
// pacote will slap integrity on its options, so we have to clone
// the object so it doesn't get mutated.
// Don't bother to load the manifest for link deps, because the target
// might be within another package that doesn't exist yet.
return spec.type === 'directory'
? Promise.resolve(new Link({ name, parent, realpath: spec.fetchSpec }))
: pacote.manifest(spec, Object.create(this.options))
.then(pkg => new Node({ name, pkg, parent }))
}
export default async function fetchTemplate(destinationPath: string, template?: string) {
if (template && fse.existsSync(path.resolve(template))) {
// local template
Logger.global.info(`Using local template: ${chalk.bold(path.resolve(template))}.`);
await fse.copy(path.resolve(template), destinationPath);
} else if (template && isNpmPackage(template)) {
// npm package
Logger.global.info(`Using NPM package as template: ${chalk.bold(template)}`);
await pacote.extract(template, destinationPath);
} else {
// default npm packge
Logger.global.info(`Using default NPM package as template: ${chalk.bold(DEFAULT_TEMPLATE)}`);
await pacote.extract(DEFAULT_TEMPLATE, destinationPath);
}
if (await fse.pathExists(path.join(destinationPath, 'template-unimodule.json'))) {
await fse.move(
path.join(destinationPath, 'template-unimodule.json'),
path.join(destinationPath, 'unimodule.json')
);
}
}
async _installPackage({pkgName, version, targetDir}) {
try {
await stat(path.join(targetDir, "package.json"));
log.verbose(`Alrady installed: ${pkgName} in version ${version}`);
this._cachedCounter++;
} catch (err) {
if (err.code === "ENOENT") { // "File or directory does not exist"
log.info(`Installing ${pkgName}...`);
log.verbose(`Installing ${pkgName} in version ${version}...`);
await pacote.extract(`${pkgName}@${version}`, targetDir, this._getPacoteOptions());
this._installedCounter++;
} else {
throw err;
}
}
}
async function processPackageTarball(name, version, options) {
const { ref, tmpLocation } = options;
const dest = join(tmpLocation, `${name}@${version}`);
const free = await tarballLocker.acquireOne();
try {
await pacote.extract(ref.flags.isGit ? ref.gitUrl : `${name}@${version}`, dest, {
...token,
registry: REGISTRY_DEFAULT_ADDR,
cache: `${process.env.HOME}/.npm`
});
await new Promise((resolve) => setImmediate(resolve));
let isProjectUsingESM = false;
// Read the package.json file in the extracted tarball
try {
const packageStr = await readFile(join(dest, "package.json"), "utf-8");
const { type = "script", description = "", author = {}, scripts = {} } = JSON.parse(packageStr);
ref.description = description;
ref.author = author;
isProjectUsingESM = type === "module";
ref.flags.hasScript = [...Object.keys(scripts)].some((value) => NPM_SCRIPTS.has(value.toLowerCase()));
const specs = trySpecs(this.spec, this.adaptVersion);
// Remember errors that pertain to accessing the base spec, independent
// of version label.
const baseSpecErrs = new Map();
do {
const spec = specs.shift();
if (!spec) throw new InternalError(`empty spec list`);
try {
const prevErr = baseSpecErrs.get(spec.base);
if (prevErr) throw prevErr;
log(`Trying ${spec.complete}`);
await pacote.extract(spec.complete, this.starterDir, opts);
return;
} catch (err) {
err = ensureError(err);
if (err.code === "ENOENT" && err.path === path.join(this.starterDir, "package.json")) {
// SUCCESS. We don't require a package.json
return;
}
if (specs.length === 0) throw new SpecError(spec.complete, err.message);
// If we can't access the base spec (e.g. git repo or npm package
// doesn't exist), then don't try additional versions of that
// base spec.
if (isErrorWithBaseSpec(spec, err)) baseSpecErrs.set(spec.base, err);
}
} while (true);
} catch (err) {
log.error(err)
return CliExitCodes.ERROR.INPUT
}
const manifestId = new ManifestId(manifest)
const globalPackagePath = path.join(this.globalConfig.globalFolderPath,
manifestId.getPath())
const xpack = new Xpack({ xpackFolderAbsolutePath: config.cwd, log })
const packFullName = manifestId.getFullName()
// Read the cwd package.json
let globalJson = await xpack.hasPackageJson(globalPackagePath)
if (!globalJson) {
log.info(`Installing ${packFullName}...`)
await pacote.extract(config.template, globalPackagePath,
{ cache: cachePath })
log.info('Installing npm dependencies...')
const spawn = new Spawn()
const code = await spawn.executeShellPromise(
'npm install --production --color=false',
{
cwd: globalPackagePath
})
if (code !== 0) {
log.error(`Install dependencies failed (npm returned ${code}).`)
await del(globalPackagePath, { force: true })
return CliExitCodes.ERROR.APPLICATION
}
globalJson = await xpack.hasPackageJson(globalPackagePath)
}
async updateDatabase() {
// Download and extract the database package from npm
logger.info( `Downloading database update to ${this.tempFolder}` )
await remove( this.tempFolder )
await extract( databasePackage, this.tempFolder )
logger.info( 'Hot-patching database module' )
// Disconnect the Shabad OS database connection
await knex.destroy()
// Move across the updated npm database module
await move( this.tempFolder, DATABASE_FOLDER, { overwrite: true } )
// Reimport the database
//! Relies on knex being reinitialised globally
importFresh( '@shabados/database' )
}