@verdaccio/local-storage 14.0.0-next-9.32 → 14.0.0-next-9.34

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.
@@ -165,8 +165,8 @@ var LocalDatabase = class extends _verdaccio_core.pluginUtils.Plugin {
165
165
  } else storagePath = storageRoot;
166
166
  const packageStoragePath = _verdaccio_core.fileUtils.resolveSafePath(storagePath, packageName);
167
167
  debug$1("package path %o", packageStoragePath);
168
- if ((0, lodash_es.isNil)(packageStoragePath)) {
169
- this.logger.error("package-specific storage path is not under the configured storage directory or is invalid");
168
+ if (!(!(0, lodash_es.isNil)(packageStoragePath) && node_path.default.relative(storagePath, packageStoragePath).split(node_path.default.sep).join("/") === packageName)) {
169
+ this.logger.warn({ packageName }, "package @{packageName} has no local storage because its name does not match its folder");
170
170
  throw _verdaccio_core.errorUtils.getInternalError("package-specific storage path is not under the configured storage directory or is invalid");
171
171
  }
172
172
  return new require_local_fs.default(packageStoragePath, this.logger);
@@ -241,6 +241,7 @@ var LocalDatabase = class extends _verdaccio_core.pluginUtils.Plugin {
241
241
  debug$1("token db generated");
242
242
  this.tokenDb = new lowdb.Low(adapter, {});
243
243
  await this.tokenDb.read();
244
+ this.tokenDb.data = Object.assign(Object.create(null), this.tokenDb.data);
244
245
  }
245
246
  return this.tokenDb;
246
247
  }
@@ -1 +1 @@
1
- {"version":3,"file":"local-database.js","names":[],"sources":["../src/local-database.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { escapeRegExp, isNil } from 'lodash-es';\nimport { Low, Memory } from 'lowdb';\nimport { JSONFile } from 'lowdb/node';\nimport path from 'node:path';\n\nimport type { searchUtils } from '@verdaccio/core';\nimport { authUtils, errorUtils, fileUtils, pluginUtils } from '@verdaccio/core';\nimport type { Config, Logger, Token, TokenFilter } from '@verdaccio/types';\n\nimport { searchOnStorage } from './dir-utils';\nimport { mkdirPromise, writeFilePromise } from './fs';\nimport LocalDriver, { noSuchFile } from './local-fs';\nimport type { LocalStorage } from './pkg-utils';\nimport { loadPrivatePackages } from './pkg-utils';\nimport { _dbGenPath } from './utils';\n\nconst TOKEN_DB_NAME = '.token-db.json';\nconst DB_NAME = process.env.VERDACCIO_STORAGE_NAME ?? fileUtils.Files.DatabaseName;\n\nconst debug = buildDebug('verdaccio:plugin:local-storage');\n\nexport const ERROR_DB_LOCKED =\n 'Database is locked, please check error message printed during startup to prevent data loss';\n\ntype Storage = pluginUtils.Storage<{}>;\n\nclass LocalDatabase extends pluginUtils.Plugin<{}> implements Storage {\n private readonly path: string;\n private readonly logger: Logger;\n public readonly config: Config;\n public readonly storages: Map<string, string>;\n public data: LocalStorage | undefined;\n public locked: boolean;\n public tokenDb: Low<Record<string, Token[]>> | null;\n\n public constructor(config: Config, logger: Logger) {\n // TODO: fix double config\n super(config, { config, logger });\n this.tokenDb = null;\n this.config = config;\n this.logger = logger;\n this.locked = false;\n this.data = undefined;\n debug('config path %o', config.configPath);\n this.path = _dbGenPath(DB_NAME, config);\n this.storages = this._getCustomPackageLocalStorages();\n this.logger.info({ path: this.path }, 'local storage path: @{path}');\n debug('plugin storage path %o', this.path);\n }\n\n public async init(): Promise<void> {\n debug('plugin init');\n this.data = await this.fetchLocalPackages();\n debug('local packages loaded');\n await this._sync();\n }\n\n public async getSecret(): Promise<string> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n return Promise.resolve(this.data.secret);\n }\n\n public async setSecret(secret: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n } else {\n this.data.secret = secret;\n }\n\n await this._sync();\n }\n\n public async add(name: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n if (this.data.list.indexOf(name) === -1) {\n this.data.list.push(name);\n debug('the private package %s has been added', name);\n await this._sync();\n } else {\n debug('the private package %s already exist on database', name);\n return Promise.resolve();\n }\n }\n\n /**\n * The field storage could be absolute or relative.\n * If relative, it will be resolved against the config path.\n * If absolute, it will be returned as is.\n **/\n private getStoragePath() {\n const { storage } = this.config;\n if (typeof storage !== 'string') {\n throw new TypeError('storage field is mandatory');\n }\n\n const storagePath = path.isAbsolute(storage)\n ? storage\n : path.normalize(path.join(this.getBaseConfigPath(), storage));\n debug('storage path %o', storagePath);\n return storagePath;\n }\n\n private getBaseConfigPath(): string {\n return path.dirname(this.config.configPath);\n }\n\n /**\n * Filter and only match those values that the query define.\n **/\n public async filterByQuery(results: searchUtils.SearchItemPkg[], query: searchUtils.SearchQuery) {\n // FUTURE: apply new filters, keyword, version, ...\n return results.filter((item: searchUtils.SearchItemPkg) => {\n // Sanitize user input\n const safeText = escapeRegExp(query.text);\n return item?.name?.match(safeText) !== null;\n }) as searchUtils.SearchItemPkg[];\n }\n\n public async getScore(_pkg: searchUtils.SearchItemPkg): Promise<searchUtils.Score> {\n // TODO: there is no particular reason to predefined scores\n // could be improved by using\n return Promise.resolve({\n final: 1,\n detail: {\n maintenance: 0,\n popularity: 1,\n quality: 1,\n },\n });\n }\n\n /**\n *\n * @param query\n * @returns\n */\n public async search(query: searchUtils.SearchQuery): Promise<searchUtils.SearchItem[]> {\n debug('search query to %o', query.text);\n const results: searchUtils.SearchItem[] = [];\n const storagePath = this.getStoragePath();\n const localResults = await searchOnStorage(storagePath, this.storages);\n const packagesOnStorage = await this.filterByQuery(localResults, query);\n debug('packages found %o', packagesOnStorage.length);\n for (const storage of packagesOnStorage) {\n // check if package is listed on the cache private database\n const isPrivate = (this.data as LocalStorage).list.includes(storage.name);\n const score = await this.getScore(storage);\n results.push({\n package: storage,\n verdaccioPrivate: isPrivate,\n verdaccioPkgCached: !isPrivate,\n score,\n });\n }\n return results;\n }\n\n public async remove(name: string): Promise<void> {\n try {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const data = await this.get();\n\n const pkgName = data.indexOf(name);\n if (pkgName !== -1) {\n this.data.list.splice(pkgName, 1);\n debug('package %o has been removed', name);\n }\n await this._sync();\n } catch (err) {\n this.logger.error({ err }, 'remove the private package has failed @{err}');\n throw errorUtils.getInternalError('error remove private package');\n }\n }\n\n public async get(): Promise<any> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const { list } = this.data;\n const totalItems = list?.length;\n debug('get full list of packages (%o) has been fetched', totalItems);\n return Promise.resolve(list);\n }\n\n public getPackageStorage(packageName: string): pluginUtils.StorageHandler {\n // Storage root\n const storageRoot = path.resolve(this.getStoragePath());\n debug('storage root %o', storageRoot);\n\n if (isNil(storageRoot)) {\n this.logger.error('property storage in config.yaml is required for using this plugin');\n throw new Error('property storage in config.yaml is required for using this plugin');\n }\n\n // Storage path based on package access configuration\n const packageAccess = authUtils.getMatchedPackagesSpec(packageName, this.config.packages);\n\n let storagePath;\n if (packageAccess && typeof packageAccess.storage === 'string') {\n storagePath = fileUtils.resolveSafePath(storageRoot, packageAccess.storage);\n debug('storage path %o', storagePath);\n\n if (isNil(storagePath)) {\n this.logger.error(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n } else {\n storagePath = storageRoot;\n }\n\n // Storage path for the package\n const packageStoragePath = fileUtils.resolveSafePath(storagePath, packageName);\n debug('package path %o', packageStoragePath);\n\n if (isNil(packageStoragePath)) {\n this.logger.error(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n\n return new LocalDriver(packageStoragePath as string, this.logger);\n }\n\n public async clean(): Promise<void> {\n await this._sync();\n }\n\n private _getCustomPackageLocalStorages(): Map<string, string> {\n const storages = new Map<string, string>();\n const { packages } = this.config;\n\n if (packages) {\n Object.keys(packages || {}).map((pkg) => {\n const { storage } = packages[pkg];\n if (typeof storage === 'string') {\n const storagePath = path.join(this.getStoragePath(), storage);\n debug('add custom storage for %s on %s', storage, storagePath);\n storages.set(storage, storagePath);\n }\n });\n }\n\n return storages;\n }\n\n private async _sync(): Promise<null> {\n debug('sync database started');\n\n if (this.locked) {\n this.logger.error(ERROR_DB_LOCKED);\n throw new Error(ERROR_DB_LOCKED);\n }\n // Uses sync to prevent ugly race condition\n try {\n const folderName = path.dirname(this.path);\n debug('creating folder %o', folderName);\n await mkdirPromise(folderName, { recursive: true });\n debug('creating folder %o created succeed', folderName);\n } catch (err) {\n this.logger.error({ err }, 'sync create folder has failed with error: @{err}');\n throw err;\n }\n\n try {\n await writeFilePromise(this.path, JSON.stringify(this.data));\n debug('sync write succeeded');\n\n return null;\n } catch (err: any) {\n this.logger.error({ err }, 'sync database file failed: @{err}');\n throw err;\n }\n }\n\n private async fetchLocalPackages(): Promise<LocalStorage> {\n try {\n return await loadPrivatePackages(this.path, this.logger);\n } catch (err: any) {\n // readFileSync is platform specific, macOS, Linux and Windows thrown an error\n // Only recreate if file not found to prevent data loss\n this.logger.info(\n { path: this.path },\n 'no private database found, recreating new one on @{path}'\n );\n if (err.code !== noSuchFile) {\n this.locked = true;\n this.logger.error(\n 'Failed to read package database file, please check the error printed below:\\n',\n `File Path: ${this.path}\\n\\n ${err.message}`\n );\n }\n // if no database is found we set empty placeholders\n return { list: [], secret: '' };\n }\n }\n\n private async getTokenDb(): Promise<Low<Record<string, Token[]>>> {\n if (!this.tokenDb) {\n debug('token database is not defined');\n let adapter;\n if (process.env.NODE_ENV === 'test') {\n debug('token memory adapter');\n adapter = new Memory<Record<string, Token[]>>();\n } else {\n debug('token async adapter');\n const pathDb = _dbGenPath(TOKEN_DB_NAME, this.config);\n adapter = new JSONFile<Record<string, Token[]>>(pathDb);\n }\n debug('token db generated');\n this.tokenDb = new Low<Record<string, Token[]>>(adapter, {});\n await this.tokenDb.read();\n }\n\n return this.tokenDb;\n }\n\n public async saveToken(token: Token): Promise<void> {\n debug('token key %o', token.key);\n const db = await this.getTokenDb();\n const userData = db.data[token.user];\n debug('user data %o', userData);\n if (isNil(userData)) {\n db.data[token.user] = [token];\n debug('token user %o new database', token.user);\n } else {\n db.data[token.user].push(token);\n }\n await db.write();\n debug('data %o', db.data);\n debug('token saved %o', token.user);\n }\n\n public async deleteToken(user: string, tokenKey: string): Promise<void> {\n const db = await this.getTokenDb();\n const userTokens = db.data[user];\n if (isNil(userTokens)) {\n throw new Error('user not found');\n }\n debug('tokens %o - %o', userTokens, userTokens.length);\n db.data[user] = userTokens.filter(({ key }) => {\n debug('key %o', key);\n return key !== tokenKey;\n });\n await db.write();\n debug('removed tokens key %o', tokenKey);\n }\n\n public async readTokens(filter: TokenFilter): Promise<Token[]> {\n const { user } = filter;\n debug('read tokens with %o', user);\n const db = await this.getTokenDb();\n const tokens = db.data[user];\n return tokens || [];\n }\n}\n\nexport default LocalDatabase;\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,IAAM,gBAAgB;AACtB,IAAM,UAAU,QAAQ,IAAI,0BAA0B,gBAAA,UAAU,MAAM;AAEtE,IAAM,WAAA,GAAQ,MAAA,QAAA,CAAW,gCAAgC;AAEzD,IAAa,kBACX;AAIF,IAAM,gBAAN,cAA4B,gBAAA,YAAY,OAA8B;CACpE;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB;EAEjD,MAAM,QAAQ;GAAE;GAAQ;EAAO,CAAC;EAChC,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,KAAA;EACZ,QAAM,kBAAkB,OAAO,UAAU;EACzC,KAAK,OAAO,cAAA,WAAW,SAAS,MAAM;EACtC,KAAK,WAAW,KAAK,+BAA+B;EACpD,KAAK,OAAO,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,6BAA6B;EACnE,QAAM,0BAA0B,KAAK,IAAI;CAC3C;CAEA,MAAa,OAAsB;EACjC,QAAM,aAAa;EACnB,KAAK,OAAO,MAAM,KAAK,mBAAmB;EAC1C,QAAM,uBAAuB;EAC7B,MAAM,KAAK,MAAM;CACnB;CAEA,MAAa,YAA6B;EAC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;CAEA,MAAa,UAAU,OAA6B;EAClD,QAAM,gBAAgB,MAAM,GAAG;EAC/B,MAAM,KAAK,MAAM,KAAK,WAAW;EACjC,MAAM,WAAW,GAAG,KAAK,MAAM;EAC/B,QAAM,gBAAgB,QAAQ;EAC9B,KAAA,GAAI,UAAA,MAAA,CAAM,QAAQ,GAAG;GACnB,GAAG,KAAK,MAAM,QAAQ,CAAC,KAAK;GAC5B,QAAM,8BAA8B,MAAM,IAAI;EAChD,OACE,GAAG,KAAK,MAAM,KAAK,CAAC,KAAK,KAAK;EAEhC,MAAM,GAAG,MAAM;EACf,QAAM,WAAW,GAAG,IAAI;EACxB,QAAM,kBAAkB,MAAM,IAAI;CACpC;CAEA,MAAa,YAAY,MAAc,UAAiC;EACtE,MAAM,KAAK,MAAM,KAAK,WAAW;EACjC,MAAM,aAAa,GAAG,KAAK;EAC3B,KAAA,GAAI,UAAA,MAAA,CAAM,UAAU,GAClB,MAAM,IAAI,MAAM,gBAAgB;EAElC,QAAM,kBAAkB,YAAY,WAAW,MAAM;EACrD,GAAG,KAAK,QAAQ,WAAW,QAAQ,EAAE,UAAU;GAC7C,QAAM,UAAU,GAAG;GACnB,OAAO,QAAQ;EACjB,CAAC;EACD,MAAM,GAAG,MAAM;EACf,QAAM,yBAAyB,QAAQ;CACzC;CAEA,MAAa,WAAW,QAAuC;EAC7D,MAAM,EAAE,SAAS;EACjB,QAAM,uBAAuB,IAAI;EAGjC,QADe,MADE,KAAK,WAAW,EAAA,CACf,KAAK,SACN,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"local-database.js","names":[],"sources":["../src/local-database.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { escapeRegExp, isNil } from 'lodash-es';\nimport { Low, Memory } from 'lowdb';\nimport { JSONFile } from 'lowdb/node';\nimport path from 'node:path';\n\nimport type { searchUtils } from '@verdaccio/core';\nimport { authUtils, errorUtils, fileUtils, pluginUtils } from '@verdaccio/core';\nimport type { Config, Logger, Token, TokenFilter } from '@verdaccio/types';\n\nimport { searchOnStorage } from './dir-utils';\nimport { mkdirPromise, writeFilePromise } from './fs';\nimport LocalDriver, { noSuchFile } from './local-fs';\nimport type { LocalStorage } from './pkg-utils';\nimport { loadPrivatePackages } from './pkg-utils';\nimport { _dbGenPath } from './utils';\n\nconst TOKEN_DB_NAME = '.token-db.json';\nconst DB_NAME = process.env.VERDACCIO_STORAGE_NAME ?? fileUtils.Files.DatabaseName;\n\nconst debug = buildDebug('verdaccio:plugin:local-storage');\n\nexport const ERROR_DB_LOCKED =\n 'Database is locked, please check error message printed during startup to prevent data loss';\n\ntype Storage = pluginUtils.Storage<{}>;\n\nclass LocalDatabase extends pluginUtils.Plugin<{}> implements Storage {\n private readonly path: string;\n private readonly logger: Logger;\n public readonly config: Config;\n public readonly storages: Map<string, string>;\n public data: LocalStorage | undefined;\n public locked: boolean;\n public tokenDb: Low<Record<string, Token[]>> | null;\n\n public constructor(config: Config, logger: Logger) {\n // TODO: fix double config\n super(config, { config, logger });\n this.tokenDb = null;\n this.config = config;\n this.logger = logger;\n this.locked = false;\n this.data = undefined;\n debug('config path %o', config.configPath);\n this.path = _dbGenPath(DB_NAME, config);\n this.storages = this._getCustomPackageLocalStorages();\n this.logger.info({ path: this.path }, 'local storage path: @{path}');\n debug('plugin storage path %o', this.path);\n }\n\n public async init(): Promise<void> {\n debug('plugin init');\n this.data = await this.fetchLocalPackages();\n debug('local packages loaded');\n await this._sync();\n }\n\n public async getSecret(): Promise<string> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n return Promise.resolve(this.data.secret);\n }\n\n public async setSecret(secret: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n } else {\n this.data.secret = secret;\n }\n\n await this._sync();\n }\n\n public async add(name: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n if (this.data.list.indexOf(name) === -1) {\n this.data.list.push(name);\n debug('the private package %s has been added', name);\n await this._sync();\n } else {\n debug('the private package %s already exist on database', name);\n return Promise.resolve();\n }\n }\n\n /**\n * The field storage could be absolute or relative.\n * If relative, it will be resolved against the config path.\n * If absolute, it will be returned as is.\n **/\n private getStoragePath() {\n const { storage } = this.config;\n if (typeof storage !== 'string') {\n throw new TypeError('storage field is mandatory');\n }\n\n const storagePath = path.isAbsolute(storage)\n ? storage\n : path.normalize(path.join(this.getBaseConfigPath(), storage));\n debug('storage path %o', storagePath);\n return storagePath;\n }\n\n private getBaseConfigPath(): string {\n return path.dirname(this.config.configPath);\n }\n\n /**\n * Filter and only match those values that the query define.\n **/\n public async filterByQuery(results: searchUtils.SearchItemPkg[], query: searchUtils.SearchQuery) {\n // FUTURE: apply new filters, keyword, version, ...\n return results.filter((item: searchUtils.SearchItemPkg) => {\n // Sanitize user input\n const safeText = escapeRegExp(query.text);\n return item?.name?.match(safeText) !== null;\n }) as searchUtils.SearchItemPkg[];\n }\n\n public async getScore(_pkg: searchUtils.SearchItemPkg): Promise<searchUtils.Score> {\n // TODO: there is no particular reason to predefined scores\n // could be improved by using\n return Promise.resolve({\n final: 1,\n detail: {\n maintenance: 0,\n popularity: 1,\n quality: 1,\n },\n });\n }\n\n /**\n *\n * @param query\n * @returns\n */\n public async search(query: searchUtils.SearchQuery): Promise<searchUtils.SearchItem[]> {\n debug('search query to %o', query.text);\n const results: searchUtils.SearchItem[] = [];\n const storagePath = this.getStoragePath();\n const localResults = await searchOnStorage(storagePath, this.storages);\n const packagesOnStorage = await this.filterByQuery(localResults, query);\n debug('packages found %o', packagesOnStorage.length);\n for (const storage of packagesOnStorage) {\n // check if package is listed on the cache private database\n const isPrivate = (this.data as LocalStorage).list.includes(storage.name);\n const score = await this.getScore(storage);\n results.push({\n package: storage,\n verdaccioPrivate: isPrivate,\n verdaccioPkgCached: !isPrivate,\n score,\n });\n }\n return results;\n }\n\n public async remove(name: string): Promise<void> {\n try {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const data = await this.get();\n\n const pkgName = data.indexOf(name);\n if (pkgName !== -1) {\n this.data.list.splice(pkgName, 1);\n debug('package %o has been removed', name);\n }\n await this._sync();\n } catch (err) {\n this.logger.error({ err }, 'remove the private package has failed @{err}');\n throw errorUtils.getInternalError('error remove private package');\n }\n }\n\n public async get(): Promise<any> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const { list } = this.data;\n const totalItems = list?.length;\n debug('get full list of packages (%o) has been fetched', totalItems);\n return Promise.resolve(list);\n }\n\n public getPackageStorage(packageName: string): pluginUtils.StorageHandler {\n // Storage root\n const storageRoot = path.resolve(this.getStoragePath());\n debug('storage root %o', storageRoot);\n\n if (isNil(storageRoot)) {\n this.logger.error('property storage in config.yaml is required for using this plugin');\n throw new Error('property storage in config.yaml is required for using this plugin');\n }\n\n // Storage path based on package access configuration\n const packageAccess = authUtils.getMatchedPackagesSpec(packageName, this.config.packages);\n\n let storagePath;\n if (packageAccess && typeof packageAccess.storage === 'string') {\n storagePath = fileUtils.resolveSafePath(storageRoot, packageAccess.storage);\n debug('storage path %o', storagePath);\n\n if (isNil(storagePath)) {\n this.logger.error(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n } else {\n storagePath = storageRoot;\n }\n\n // Storage path for the package\n const packageStoragePath = fileUtils.resolveSafePath(storagePath, packageName);\n debug('package path %o', packageStoragePath);\n\n // the folder must be the name itself, not a normalized form of it\n const isExactFolder =\n !isNil(packageStoragePath) &&\n path.relative(storagePath, packageStoragePath).split(path.sep).join('/') === packageName;\n\n if (!isExactFolder) {\n this.logger.warn(\n { packageName },\n 'package @{packageName} has no local storage because its name does not match its folder'\n );\n throw errorUtils.getInternalError(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n\n return new LocalDriver(packageStoragePath as string, this.logger);\n }\n\n public async clean(): Promise<void> {\n await this._sync();\n }\n\n private _getCustomPackageLocalStorages(): Map<string, string> {\n const storages = new Map<string, string>();\n const { packages } = this.config;\n\n if (packages) {\n Object.keys(packages || {}).map((pkg) => {\n const { storage } = packages[pkg];\n if (typeof storage === 'string') {\n const storagePath = path.join(this.getStoragePath(), storage);\n debug('add custom storage for %s on %s', storage, storagePath);\n storages.set(storage, storagePath);\n }\n });\n }\n\n return storages;\n }\n\n private async _sync(): Promise<null> {\n debug('sync database started');\n\n if (this.locked) {\n this.logger.error(ERROR_DB_LOCKED);\n throw new Error(ERROR_DB_LOCKED);\n }\n // Uses sync to prevent ugly race condition\n try {\n const folderName = path.dirname(this.path);\n debug('creating folder %o', folderName);\n await mkdirPromise(folderName, { recursive: true });\n debug('creating folder %o created succeed', folderName);\n } catch (err) {\n this.logger.error({ err }, 'sync create folder has failed with error: @{err}');\n throw err;\n }\n\n try {\n await writeFilePromise(this.path, JSON.stringify(this.data));\n debug('sync write succeeded');\n\n return null;\n } catch (err: any) {\n this.logger.error({ err }, 'sync database file failed: @{err}');\n throw err;\n }\n }\n\n private async fetchLocalPackages(): Promise<LocalStorage> {\n try {\n return await loadPrivatePackages(this.path, this.logger);\n } catch (err: any) {\n // readFileSync is platform specific, macOS, Linux and Windows thrown an error\n // Only recreate if file not found to prevent data loss\n this.logger.info(\n { path: this.path },\n 'no private database found, recreating new one on @{path}'\n );\n if (err.code !== noSuchFile) {\n this.locked = true;\n this.logger.error(\n 'Failed to read package database file, please check the error printed below:\\n',\n `File Path: ${this.path}\\n\\n ${err.message}`\n );\n }\n // if no database is found we set empty placeholders\n return { list: [], secret: '' };\n }\n }\n\n private async getTokenDb(): Promise<Low<Record<string, Token[]>>> {\n if (!this.tokenDb) {\n debug('token database is not defined');\n let adapter;\n if (process.env.NODE_ENV === 'test') {\n debug('token memory adapter');\n adapter = new Memory<Record<string, Token[]>>();\n } else {\n debug('token async adapter');\n const pathDb = _dbGenPath(TOKEN_DB_NAME, this.config);\n adapter = new JSONFile<Record<string, Token[]>>(pathDb);\n }\n debug('token db generated');\n this.tokenDb = new Low<Record<string, Token[]>>(adapter, {});\n await this.tokenDb.read();\n // keyed by username: names like `constructor` or `__proto__` must not hit the prototype\n this.tokenDb.data = Object.assign(Object.create(null), this.tokenDb.data);\n }\n\n return this.tokenDb;\n }\n\n public async saveToken(token: Token): Promise<void> {\n debug('token key %o', token.key);\n const db = await this.getTokenDb();\n const userData = db.data[token.user];\n debug('user data %o', userData);\n if (isNil(userData)) {\n db.data[token.user] = [token];\n debug('token user %o new database', token.user);\n } else {\n db.data[token.user].push(token);\n }\n await db.write();\n debug('data %o', db.data);\n debug('token saved %o', token.user);\n }\n\n public async deleteToken(user: string, tokenKey: string): Promise<void> {\n const db = await this.getTokenDb();\n const userTokens = db.data[user];\n if (isNil(userTokens)) {\n throw new Error('user not found');\n }\n debug('tokens %o - %o', userTokens, userTokens.length);\n db.data[user] = userTokens.filter(({ key }) => {\n debug('key %o', key);\n return key !== tokenKey;\n });\n await db.write();\n debug('removed tokens key %o', tokenKey);\n }\n\n public async readTokens(filter: TokenFilter): Promise<Token[]> {\n const { user } = filter;\n debug('read tokens with %o', user);\n const db = await this.getTokenDb();\n const tokens = db.data[user];\n return tokens || [];\n }\n}\n\nexport default LocalDatabase;\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,IAAM,gBAAgB;AACtB,IAAM,UAAU,QAAQ,IAAI,0BAA0B,gBAAA,UAAU,MAAM;AAEtE,IAAM,WAAA,GAAQ,MAAA,QAAA,CAAW,gCAAgC;AAEzD,IAAa,kBACX;AAIF,IAAM,gBAAN,cAA4B,gBAAA,YAAY,OAA8B;CACpE;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB;EAEjD,MAAM,QAAQ;GAAE;GAAQ;EAAO,CAAC;EAChC,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,KAAA;EACZ,QAAM,kBAAkB,OAAO,UAAU;EACzC,KAAK,OAAO,cAAA,WAAW,SAAS,MAA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AO,QAAQ;EACjB,CAAC;EACD,MAAM,GAAG,MAAM;EACf,QAAM,yBAAyB,QAAQ;CACzC;CAEA,MAAa,WAAW,QAAuC;EAC7D,MAAM,EAAE,SAAS;EACjB,QAAM,uBAAuB,IAAI;EAGjC,QADe,MADE,KAAK,WAAW,EAAA,CACf,KAAK,SACN,CAAC;CACpB;AACF"}
@@ -162,8 +162,8 @@ var LocalDatabase = class extends pluginUtils.Plugin {
162
162
  } else storagePath = storageRoot;
163
163
  const packageStoragePath = fileUtils.resolveSafePath(storagePath, packageName);
164
164
  debug("package path %o", packageStoragePath);
165
- if (isNil(packageStoragePath)) {
166
- this.logger.error("package-specific storage path is not under the configured storage directory or is invalid");
165
+ if (!(!isNil(packageStoragePath) && path.relative(storagePath, packageStoragePath).split(path.sep).join("/") === packageName)) {
166
+ this.logger.warn({ packageName }, "package @{packageName} has no local storage because its name does not match its folder");
167
167
  throw errorUtils.getInternalError("package-specific storage path is not under the configured storage directory or is invalid");
168
168
  }
169
169
  return new LocalFS(packageStoragePath, this.logger);
@@ -238,6 +238,7 @@ var LocalDatabase = class extends pluginUtils.Plugin {
238
238
  debug("token db generated");
239
239
  this.tokenDb = new Low(adapter, {});
240
240
  await this.tokenDb.read();
241
+ this.tokenDb.data = Object.assign(Object.create(null), this.tokenDb.data);
241
242
  }
242
243
  return this.tokenDb;
243
244
  }
@@ -1 +1 @@
1
- {"version":3,"file":"local-database.mjs","names":[],"sources":["../src/local-database.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { escapeRegExp, isNil } from 'lodash-es';\nimport { Low, Memory } from 'lowdb';\nimport { JSONFile } from 'lowdb/node';\nimport path from 'node:path';\n\nimport type { searchUtils } from '@verdaccio/core';\nimport { authUtils, errorUtils, fileUtils, pluginUtils } from '@verdaccio/core';\nimport type { Config, Logger, Token, TokenFilter } from '@verdaccio/types';\n\nimport { searchOnStorage } from './dir-utils';\nimport { mkdirPromise, writeFilePromise } from './fs';\nimport LocalDriver, { noSuchFile } from './local-fs';\nimport type { LocalStorage } from './pkg-utils';\nimport { loadPrivatePackages } from './pkg-utils';\nimport { _dbGenPath } from './utils';\n\nconst TOKEN_DB_NAME = '.token-db.json';\nconst DB_NAME = process.env.VERDACCIO_STORAGE_NAME ?? fileUtils.Files.DatabaseName;\n\nconst debug = buildDebug('verdaccio:plugin:local-storage');\n\nexport const ERROR_DB_LOCKED =\n 'Database is locked, please check error message printed during startup to prevent data loss';\n\ntype Storage = pluginUtils.Storage<{}>;\n\nclass LocalDatabase extends pluginUtils.Plugin<{}> implements Storage {\n private readonly path: string;\n private readonly logger: Logger;\n public readonly config: Config;\n public readonly storages: Map<string, string>;\n public data: LocalStorage | undefined;\n public locked: boolean;\n public tokenDb: Low<Record<string, Token[]>> | null;\n\n public constructor(config: Config, logger: Logger) {\n // TODO: fix double config\n super(config, { config, logger });\n this.tokenDb = null;\n this.config = config;\n this.logger = logger;\n this.locked = false;\n this.data = undefined;\n debug('config path %o', config.configPath);\n this.path = _dbGenPath(DB_NAME, config);\n this.storages = this._getCustomPackageLocalStorages();\n this.logger.info({ path: this.path }, 'local storage path: @{path}');\n debug('plugin storage path %o', this.path);\n }\n\n public async init(): Promise<void> {\n debug('plugin init');\n this.data = await this.fetchLocalPackages();\n debug('local packages loaded');\n await this._sync();\n }\n\n public async getSecret(): Promise<string> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n return Promise.resolve(this.data.secret);\n }\n\n public async setSecret(secret: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n } else {\n this.data.secret = secret;\n }\n\n await this._sync();\n }\n\n public async add(name: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n if (this.data.list.indexOf(name) === -1) {\n this.data.list.push(name);\n debug('the private package %s has been added', name);\n await this._sync();\n } else {\n debug('the private package %s already exist on database', name);\n return Promise.resolve();\n }\n }\n\n /**\n * The field storage could be absolute or relative.\n * If relative, it will be resolved against the config path.\n * If absolute, it will be returned as is.\n **/\n private getStoragePath() {\n const { storage } = this.config;\n if (typeof storage !== 'string') {\n throw new TypeError('storage field is mandatory');\n }\n\n const storagePath = path.isAbsolute(storage)\n ? storage\n : path.normalize(path.join(this.getBaseConfigPath(), storage));\n debug('storage path %o', storagePath);\n return storagePath;\n }\n\n private getBaseConfigPath(): string {\n return path.dirname(this.config.configPath);\n }\n\n /**\n * Filter and only match those values that the query define.\n **/\n public async filterByQuery(results: searchUtils.SearchItemPkg[], query: searchUtils.SearchQuery) {\n // FUTURE: apply new filters, keyword, version, ...\n return results.filter((item: searchUtils.SearchItemPkg) => {\n // Sanitize user input\n const safeText = escapeRegExp(query.text);\n return item?.name?.match(safeText) !== null;\n }) as searchUtils.SearchItemPkg[];\n }\n\n public async getScore(_pkg: searchUtils.SearchItemPkg): Promise<searchUtils.Score> {\n // TODO: there is no particular reason to predefined scores\n // could be improved by using\n return Promise.resolve({\n final: 1,\n detail: {\n maintenance: 0,\n popularity: 1,\n quality: 1,\n },\n });\n }\n\n /**\n *\n * @param query\n * @returns\n */\n public async search(query: searchUtils.SearchQuery): Promise<searchUtils.SearchItem[]> {\n debug('search query to %o', query.text);\n const results: searchUtils.SearchItem[] = [];\n const storagePath = this.getStoragePath();\n const localResults = await searchOnStorage(storagePath, this.storages);\n const packagesOnStorage = await this.filterByQuery(localResults, query);\n debug('packages found %o', packagesOnStorage.length);\n for (const storage of packagesOnStorage) {\n // check if package is listed on the cache private database\n const isPrivate = (this.data as LocalStorage).list.includes(storage.name);\n const score = await this.getScore(storage);\n results.push({\n package: storage,\n verdaccioPrivate: isPrivate,\n verdaccioPkgCached: !isPrivate,\n score,\n });\n }\n return results;\n }\n\n public async remove(name: string): Promise<void> {\n try {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const data = await this.get();\n\n const pkgName = data.indexOf(name);\n if (pkgName !== -1) {\n this.data.list.splice(pkgName, 1);\n debug('package %o has been removed', name);\n }\n await this._sync();\n } catch (err) {\n this.logger.error({ err }, 'remove the private package has failed @{err}');\n throw errorUtils.getInternalError('error remove private package');\n }\n }\n\n public async get(): Promise<any> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const { list } = this.data;\n const totalItems = list?.length;\n debug('get full list of packages (%o) has been fetched', totalItems);\n return Promise.resolve(list);\n }\n\n public getPackageStorage(packageName: string): pluginUtils.StorageHandler {\n // Storage root\n const storageRoot = path.resolve(this.getStoragePath());\n debug('storage root %o', storageRoot);\n\n if (isNil(storageRoot)) {\n this.logger.error('property storage in config.yaml is required for using this plugin');\n throw new Error('property storage in config.yaml is required for using this plugin');\n }\n\n // Storage path based on package access configuration\n const packageAccess = authUtils.getMatchedPackagesSpec(packageName, this.config.packages);\n\n let storagePath;\n if (packageAccess && typeof packageAccess.storage === 'string') {\n storagePath = fileUtils.resolveSafePath(storageRoot, packageAccess.storage);\n debug('storage path %o', storagePath);\n\n if (isNil(storagePath)) {\n this.logger.error(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n } else {\n storagePath = storageRoot;\n }\n\n // Storage path for the package\n const packageStoragePath = fileUtils.resolveSafePath(storagePath, packageName);\n debug('package path %o', packageStoragePath);\n\n if (isNil(packageStoragePath)) {\n this.logger.error(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n\n return new LocalDriver(packageStoragePath as string, this.logger);\n }\n\n public async clean(): Promise<void> {\n await this._sync();\n }\n\n private _getCustomPackageLocalStorages(): Map<string, string> {\n const storages = new Map<string, string>();\n const { packages } = this.config;\n\n if (packages) {\n Object.keys(packages || {}).map((pkg) => {\n const { storage } = packages[pkg];\n if (typeof storage === 'string') {\n const storagePath = path.join(this.getStoragePath(), storage);\n debug('add custom storage for %s on %s', storage, storagePath);\n storages.set(storage, storagePath);\n }\n });\n }\n\n return storages;\n }\n\n private async _sync(): Promise<null> {\n debug('sync database started');\n\n if (this.locked) {\n this.logger.error(ERROR_DB_LOCKED);\n throw new Error(ERROR_DB_LOCKED);\n }\n // Uses sync to prevent ugly race condition\n try {\n const folderName = path.dirname(this.path);\n debug('creating folder %o', folderName);\n await mkdirPromise(folderName, { recursive: true });\n debug('creating folder %o created succeed', folderName);\n } catch (err) {\n this.logger.error({ err }, 'sync create folder has failed with error: @{err}');\n throw err;\n }\n\n try {\n await writeFilePromise(this.path, JSON.stringify(this.data));\n debug('sync write succeeded');\n\n return null;\n } catch (err: any) {\n this.logger.error({ err }, 'sync database file failed: @{err}');\n throw err;\n }\n }\n\n private async fetchLocalPackages(): Promise<LocalStorage> {\n try {\n return await loadPrivatePackages(this.path, this.logger);\n } catch (err: any) {\n // readFileSync is platform specific, macOS, Linux and Windows thrown an error\n // Only recreate if file not found to prevent data loss\n this.logger.info(\n { path: this.path },\n 'no private database found, recreating new one on @{path}'\n );\n if (err.code !== noSuchFile) {\n this.locked = true;\n this.logger.error(\n 'Failed to read package database file, please check the error printed below:\\n',\n `File Path: ${this.path}\\n\\n ${err.message}`\n );\n }\n // if no database is found we set empty placeholders\n return { list: [], secret: '' };\n }\n }\n\n private async getTokenDb(): Promise<Low<Record<string, Token[]>>> {\n if (!this.tokenDb) {\n debug('token database is not defined');\n let adapter;\n if (process.env.NODE_ENV === 'test') {\n debug('token memory adapter');\n adapter = new Memory<Record<string, Token[]>>();\n } else {\n debug('token async adapter');\n const pathDb = _dbGenPath(TOKEN_DB_NAME, this.config);\n adapter = new JSONFile<Record<string, Token[]>>(pathDb);\n }\n debug('token db generated');\n this.tokenDb = new Low<Record<string, Token[]>>(adapter, {});\n await this.tokenDb.read();\n }\n\n return this.tokenDb;\n }\n\n public async saveToken(token: Token): Promise<void> {\n debug('token key %o', token.key);\n const db = await this.getTokenDb();\n const userData = db.data[token.user];\n debug('user data %o', userData);\n if (isNil(userData)) {\n db.data[token.user] = [token];\n debug('token user %o new database', token.user);\n } else {\n db.data[token.user].push(token);\n }\n await db.write();\n debug('data %o', db.data);\n debug('token saved %o', token.user);\n }\n\n public async deleteToken(user: string, tokenKey: string): Promise<void> {\n const db = await this.getTokenDb();\n const userTokens = db.data[user];\n if (isNil(userTokens)) {\n throw new Error('user not found');\n }\n debug('tokens %o - %o', userTokens, userTokens.length);\n db.data[user] = userTokens.filter(({ key }) => {\n debug('key %o', key);\n return key !== tokenKey;\n });\n await db.write();\n debug('removed tokens key %o', tokenKey);\n }\n\n public async readTokens(filter: TokenFilter): Promise<Token[]> {\n const { user } = filter;\n debug('read tokens with %o', user);\n const db = await this.getTokenDb();\n const tokens = db.data[user];\n return tokens || [];\n }\n}\n\nexport default LocalDatabase;\n"],"mappings":";;;;;;;;;;;;AAiBA,IAAM,gBAAgB;AACtB,IAAM,UAAU,QAAQ,IAAI,0BAA0B,UAAU,MAAM;AAEtE,IAAM,QAAQ,WAAW,gCAAgC;AAEzD,IAAa,kBACX;AAIF,IAAM,gBAAN,cAA4B,YAAY,OAA8B;CACpE;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB;EAEjD,MAAM,QAAQ;GAAE;GAAQ;EAAO,CAAC;EAChC,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,KAAA;EACZ,MAAM,kBAAkB,OAAO,UAAU;EACzC,KAAK,OAAO,WAAW,SAAS,MAAM;EACtC,KAAK,WAAW,KAAK,+BAA+B;EACpD,KAAK,OAAO,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,6BAA6B;EACnE,MAAM,0BAA0B,KAAK,IAAI;CAC3C;CAEA,MAAa,OAAsB;EACjC,MAAM,aAAa;EACnB,KAAK,OAAO,MAAM,KAAK,mBAAmB;EAC1C,MAAM,uBAAuB;EAC7B,MAAM,KAAK,MAAM;CACnB;CAEA,MAAa,YAA6B;EACxC,IAAI,OAAO,KAAK,SAAS,aACvB,M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8BAA8B,MAAM,IAAI;EAChD,OACE,GAAG,KAAK,MAAM,KAAK,CAAC,KAAK,KAAK;EAEhC,MAAM,GAAG,MAAM;EACf,MAAM,WAAW,GAAG,IAAI;EACxB,MAAM,kBAAkB,MAAM,IAAI;CACpC;CAEA,MAAa,YAAY,MAAc,UAAiC;EACtE,MAAM,KAAK,MAAM,KAAK,WAAW;EACjC,MAAM,aAAa,GAAG,KAAK;EAC3B,IAAI,MAAM,UAAU,GAClB,MAAM,IAAI,MAAM,gBAAgB;EAElC,MAAM,kBAAkB,YAAY,WAAW,MAAM;EACrD,GAAG,KAAK,QAAQ,WAAW,QAAQ,EAAE,UAAU;GAC7C,MAAM,UAAU,GAAG;GACnB,OAAO,QAAQ;EACjB,CAAC;EACD,MAAM,GAAG,MAAM;EACf,MAAM,yBAAyB,QAAQ;CACzC;CAEA,MAAa,WAAW,QAAuC;EAC7D,MAAM,EAAE,SAAS;EACjB,MAAM,uBAAuB,IAAI;EAGjC,QADe,MADE,KAAK,WAAW,EAAA,CACf,KAAK,SACN,CAAC;CACpB;AACF"}
1
+ {"version":3,"file":"local-database.mjs","names":[],"sources":["../src/local-database.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport { escapeRegExp, isNil } from 'lodash-es';\nimport { Low, Memory } from 'lowdb';\nimport { JSONFile } from 'lowdb/node';\nimport path from 'node:path';\n\nimport type { searchUtils } from '@verdaccio/core';\nimport { authUtils, errorUtils, fileUtils, pluginUtils } from '@verdaccio/core';\nimport type { Config, Logger, Token, TokenFilter } from '@verdaccio/types';\n\nimport { searchOnStorage } from './dir-utils';\nimport { mkdirPromise, writeFilePromise } from './fs';\nimport LocalDriver, { noSuchFile } from './local-fs';\nimport type { LocalStorage } from './pkg-utils';\nimport { loadPrivatePackages } from './pkg-utils';\nimport { _dbGenPath } from './utils';\n\nconst TOKEN_DB_NAME = '.token-db.json';\nconst DB_NAME = process.env.VERDACCIO_STORAGE_NAME ?? fileUtils.Files.DatabaseName;\n\nconst debug = buildDebug('verdaccio:plugin:local-storage');\n\nexport const ERROR_DB_LOCKED =\n 'Database is locked, please check error message printed during startup to prevent data loss';\n\ntype Storage = pluginUtils.Storage<{}>;\n\nclass LocalDatabase extends pluginUtils.Plugin<{}> implements Storage {\n private readonly path: string;\n private readonly logger: Logger;\n public readonly config: Config;\n public readonly storages: Map<string, string>;\n public data: LocalStorage | undefined;\n public locked: boolean;\n public tokenDb: Low<Record<string, Token[]>> | null;\n\n public constructor(config: Config, logger: Logger) {\n // TODO: fix double config\n super(config, { config, logger });\n this.tokenDb = null;\n this.config = config;\n this.logger = logger;\n this.locked = false;\n this.data = undefined;\n debug('config path %o', config.configPath);\n this.path = _dbGenPath(DB_NAME, config);\n this.storages = this._getCustomPackageLocalStorages();\n this.logger.info({ path: this.path }, 'local storage path: @{path}');\n debug('plugin storage path %o', this.path);\n }\n\n public async init(): Promise<void> {\n debug('plugin init');\n this.data = await this.fetchLocalPackages();\n debug('local packages loaded');\n await this._sync();\n }\n\n public async getSecret(): Promise<string> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n return Promise.resolve(this.data.secret);\n }\n\n public async setSecret(secret: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n } else {\n this.data.secret = secret;\n }\n\n await this._sync();\n }\n\n public async add(name: string): Promise<void> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n if (this.data.list.indexOf(name) === -1) {\n this.data.list.push(name);\n debug('the private package %s has been added', name);\n await this._sync();\n } else {\n debug('the private package %s already exist on database', name);\n return Promise.resolve();\n }\n }\n\n /**\n * The field storage could be absolute or relative.\n * If relative, it will be resolved against the config path.\n * If absolute, it will be returned as is.\n **/\n private getStoragePath() {\n const { storage } = this.config;\n if (typeof storage !== 'string') {\n throw new TypeError('storage field is mandatory');\n }\n\n const storagePath = path.isAbsolute(storage)\n ? storage\n : path.normalize(path.join(this.getBaseConfigPath(), storage));\n debug('storage path %o', storagePath);\n return storagePath;\n }\n\n private getBaseConfigPath(): string {\n return path.dirname(this.config.configPath);\n }\n\n /**\n * Filter and only match those values that the query define.\n **/\n public async filterByQuery(results: searchUtils.SearchItemPkg[], query: searchUtils.SearchQuery) {\n // FUTURE: apply new filters, keyword, version, ...\n return results.filter((item: searchUtils.SearchItemPkg) => {\n // Sanitize user input\n const safeText = escapeRegExp(query.text);\n return item?.name?.match(safeText) !== null;\n }) as searchUtils.SearchItemPkg[];\n }\n\n public async getScore(_pkg: searchUtils.SearchItemPkg): Promise<searchUtils.Score> {\n // TODO: there is no particular reason to predefined scores\n // could be improved by using\n return Promise.resolve({\n final: 1,\n detail: {\n maintenance: 0,\n popularity: 1,\n quality: 1,\n },\n });\n }\n\n /**\n *\n * @param query\n * @returns\n */\n public async search(query: searchUtils.SearchQuery): Promise<searchUtils.SearchItem[]> {\n debug('search query to %o', query.text);\n const results: searchUtils.SearchItem[] = [];\n const storagePath = this.getStoragePath();\n const localResults = await searchOnStorage(storagePath, this.storages);\n const packagesOnStorage = await this.filterByQuery(localResults, query);\n debug('packages found %o', packagesOnStorage.length);\n for (const storage of packagesOnStorage) {\n // check if package is listed on the cache private database\n const isPrivate = (this.data as LocalStorage).list.includes(storage.name);\n const score = await this.getScore(storage);\n results.push({\n package: storage,\n verdaccioPrivate: isPrivate,\n verdaccioPkgCached: !isPrivate,\n score,\n });\n }\n return results;\n }\n\n public async remove(name: string): Promise<void> {\n try {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const data = await this.get();\n\n const pkgName = data.indexOf(name);\n if (pkgName !== -1) {\n this.data.list.splice(pkgName, 1);\n debug('package %o has been removed', name);\n }\n await this._sync();\n } catch (err) {\n this.logger.error({ err }, 'remove the private package has failed @{err}');\n throw errorUtils.getInternalError('error remove private package');\n }\n }\n\n public async get(): Promise<any> {\n if (typeof this.data === 'undefined') {\n throw Error('no data secret available');\n }\n\n const { list } = this.data;\n const totalItems = list?.length;\n debug('get full list of packages (%o) has been fetched', totalItems);\n return Promise.resolve(list);\n }\n\n public getPackageStorage(packageName: string): pluginUtils.StorageHandler {\n // Storage root\n const storageRoot = path.resolve(this.getStoragePath());\n debug('storage root %o', storageRoot);\n\n if (isNil(storageRoot)) {\n this.logger.error('property storage in config.yaml is required for using this plugin');\n throw new Error('property storage in config.yaml is required for using this plugin');\n }\n\n // Storage path based on package access configuration\n const packageAccess = authUtils.getMatchedPackagesSpec(packageName, this.config.packages);\n\n let storagePath;\n if (packageAccess && typeof packageAccess.storage === 'string') {\n storagePath = fileUtils.resolveSafePath(storageRoot, packageAccess.storage);\n debug('storage path %o', storagePath);\n\n if (isNil(storagePath)) {\n this.logger.error(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n throw errorUtils.getInternalError(\n 'access-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n } else {\n storagePath = storageRoot;\n }\n\n // Storage path for the package\n const packageStoragePath = fileUtils.resolveSafePath(storagePath, packageName);\n debug('package path %o', packageStoragePath);\n\n // the folder must be the name itself, not a normalized form of it\n const isExactFolder =\n !isNil(packageStoragePath) &&\n path.relative(storagePath, packageStoragePath).split(path.sep).join('/') === packageName;\n\n if (!isExactFolder) {\n this.logger.warn(\n { packageName },\n 'package @{packageName} has no local storage because its name does not match its folder'\n );\n throw errorUtils.getInternalError(\n 'package-specific storage path is not under the configured storage directory or is invalid'\n );\n }\n\n return new LocalDriver(packageStoragePath as string, this.logger);\n }\n\n public async clean(): Promise<void> {\n await this._sync();\n }\n\n private _getCustomPackageLocalStorages(): Map<string, string> {\n const storages = new Map<string, string>();\n const { packages } = this.config;\n\n if (packages) {\n Object.keys(packages || {}).map((pkg) => {\n const { storage } = packages[pkg];\n if (typeof storage === 'string') {\n const storagePath = path.join(this.getStoragePath(), storage);\n debug('add custom storage for %s on %s', storage, storagePath);\n storages.set(storage, storagePath);\n }\n });\n }\n\n return storages;\n }\n\n private async _sync(): Promise<null> {\n debug('sync database started');\n\n if (this.locked) {\n this.logger.error(ERROR_DB_LOCKED);\n throw new Error(ERROR_DB_LOCKED);\n }\n // Uses sync to prevent ugly race condition\n try {\n const folderName = path.dirname(this.path);\n debug('creating folder %o', folderName);\n await mkdirPromise(folderName, { recursive: true });\n debug('creating folder %o created succeed', folderName);\n } catch (err) {\n this.logger.error({ err }, 'sync create folder has failed with error: @{err}');\n throw err;\n }\n\n try {\n await writeFilePromise(this.path, JSON.stringify(this.data));\n debug('sync write succeeded');\n\n return null;\n } catch (err: any) {\n this.logger.error({ err }, 'sync database file failed: @{err}');\n throw err;\n }\n }\n\n private async fetchLocalPackages(): Promise<LocalStorage> {\n try {\n return await loadPrivatePackages(this.path, this.logger);\n } catch (err: any) {\n // readFileSync is platform specific, macOS, Linux and Windows thrown an error\n // Only recreate if file not found to prevent data loss\n this.logger.info(\n { path: this.path },\n 'no private database found, recreating new one on @{path}'\n );\n if (err.code !== noSuchFile) {\n this.locked = true;\n this.logger.error(\n 'Failed to read package database file, please check the error printed below:\\n',\n `File Path: ${this.path}\\n\\n ${err.message}`\n );\n }\n // if no database is found we set empty placeholders\n return { list: [], secret: '' };\n }\n }\n\n private async getTokenDb(): Promise<Low<Record<string, Token[]>>> {\n if (!this.tokenDb) {\n debug('token database is not defined');\n let adapter;\n if (process.env.NODE_ENV === 'test') {\n debug('token memory adapter');\n adapter = new Memory<Record<string, Token[]>>();\n } else {\n debug('token async adapter');\n const pathDb = _dbGenPath(TOKEN_DB_NAME, this.config);\n adapter = new JSONFile<Record<string, Token[]>>(pathDb);\n }\n debug('token db generated');\n this.tokenDb = new Low<Record<string, Token[]>>(adapter, {});\n await this.tokenDb.read();\n // keyed by username: names like `constructor` or `__proto__` must not hit the prototype\n this.tokenDb.data = Object.assign(Object.create(null), this.tokenDb.data);\n }\n\n return this.tokenDb;\n }\n\n public async saveToken(token: Token): Promise<void> {\n debug('token key %o', token.key);\n const db = await this.getTokenDb();\n const userData = db.data[token.user];\n debug('user data %o', userData);\n if (isNil(userData)) {\n db.data[token.user] = [token];\n debug('token user %o new database', token.user);\n } else {\n db.data[token.user].push(token);\n }\n await db.write();\n debug('data %o', db.data);\n debug('token saved %o', token.user);\n }\n\n public async deleteToken(user: string, tokenKey: string): Promise<void> {\n const db = await this.getTokenDb();\n const userTokens = db.data[user];\n if (isNil(userTokens)) {\n throw new Error('user not found');\n }\n debug('tokens %o - %o', userTokens, userTokens.length);\n db.data[user] = userTokens.filter(({ key }) => {\n debug('key %o', key);\n return key !== tokenKey;\n });\n await db.write();\n debug('removed tokens key %o', tokenKey);\n }\n\n public async readTokens(filter: TokenFilter): Promise<Token[]> {\n const { user } = filter;\n debug('read tokens with %o', user);\n const db = await this.getTokenDb();\n const tokens = db.data[user];\n return tokens || [];\n }\n}\n\nexport default LocalDatabase;\n"],"mappings":";;;;;;;;;;;;AAiBA,IAAM,gBAAgB;AACtB,IAAM,UAAU,QAAQ,IAAI,0BAA0B,UAAU,MAAM;AAEtE,IAAM,QAAQ,WAAW,gCAAgC;AAEzD,IAAa,kBACX;AAIF,IAAM,gBAAN,cAA4B,YAAY,OAA8B;CACpE;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAmB,QAAgB,QAAgB;EAEjD,MAAM,QAAQ;GAAE;GAAQ;EAAO,CAAC;EAChC,KAAK,UAAU;EACf,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,SAAS;EACd,KAAK,OAAO,KAAA;EACZ,MAAM,kBAAkB,OAAO,UAAU;EACzC,KAAK,OAAO,WAAW,SAAS,MAAM;EACtC,KAAK,WAAW,KAAK,+BAA+B;EACpD,KAAK,OAAO,KAAK,EAAE,MAAM,KAAK,KAAK,GAAG,6BAA6B;EACnE,MAAM,0BAA0B,KAAK,IAAI;CAC3C;CAEA,MAAa,OAAsB;EACjC,MAAM,aAAa;EACnB,KAAK,OAAO,MAAM,KAAK,mBAAmB;EAC1C,MAAM,uBAAuB;EAC7B,MAAM,KAAK,MAAM;CACnB;CAEA,MAAa,YAA6B;EACxC,IAAI,OAAO,KAAK,SAAS,aACvB,MAAM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,GAAG;EAC/B,MAAM,KAAK,MAAM,KAAK,WAAW;EACjC,MAAM,WAAW,GAAG,KAAK,MAAM;EAC/B,MAAM,gBAAgB,QAAQ;EAC9B,IAAI,MAAM,QAAQ,GAAG;GACnB,GAAG,KAAK,MAAM,QAAQ,CAAC,KAAK;GAC5B,MAAM,8BAA8B,MAAM,IAAI;EAChD,OACE,GAAG,KAAK,MAAM,KAAK,CAAC,KAAK,KAAK;EAEhC,MAAM,GAAG,MAAM;EACf,MAAM,WAAW,GAAG,IAAI;EACxB,MAAM,kBAAkB,MAAM,IAAI;CACpC;CAEA,MAAa,YAAY,MAAc,UAAiC;EACtE,MAAM,KAAK,MAAM,KAAK,WAAW;EACjC,MAAM,aAAa,GAAG,KAAK;EAC3B,IAAI,MAAM,UAAU,GAClB,MAAM,IAAI,MAAM,gBAAgB;EAElC,MAAM,kBAAkB,YAAY,WAAW,MAAM;EACrD,GAAG,KAAK,QAAQ,WAAW,QAAQ,EAAE,UAAU;GAC7C,MAAM,UAAU,GAAG;GACnB,OAAO,QAAQ;EACjB,CAAC;EACD,MAAM,GAAG,MAAM;EACf,MAAM,yBAAyB,QAAQ;CACzC;CAEA,MAAa,WAAW,QAAuC;EAC7D,MAAM,EAAE,SAAS;EACjB,MAAM,uBAAuB,IAAI;EAGjC,QADe,MADE,KAAK,WAAW,EAAA,CACf,KAAK,SACN,CAAC;CACpB;AACF"}
package/build/local-fs.js CHANGED
@@ -82,13 +82,14 @@ var LocalFS = class {
82
82
  err,
83
83
  packageName
84
84
  }, "error on update package @{packageName}: @{err.message}");
85
- if (locked) try {
86
- await this._unlockJSON(packageJSONFileName);
85
+ if (locked) {
86
+ try {
87
+ await this._unlockJSON(packageJSONFileName);
88
+ } catch {
89
+ throw _verdaccio_core.errorUtils.getInternalError("resource temporarily unavailable");
90
+ }
87
91
  throw err;
88
- } catch {
89
- throw _verdaccio_core.errorUtils.getInternalError("resource temporarily unavailable");
90
- }
91
- else if (err.code === "EAGAIN") throw _verdaccio_core.errorUtils.getInternalError("resource temporarily unavailable");
92
+ } else if (err.code === "EAGAIN") throw _verdaccio_core.errorUtils.getInternalError("resource temporarily unavailable");
92
93
  else if (err.code === "ENOENT") throw _verdaccio_core.errorUtils.getNotFound();
93
94
  else throw err;
94
95
  }
@@ -1 +1 @@
1
- {"version":3,"file":"local-fs.js","names":[],"sources":["../src/local-fs.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Readable, Writable } from 'node:stream';\nimport { addAbortSignal } from 'node:stream';\nimport sanitzers from 'sanitize-filename';\n\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport { errorUtils } from '@verdaccio/core';\nimport { readFileNext, unlockFileNext } from '@verdaccio/file-locking';\nimport type { Logger, Manifest } from '@verdaccio/types';\n\nimport {\n accessPromise,\n mkdirPromise,\n openPromise,\n readFilePromise,\n renamePromise,\n rmdirPromise,\n statPromise,\n unlinkPromise,\n writeFilePromise,\n} from './fs';\n\nexport const fileExist = 'EEXISTS';\nexport const noSuchFile = 'ENOENT';\nexport const resourceNotAvailable = 'EAGAIN';\nexport const packageJSONFileName = 'package.json';\n\nexport type ILocalFSPackageManager = pluginUtils.StorageHandler & { path: string };\n\nconst debug = buildDebug('verdaccio:plugin:local-storage:local-fs');\n\nexport const fSError = function (message: string, code = 409): VerdaccioError {\n const err: VerdaccioError = errorUtils.getCode(code, message);\n // FIXME: we should return http-status codes here instead, future improvement\n // @ts-ignore\n err.code = message;\n\n return err;\n};\n\nconst tempFile = function (str): string {\n return `${str}.tmp${String(Math.random()).slice(2)}`;\n};\n\nexport async function renameTmp(src: string, dst: string): Promise<void> {\n debug('rename %s to %s', src, dst);\n try {\n await renamePromise(src, dst);\n } catch (err: any) {\n debug('error rename %s error %s', src, err?.message);\n await unlinkPromise(src);\n }\n}\n\nexport default class LocalFS implements ILocalFSPackageManager {\n public path: string;\n public logger: Logger;\n\n public constructor(path: string, logger: Logger) {\n this.path = path;\n this.logger = logger;\n }\n\n /**\n * This function allows to update the package\n * This function handle the update package logic, for this plugin\n * we need to lock/unlock handlers for thread-safely and then apply\n * the `handleUpdate` and return the result.\n *\n * The lock could fail on several steps so we need to ensure the\n * file does not get locked if the whole process fails.\n *\n Algorithm:\n 1. lock package.json for writing\n 2. read package.json\n 3. apply external update package handler\n 4. return manifest (write is being hanlded into the core)\n 5. rename package.json.tmp package.json\n * @param {*} packageName\n * The update package handler could be different based\n * on the action and handled into the core.\n * @param {*} handleUpdate\n */\n public async updatePackage(\n packageName: string,\n handleUpdate: (manifest: Manifest) => Promise<Manifest>\n ): Promise<Manifest> {\n // this plugin lock files on write, we handle all possible scenarios\n let locked = false;\n let manifestUpdated: Manifest;\n try {\n const manifest = await this._lockAndReadJSON(packageJSONFileName);\n locked = true;\n manifestUpdated = await handleUpdate(manifest);\n if (locked) {\n debug('unlock %s', packageJSONFileName);\n await this._unlockJSON(packageJSONFileName);\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n } else {\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n }\n } catch (err: any) {\n // we ensure lock the file\n this.logger.error(\n { err, packageName },\n 'error on update package @{packageName}: @{err.message}'\n );\n if (locked) {\n try {\n await this._unlockJSON(packageJSONFileName);\n // after unlock bubble up error.\n throw err;\n } catch {\n // unlock could fail, we bubble up error\n throw errorUtils.getInternalError('resource temporarily unavailable');\n }\n } else {\n if (err.code === resourceNotAvailable) {\n throw errorUtils.getInternalError('resource temporarily unavailable');\n } else if (err.code === noSuchFile) {\n throw errorUtils.getNotFound();\n } else {\n throw err;\n }\n }\n }\n }\n\n public async deletePackage(packageName: string): Promise<void> {\n debug('delete a file/package %o', packageName);\n\n return await unlinkPromise(this._getStorage(packageName));\n }\n\n public async removePackage(): Promise<void> {\n debug('remove a package folder %o', this.path);\n\n await rmdirPromise(this._getStorage('.'));\n }\n\n /**\n * Verify if the package exists already.\n * @param name package name\n * @returns\n */\n public async hasPackage(): Promise<boolean> {\n const pathName: string = this._getStorage(packageJSONFileName);\n try {\n const stat = await statPromise(pathName);\n return stat.isFile();\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('dir: %o does not exist %s', pathName, err?.code);\n return false;\n } else {\n this.logger.error({ err }, 'error on verify a package exist: @{err.message}');\n throw errorUtils.getInternalError('error on verify a package exist');\n }\n }\n }\n\n /**\n * Create a package in the local storage, if package already exist fails.\n * @param name package name\n * @param manifest package manifest\n */\n public async createPackage(name: string, manifest: Manifest): Promise<void> {\n debug('create a new package %o', name);\n const pathPackage = this._getStorage(packageJSONFileName);\n try {\n // https://nodejs.org/dist/latest-v17.x/docs/api/fs.html#file-system-flags\n // 'wx': Like 'w' but fails if the path exists\n await openPromise(pathPackage, 'wx');\n } catch (err: any) {\n // cannot override a pacakge that already exist\n if (err.code === 'EEXIST') {\n debug('file %o cannot be created, it already exists: %o', name);\n throw fSError(fileExist);\n }\n }\n // Create a new file and it´s folder if does not exist previously\n await this.writeFile(pathPackage, this._convertToString(manifest));\n }\n\n public async savePackage(name: string, value: Manifest): Promise<void> {\n debug('save a package %o', name);\n\n await this.writeFile(this._getStorage(packageJSONFileName), this._convertToString(value));\n }\n\n public async readPackage(name: string): Promise<Manifest> {\n debug('read a package %o', name);\n try {\n const res = await this._readStorageFile(this._getStorage(packageJSONFileName));\n const data: any = JSON.parse(res.toString('utf8'));\n\n debug('read storage file %o has succeeded', name);\n return data;\n } catch (err: any) {\n if (err.code !== noSuchFile) {\n debug('parse error');\n this.logger.error({ err, name }, 'error on parse @{name}: @{err.message}');\n }\n throw err;\n }\n }\n\n public async hasTarball(fileName: string): Promise<boolean> {\n const pathName: string = this._getStorage(fileName);\n return new Promise((resolve) => {\n accessPromise(pathName)\n .then(() => {\n resolve(true);\n })\n .catch(() => resolve(false));\n });\n }\n\n /**\n * Best-effort removal of a temporary file. Error and abort can both try to\n * clean the same file from event listeners, so a missing file is fine and\n * nothing may throw — a rejection here becomes an uncaught exception.\n */\n private async removeTempFile(temporalName): Promise<void> {\n debug('remove temporal file %o', temporalName);\n try {\n await unlinkPromise(temporalName);\n debug('removed temporal file %o', temporalName);\n } catch (err: any) {\n if (err?.code !== 'ENOENT') {\n this.logger.warn(\n { temporalName, err: err.message },\n 'unable to remove temporal file @{temporalName}: @{err}'\n );\n }\n }\n }\n\n /**\n * Write a tarball into the storage\n * @param fileName package name\n * @param param1\n * @returns\n */\n public async writeTarball(fileName: string, { signal }): Promise<Writable> {\n debug('write a tarball %o', fileName);\n const pathName: string = this._getStorage(fileName);\n await this.checkCreateFolder(pathName);\n // create a temporary file to avoid conflicts or prev corruption files\n const temporalName = path.join(\n this.path,\n sanitzers(`${fileName}.tmp-${String(Math.random()).replace(/^0\\./, '')}`)\n );\n\n debug('write a temporal name %o', temporalName);\n let opened = false;\n // an errored or aborted download must never be renamed into place: that\n // would publish a truncated tarball under the final name\n let failed = false;\n const writeStream = fs.createWriteStream(temporalName);\n\n writeStream.on('open', () => {\n opened = true;\n });\n\n writeStream.on('error', async (err) => {\n failed = true;\n if (opened) {\n this.logger.error(\n { err, fileName },\n 'error on open write tarball for @{fileName}: @{err.message}'\n );\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n this.logger.error(\n { err, fileName },\n 'error on writing tarball for @{fileName}: @{err.message}'\n );\n await this.removeTempFile(temporalName);\n }\n });\n\n // the 'close' event is emitted when the stream and any of its\n // underlying resources (a file descriptor, for example) have been closed.\n writeStream.once('close', async () => {\n if (failed) {\n // the error/abort listeners own the cleanup of the temporal file\n return;\n }\n try {\n await renameTmp(temporalName, pathName);\n } catch (err) {\n this.logger.error(\n { err, temporalName, pathName },\n 'error on rename temporal file @{temporalName} to @{pathName}: @{err.message},' +\n 'please report this bug'\n );\n }\n });\n\n // if upload is aborted, we clean up the temporal file\n signal?.addEventListener(\n 'abort',\n async () => {\n failed = true;\n if (opened) {\n // close always happens, even if error\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n await this.removeTempFile(temporalName);\n }\n },\n { once: true }\n );\n\n return writeStream;\n }\n\n /**\n * Read a tarball from the storage\n * @param tarballName tarball name eg: foo-1.0.0.tgz\n * @param options {signal} abort signal\n * @returns Readable stream\n */\n public async readTarball(tarballName: string, { signal }): Promise<Readable> {\n const pathName: string = this._getStorage(tarballName);\n debug('read a tarball %o', pathName);\n const readStream = addAbortSignal(signal, fs.createReadStream(pathName));\n readStream.on('open', function (fileDescriptorId: number) {\n // if abort, the descriptor is null\n debug('file descriptor id %o', fileDescriptorId);\n if (fileDescriptorId) {\n // sync on purpose: the size must be emitted before the first data\n // chunk flushes the response headers (an async fstat races it)\n let size: number | undefined;\n try {\n size = fs.fstatSync(fileDescriptorId).size;\n } catch {\n // the stream 'error' event surfaces any real problem\n }\n if (size !== undefined) {\n debug('file size %o', size);\n readStream.emit('content-length', size);\n }\n }\n });\n readStream.on('error', (error) => {\n debug('no tarball found %o for %s message %s', pathName, tarballName, error.message);\n });\n return readStream;\n }\n\n private async _readStorageFile(name: string): Promise<any> {\n debug('reading the file: %o', name);\n try {\n return await readFilePromise(name);\n } catch (err: any) {\n debug('error reading the file: %o with error %o', name, err.message);\n throw err;\n }\n }\n\n private _convertToString(value: Manifest): string {\n return JSON.stringify(value);\n }\n\n public _getStorage(fileName = ''): string {\n const storagePath: string = path.join(this.path, sanitzers(fileName));\n debug('get storage %s', storagePath);\n return storagePath;\n }\n\n private async writeTempFileAndRename(dest: string, fileContent: string): Promise<any> {\n const tempFilePath = tempFile(dest);\n try {\n // write file on temp location\n await this.checkCreateFolder(tempFilePath);\n await writeFilePromise(tempFilePath, fileContent);\n debug('creating a new file:: %o', dest);\n // rename tmp file to original\n await renameTmp(tempFilePath, dest);\n } catch (err: any) {\n debug('error on write the file: %o', dest);\n throw err;\n }\n }\n\n private async writeFile(destiny: string, fileContent: string): Promise<void> {\n try {\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } catch (err: any) {\n if (err && err.code === noSuchFile) {\n await this.checkCreateFolder(destiny);\n // we try again create the temp file\n debug('writing a temp file %s', destiny);\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } else {\n this.logger.error({ err }, 'error on write file: @{err.message}');\n throw err;\n }\n }\n }\n\n private async checkCreateFolder(pathName: string): Promise<void> {\n // Check if folder exists and create it if not\n const dir = path.dirname(pathName);\n try {\n await accessPromise(dir);\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('folder does not exist %o', dir);\n await mkdirPromise(dir, { recursive: true });\n debug('folder %o created', dir);\n } else {\n debug('error on check folder %o', dir);\n throw err;\n }\n }\n }\n\n private async _lockAndReadJSON(name: string): Promise<Manifest> {\n const fileName: string = this._getStorage(name);\n debug('lock and read a file %o', fileName);\n try {\n const data = await readFileNext<Manifest>(fileName, {\n lock: true,\n parse: true,\n });\n return data;\n } catch (err) {\n this.logger.error({ err }, 'error on lock file: @{err.message}');\n debug('error on lock and read json for file: %o', name);\n\n throw err;\n }\n }\n\n private async _unlockJSON(name: string): Promise<void> {\n await unlockFileNext(this._getStorage(name));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,IAAa,YAAY;AACzB,IAAa,aAAa;AAC1B,IAAa,uBAAuB;AACpC,IAAa,sBAAsB;AAInC,IAAM,WAAA,GAAQ,MAAA,QAAA,CAAW,yCAAyC;AAElE,IAAa,UAAU,SAAU,SAAiB,OAAO,KAAqB;CAC5E,MAAM,MAAsB,gBAAA,WAAW,QAAQ,MAAM,OAAO;CAG5D,IAAI,OAAO;CAEX,OAAO;AACT;AAEA,IAAM,WAAW,SAAU,KAAa;CACtC,OAAO,GAAG,IAAI,MAAM,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;AACnD;AAEA,eAAsB,UAAU,KAAa,KAA4B;CACvE,QAAM,mBAAmB,KAAK,GAAG;CACjC,IAAI;EACF,MAAM,WAAA,cAAc,KAAK,GAAG;CAC9B,SAAS,KAAU;EACj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,KAAK,OAAO,MAAM,EAAE,IAAI,GAAG,oCAAoC;GAC/D,QAAM,4CAA4C,IAAI;GAEtD,MAAM;EACR;CACF;CAEA,MAAc,YAAY,MAA6B;EACrD,OAAA,GAAM,wBAAA,eAAA,CAAe,KAAK,YAAY,IAAI,CAAC;CAC7C;AACF"}
1
+ {"version":3,"file":"local-fs.js","names":[],"sources":["../src/local-fs.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Readable, Writable } from 'node:stream';\nimport { addAbortSignal } from 'node:stream';\nimport sanitzers from 'sanitize-filename';\n\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport { errorUtils } from '@verdaccio/core';\nimport { readFileNext, unlockFileNext } from '@verdaccio/file-locking';\nimport type { Logger, Manifest } from '@verdaccio/types';\n\nimport {\n accessPromise,\n mkdirPromise,\n openPromise,\n readFilePromise,\n renamePromise,\n rmdirPromise,\n statPromise,\n unlinkPromise,\n writeFilePromise,\n} from './fs';\n\nexport const fileExist = 'EEXISTS';\nexport const noSuchFile = 'ENOENT';\nexport const resourceNotAvailable = 'EAGAIN';\nexport const packageJSONFileName = 'package.json';\n\nexport type ILocalFSPackageManager = pluginUtils.StorageHandler & { path: string };\n\nconst debug = buildDebug('verdaccio:plugin:local-storage:local-fs');\n\nexport const fSError = function (message: string, code = 409): VerdaccioError {\n const err: VerdaccioError = errorUtils.getCode(code, message);\n // FIXME: we should return http-status codes here instead, future improvement\n // @ts-ignore\n err.code = message;\n\n return err;\n};\n\nconst tempFile = function (str): string {\n return `${str}.tmp${String(Math.random()).slice(2)}`;\n};\n\nexport async function renameTmp(src: string, dst: string): Promise<void> {\n debug('rename %s to %s', src, dst);\n try {\n await renamePromise(src, dst);\n } catch (err: any) {\n debug('error rename %s error %s', src, err?.message);\n await unlinkPromise(src);\n }\n}\n\nexport default class LocalFS implements ILocalFSPackageManager {\n public path: string;\n public logger: Logger;\n\n public constructor(path: string, logger: Logger) {\n this.path = path;\n this.logger = logger;\n }\n\n /**\n * This function allows to update the package\n * This function handle the update package logic, for this plugin\n * we need to lock/unlock handlers for thread-safely and then apply\n * the `handleUpdate` and return the result.\n *\n * The lock could fail on several steps so we need to ensure the\n * file does not get locked if the whole process fails.\n *\n Algorithm:\n 1. lock package.json for writing\n 2. read package.json\n 3. apply external update package handler\n 4. return manifest (write is being hanlded into the core)\n 5. rename package.json.tmp package.json\n * @param {*} packageName\n * The update package handler could be different based\n * on the action and handled into the core.\n * @param {*} handleUpdate\n */\n public async updatePackage(\n packageName: string,\n handleUpdate: (manifest: Manifest) => Promise<Manifest>\n ): Promise<Manifest> {\n // this plugin lock files on write, we handle all possible scenarios\n let locked = false;\n let manifestUpdated: Manifest;\n try {\n const manifest = await this._lockAndReadJSON(packageJSONFileName);\n locked = true;\n manifestUpdated = await handleUpdate(manifest);\n if (locked) {\n debug('unlock %s', packageJSONFileName);\n await this._unlockJSON(packageJSONFileName);\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n } else {\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n }\n } catch (err: any) {\n // we ensure lock the file\n this.logger.error(\n { err, packageName },\n 'error on update package @{packageName}: @{err.message}'\n );\n if (locked) {\n try {\n await this._unlockJSON(packageJSONFileName);\n } catch {\n // unlock could fail, we bubble up error\n throw errorUtils.getInternalError('resource temporarily unavailable');\n }\n // after unlock bubble up the original error (e.g. thrown by the handler)\n throw err;\n } else {\n if (err.code === resourceNotAvailable) {\n throw errorUtils.getInternalError('resource temporarily unavailable');\n } else if (err.code === noSuchFile) {\n throw errorUtils.getNotFound();\n } else {\n throw err;\n }\n }\n }\n }\n\n public async deletePackage(packageName: string): Promise<void> {\n debug('delete a file/package %o', packageName);\n\n return await unlinkPromise(this._getStorage(packageName));\n }\n\n public async removePackage(): Promise<void> {\n debug('remove a package folder %o', this.path);\n\n await rmdirPromise(this._getStorage('.'));\n }\n\n /**\n * Verify if the package exists already.\n * @param name package name\n * @returns\n */\n public async hasPackage(): Promise<boolean> {\n const pathName: string = this._getStorage(packageJSONFileName);\n try {\n const stat = await statPromise(pathName);\n return stat.isFile();\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('dir: %o does not exist %s', pathName, err?.code);\n return false;\n } else {\n this.logger.error({ err }, 'error on verify a package exist: @{err.message}');\n throw errorUtils.getInternalError('error on verify a package exist');\n }\n }\n }\n\n /**\n * Create a package in the local storage, if package already exist fails.\n * @param name package name\n * @param manifest package manifest\n */\n public async createPackage(name: string, manifest: Manifest): Promise<void> {\n debug('create a new package %o', name);\n const pathPackage = this._getStorage(packageJSONFileName);\n try {\n // https://nodejs.org/dist/latest-v17.x/docs/api/fs.html#file-system-flags\n // 'wx': Like 'w' but fails if the path exists\n await openPromise(pathPackage, 'wx');\n } catch (err: any) {\n // cannot override a pacakge that already exist\n if (err.code === 'EEXIST') {\n debug('file %o cannot be created, it already exists: %o', name);\n throw fSError(fileExist);\n }\n }\n // Create a new file and it´s folder if does not exist previously\n await this.writeFile(pathPackage, this._convertToString(manifest));\n }\n\n public async savePackage(name: string, value: Manifest): Promise<void> {\n debug('save a package %o', name);\n\n await this.writeFile(this._getStorage(packageJSONFileName), this._convertToString(value));\n }\n\n public async readPackage(name: string): Promise<Manifest> {\n debug('read a package %o', name);\n try {\n const res = await this._readStorageFile(this._getStorage(packageJSONFileName));\n const data: any = JSON.parse(res.toString('utf8'));\n\n debug('read storage file %o has succeeded', name);\n return data;\n } catch (err: any) {\n if (err.code !== noSuchFile) {\n debug('parse error');\n this.logger.error({ err, name }, 'error on parse @{name}: @{err.message}');\n }\n throw err;\n }\n }\n\n public async hasTarball(fileName: string): Promise<boolean> {\n const pathName: string = this._getStorage(fileName);\n return new Promise((resolve) => {\n accessPromise(pathName)\n .then(() => {\n resolve(true);\n })\n .catch(() => resolve(false));\n });\n }\n\n /**\n * Best-effort removal of a temporary file. Error and abort can both try to\n * clean the same file from event listeners, so a missing file is fine and\n * nothing may throw — a rejection here becomes an uncaught exception.\n */\n private async removeTempFile(temporalName): Promise<void> {\n debug('remove temporal file %o', temporalName);\n try {\n await unlinkPromise(temporalName);\n debug('removed temporal file %o', temporalName);\n } catch (err: any) {\n if (err?.code !== 'ENOENT') {\n this.logger.warn(\n { temporalName, err: err.message },\n 'unable to remove temporal file @{temporalName}: @{err}'\n );\n }\n }\n }\n\n /**\n * Write a tarball into the storage\n * @param fileName package name\n * @param param1\n * @returns\n */\n public async writeTarball(fileName: string, { signal }): Promise<Writable> {\n debug('write a tarball %o', fileName);\n const pathName: string = this._getStorage(fileName);\n await this.checkCreateFolder(pathName);\n // create a temporary file to avoid conflicts or prev corruption files\n const temporalName = path.join(\n this.path,\n sanitzers(`${fileName}.tmp-${String(Math.random()).replace(/^0\\./, '')}`)\n );\n\n debug('write a temporal name %o', temporalName);\n let opened = false;\n // an errored or aborted download must never be renamed into place: that\n // would publish a truncated tarball under the final name\n let failed = false;\n const writeStream = fs.createWriteStream(temporalName);\n\n writeStream.on('open', () => {\n opened = true;\n });\n\n writeStream.on('error', async (err) => {\n failed = true;\n if (opened) {\n this.logger.error(\n { err, fileName },\n 'error on open write tarball for @{fileName}: @{err.message}'\n );\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n this.logger.error(\n { err, fileName },\n 'error on writing tarball for @{fileName}: @{err.message}'\n );\n await this.removeTempFile(temporalName);\n }\n });\n\n // the 'close' event is emitted when the stream and any of its\n // underlying resources (a file descriptor, for example) have been closed.\n writeStream.once('close', async () => {\n if (failed) {\n // the error/abort listeners own the cleanup of the temporal file\n return;\n }\n try {\n await renameTmp(temporalName, pathName);\n } catch (err) {\n this.logger.error(\n { err, temporalName, pathName },\n 'error on rename temporal file @{temporalName} to @{pathName}: @{err.message},' +\n 'please report this bug'\n );\n }\n });\n\n // if upload is aborted, we clean up the temporal file\n signal?.addEventListener(\n 'abort',\n async () => {\n failed = true;\n if (opened) {\n // close always happens, even if error\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n await this.removeTempFile(temporalName);\n }\n },\n { once: true }\n );\n\n return writeStream;\n }\n\n /**\n * Read a tarball from the storage\n * @param tarballName tarball name eg: foo-1.0.0.tgz\n * @param options {signal} abort signal\n * @returns Readable stream\n */\n public async readTarball(tarballName: string, { signal }): Promise<Readable> {\n const pathName: string = this._getStorage(tarballName);\n debug('read a tarball %o', pathName);\n const readStream = addAbortSignal(signal, fs.createReadStream(pathName));\n readStream.on('open', function (fileDescriptorId: number) {\n // if abort, the descriptor is null\n debug('file descriptor id %o', fileDescriptorId);\n if (fileDescriptorId) {\n // sync on purpose: the size must be emitted before the first data\n // chunk flushes the response headers (an async fstat races it)\n let size: number | undefined;\n try {\n size = fs.fstatSync(fileDescriptorId).size;\n } catch {\n // the stream 'error' event surfaces any real problem\n }\n if (size !== undefined) {\n debug('file size %o', size);\n readStream.emit('content-length', size);\n }\n }\n });\n readStream.on('error', (error) => {\n debug('no tarball found %o for %s message %s', pathName, tarballName, error.message);\n });\n return readStream;\n }\n\n private async _readStorageFile(name: string): Promise<any> {\n debug('reading the file: %o', name);\n try {\n return await readFilePromise(name);\n } catch (err: any) {\n debug('error reading the file: %o with error %o', name, err.message);\n throw err;\n }\n }\n\n private _convertToString(value: Manifest): string {\n return JSON.stringify(value);\n }\n\n public _getStorage(fileName = ''): string {\n const storagePath: string = path.join(this.path, sanitzers(fileName));\n debug('get storage %s', storagePath);\n return storagePath;\n }\n\n private async writeTempFileAndRename(dest: string, fileContent: string): Promise<any> {\n const tempFilePath = tempFile(dest);\n try {\n // write file on temp location\n await this.checkCreateFolder(tempFilePath);\n await writeFilePromise(tempFilePath, fileContent);\n debug('creating a new file:: %o', dest);\n // rename tmp file to original\n await renameTmp(tempFilePath, dest);\n } catch (err: any) {\n debug('error on write the file: %o', dest);\n throw err;\n }\n }\n\n private async writeFile(destiny: string, fileContent: string): Promise<void> {\n try {\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } catch (err: any) {\n if (err && err.code === noSuchFile) {\n await this.checkCreateFolder(destiny);\n // we try again create the temp file\n debug('writing a temp file %s', destiny);\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } else {\n this.logger.error({ err }, 'error on write file: @{err.message}');\n throw err;\n }\n }\n }\n\n private async checkCreateFolder(pathName: string): Promise<void> {\n // Check if folder exists and create it if not\n const dir = path.dirname(pathName);\n try {\n await accessPromise(dir);\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('folder does not exist %o', dir);\n await mkdirPromise(dir, { recursive: true });\n debug('folder %o created', dir);\n } else {\n debug('error on check folder %o', dir);\n throw err;\n }\n }\n }\n\n private async _lockAndReadJSON(name: string): Promise<Manifest> {\n const fileName: string = this._getStorage(name);\n debug('lock and read a file %o', fileName);\n try {\n const data = await readFileNext<Manifest>(fileName, {\n lock: true,\n parse: true,\n });\n return data;\n } catch (err) {\n this.logger.error({ err }, 'error on lock file: @{err.message}');\n debug('error on lock and read json for file: %o', name);\n\n throw err;\n }\n }\n\n private async _unlockJSON(name: string): Promise<void> {\n await unlockFileNext(this._getStorage(name));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAwBA,IAAa,YAAY;AACzB,IAAa,aAAa;AAC1B,IAAa,uBAAuB;AACpC,IAAa,sBAAsB;AAInC,IAAM,WAAA,GAAQ,MAAA,QAAA,CAAW,yCAAyC;AAElE,IAAa,UAAU,SAAU,SAAiB,OAAO,KAAqB;CAC5E,MAAM,MAAsB,gBAAA,WAAW,QAAQ,MAAM,OAAO;CAG5D,IAAI,OAAO;CAEX,OAAO;AACT;AAEA,IAAM,WAAW,SAAU,KAAa;CACtC,OAAO,GAAG,IAAI,MAAM,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;AACnD;AAEA,eAAsB,UAAU,KAAa,KAA4B;CACvE,QAAM,mBAAmB,KAAK,GAAG;CACjC,IAAI;EACF,MAAM,WAAA,cAAc,KAAK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ACN,OAAO;GACT,CAAC;EAEH,SAAS,KAAK;GACZ,KAAK,OAAO,MAAM,EAAE,IAAI,GAAG,oCAAoC;GAC/D,QAAM,4CAA4C,IAAI;GAEtD,MAAM;EACR;CACF;CAEA,MAAc,YAAY,MAA6B;EACrD,OAAA,GAAM,wBAAA,eAAA,CAAe,KAAK,YAAY,IAAI,CAAC;CAC7C;AACF"}
@@ -77,13 +77,14 @@ var LocalFS = class {
77
77
  err,
78
78
  packageName
79
79
  }, "error on update package @{packageName}: @{err.message}");
80
- if (locked) try {
81
- await this._unlockJSON(packageJSONFileName);
80
+ if (locked) {
81
+ try {
82
+ await this._unlockJSON(packageJSONFileName);
83
+ } catch {
84
+ throw errorUtils.getInternalError("resource temporarily unavailable");
85
+ }
82
86
  throw err;
83
- } catch {
84
- throw errorUtils.getInternalError("resource temporarily unavailable");
85
- }
86
- else if (err.code === "EAGAIN") throw errorUtils.getInternalError("resource temporarily unavailable");
87
+ } else if (err.code === "EAGAIN") throw errorUtils.getInternalError("resource temporarily unavailable");
87
88
  else if (err.code === "ENOENT") throw errorUtils.getNotFound();
88
89
  else throw err;
89
90
  }
@@ -1 +1 @@
1
- {"version":3,"file":"local-fs.mjs","names":[],"sources":["../src/local-fs.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Readable, Writable } from 'node:stream';\nimport { addAbortSignal } from 'node:stream';\nimport sanitzers from 'sanitize-filename';\n\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport { errorUtils } from '@verdaccio/core';\nimport { readFileNext, unlockFileNext } from '@verdaccio/file-locking';\nimport type { Logger, Manifest } from '@verdaccio/types';\n\nimport {\n accessPromise,\n mkdirPromise,\n openPromise,\n readFilePromise,\n renamePromise,\n rmdirPromise,\n statPromise,\n unlinkPromise,\n writeFilePromise,\n} from './fs';\n\nexport const fileExist = 'EEXISTS';\nexport const noSuchFile = 'ENOENT';\nexport const resourceNotAvailable = 'EAGAIN';\nexport const packageJSONFileName = 'package.json';\n\nexport type ILocalFSPackageManager = pluginUtils.StorageHandler & { path: string };\n\nconst debug = buildDebug('verdaccio:plugin:local-storage:local-fs');\n\nexport const fSError = function (message: string, code = 409): VerdaccioError {\n const err: VerdaccioError = errorUtils.getCode(code, message);\n // FIXME: we should return http-status codes here instead, future improvement\n // @ts-ignore\n err.code = message;\n\n return err;\n};\n\nconst tempFile = function (str): string {\n return `${str}.tmp${String(Math.random()).slice(2)}`;\n};\n\nexport async function renameTmp(src: string, dst: string): Promise<void> {\n debug('rename %s to %s', src, dst);\n try {\n await renamePromise(src, dst);\n } catch (err: any) {\n debug('error rename %s error %s', src, err?.message);\n await unlinkPromise(src);\n }\n}\n\nexport default class LocalFS implements ILocalFSPackageManager {\n public path: string;\n public logger: Logger;\n\n public constructor(path: string, logger: Logger) {\n this.path = path;\n this.logger = logger;\n }\n\n /**\n * This function allows to update the package\n * This function handle the update package logic, for this plugin\n * we need to lock/unlock handlers for thread-safely and then apply\n * the `handleUpdate` and return the result.\n *\n * The lock could fail on several steps so we need to ensure the\n * file does not get locked if the whole process fails.\n *\n Algorithm:\n 1. lock package.json for writing\n 2. read package.json\n 3. apply external update package handler\n 4. return manifest (write is being hanlded into the core)\n 5. rename package.json.tmp package.json\n * @param {*} packageName\n * The update package handler could be different based\n * on the action and handled into the core.\n * @param {*} handleUpdate\n */\n public async updatePackage(\n packageName: string,\n handleUpdate: (manifest: Manifest) => Promise<Manifest>\n ): Promise<Manifest> {\n // this plugin lock files on write, we handle all possible scenarios\n let locked = false;\n let manifestUpdated: Manifest;\n try {\n const manifest = await this._lockAndReadJSON(packageJSONFileName);\n locked = true;\n manifestUpdated = await handleUpdate(manifest);\n if (locked) {\n debug('unlock %s', packageJSONFileName);\n await this._unlockJSON(packageJSONFileName);\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n } else {\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n }\n } catch (err: any) {\n // we ensure lock the file\n this.logger.error(\n { err, packageName },\n 'error on update package @{packageName}: @{err.message}'\n );\n if (locked) {\n try {\n await this._unlockJSON(packageJSONFileName);\n // after unlock bubble up error.\n throw err;\n } catch {\n // unlock could fail, we bubble up error\n throw errorUtils.getInternalError('resource temporarily unavailable');\n }\n } else {\n if (err.code === resourceNotAvailable) {\n throw errorUtils.getInternalError('resource temporarily unavailable');\n } else if (err.code === noSuchFile) {\n throw errorUtils.getNotFound();\n } else {\n throw err;\n }\n }\n }\n }\n\n public async deletePackage(packageName: string): Promise<void> {\n debug('delete a file/package %o', packageName);\n\n return await unlinkPromise(this._getStorage(packageName));\n }\n\n public async removePackage(): Promise<void> {\n debug('remove a package folder %o', this.path);\n\n await rmdirPromise(this._getStorage('.'));\n }\n\n /**\n * Verify if the package exists already.\n * @param name package name\n * @returns\n */\n public async hasPackage(): Promise<boolean> {\n const pathName: string = this._getStorage(packageJSONFileName);\n try {\n const stat = await statPromise(pathName);\n return stat.isFile();\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('dir: %o does not exist %s', pathName, err?.code);\n return false;\n } else {\n this.logger.error({ err }, 'error on verify a package exist: @{err.message}');\n throw errorUtils.getInternalError('error on verify a package exist');\n }\n }\n }\n\n /**\n * Create a package in the local storage, if package already exist fails.\n * @param name package name\n * @param manifest package manifest\n */\n public async createPackage(name: string, manifest: Manifest): Promise<void> {\n debug('create a new package %o', name);\n const pathPackage = this._getStorage(packageJSONFileName);\n try {\n // https://nodejs.org/dist/latest-v17.x/docs/api/fs.html#file-system-flags\n // 'wx': Like 'w' but fails if the path exists\n await openPromise(pathPackage, 'wx');\n } catch (err: any) {\n // cannot override a pacakge that already exist\n if (err.code === 'EEXIST') {\n debug('file %o cannot be created, it already exists: %o', name);\n throw fSError(fileExist);\n }\n }\n // Create a new file and it´s folder if does not exist previously\n await this.writeFile(pathPackage, this._convertToString(manifest));\n }\n\n public async savePackage(name: string, value: Manifest): Promise<void> {\n debug('save a package %o', name);\n\n await this.writeFile(this._getStorage(packageJSONFileName), this._convertToString(value));\n }\n\n public async readPackage(name: string): Promise<Manifest> {\n debug('read a package %o', name);\n try {\n const res = await this._readStorageFile(this._getStorage(packageJSONFileName));\n const data: any = JSON.parse(res.toString('utf8'));\n\n debug('read storage file %o has succeeded', name);\n return data;\n } catch (err: any) {\n if (err.code !== noSuchFile) {\n debug('parse error');\n this.logger.error({ err, name }, 'error on parse @{name}: @{err.message}');\n }\n throw err;\n }\n }\n\n public async hasTarball(fileName: string): Promise<boolean> {\n const pathName: string = this._getStorage(fileName);\n return new Promise((resolve) => {\n accessPromise(pathName)\n .then(() => {\n resolve(true);\n })\n .catch(() => resolve(false));\n });\n }\n\n /**\n * Best-effort removal of a temporary file. Error and abort can both try to\n * clean the same file from event listeners, so a missing file is fine and\n * nothing may throw — a rejection here becomes an uncaught exception.\n */\n private async removeTempFile(temporalName): Promise<void> {\n debug('remove temporal file %o', temporalName);\n try {\n await unlinkPromise(temporalName);\n debug('removed temporal file %o', temporalName);\n } catch (err: any) {\n if (err?.code !== 'ENOENT') {\n this.logger.warn(\n { temporalName, err: err.message },\n 'unable to remove temporal file @{temporalName}: @{err}'\n );\n }\n }\n }\n\n /**\n * Write a tarball into the storage\n * @param fileName package name\n * @param param1\n * @returns\n */\n public async writeTarball(fileName: string, { signal }): Promise<Writable> {\n debug('write a tarball %o', fileName);\n const pathName: string = this._getStorage(fileName);\n await this.checkCreateFolder(pathName);\n // create a temporary file to avoid conflicts or prev corruption files\n const temporalName = path.join(\n this.path,\n sanitzers(`${fileName}.tmp-${String(Math.random()).replace(/^0\\./, '')}`)\n );\n\n debug('write a temporal name %o', temporalName);\n let opened = false;\n // an errored or aborted download must never be renamed into place: that\n // would publish a truncated tarball under the final name\n let failed = false;\n const writeStream = fs.createWriteStream(temporalName);\n\n writeStream.on('open', () => {\n opened = true;\n });\n\n writeStream.on('error', async (err) => {\n failed = true;\n if (opened) {\n this.logger.error(\n { err, fileName },\n 'error on open write tarball for @{fileName}: @{err.message}'\n );\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n this.logger.error(\n { err, fileName },\n 'error on writing tarball for @{fileName}: @{err.message}'\n );\n await this.removeTempFile(temporalName);\n }\n });\n\n // the 'close' event is emitted when the stream and any of its\n // underlying resources (a file descriptor, for example) have been closed.\n writeStream.once('close', async () => {\n if (failed) {\n // the error/abort listeners own the cleanup of the temporal file\n return;\n }\n try {\n await renameTmp(temporalName, pathName);\n } catch (err) {\n this.logger.error(\n { err, temporalName, pathName },\n 'error on rename temporal file @{temporalName} to @{pathName}: @{err.message},' +\n 'please report this bug'\n );\n }\n });\n\n // if upload is aborted, we clean up the temporal file\n signal?.addEventListener(\n 'abort',\n async () => {\n failed = true;\n if (opened) {\n // close always happens, even if error\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n await this.removeTempFile(temporalName);\n }\n },\n { once: true }\n );\n\n return writeStream;\n }\n\n /**\n * Read a tarball from the storage\n * @param tarballName tarball name eg: foo-1.0.0.tgz\n * @param options {signal} abort signal\n * @returns Readable stream\n */\n public async readTarball(tarballName: string, { signal }): Promise<Readable> {\n const pathName: string = this._getStorage(tarballName);\n debug('read a tarball %o', pathName);\n const readStream = addAbortSignal(signal, fs.createReadStream(pathName));\n readStream.on('open', function (fileDescriptorId: number) {\n // if abort, the descriptor is null\n debug('file descriptor id %o', fileDescriptorId);\n if (fileDescriptorId) {\n // sync on purpose: the size must be emitted before the first data\n // chunk flushes the response headers (an async fstat races it)\n let size: number | undefined;\n try {\n size = fs.fstatSync(fileDescriptorId).size;\n } catch {\n // the stream 'error' event surfaces any real problem\n }\n if (size !== undefined) {\n debug('file size %o', size);\n readStream.emit('content-length', size);\n }\n }\n });\n readStream.on('error', (error) => {\n debug('no tarball found %o for %s message %s', pathName, tarballName, error.message);\n });\n return readStream;\n }\n\n private async _readStorageFile(name: string): Promise<any> {\n debug('reading the file: %o', name);\n try {\n return await readFilePromise(name);\n } catch (err: any) {\n debug('error reading the file: %o with error %o', name, err.message);\n throw err;\n }\n }\n\n private _convertToString(value: Manifest): string {\n return JSON.stringify(value);\n }\n\n public _getStorage(fileName = ''): string {\n const storagePath: string = path.join(this.path, sanitzers(fileName));\n debug('get storage %s', storagePath);\n return storagePath;\n }\n\n private async writeTempFileAndRename(dest: string, fileContent: string): Promise<any> {\n const tempFilePath = tempFile(dest);\n try {\n // write file on temp location\n await this.checkCreateFolder(tempFilePath);\n await writeFilePromise(tempFilePath, fileContent);\n debug('creating a new file:: %o', dest);\n // rename tmp file to original\n await renameTmp(tempFilePath, dest);\n } catch (err: any) {\n debug('error on write the file: %o', dest);\n throw err;\n }\n }\n\n private async writeFile(destiny: string, fileContent: string): Promise<void> {\n try {\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } catch (err: any) {\n if (err && err.code === noSuchFile) {\n await this.checkCreateFolder(destiny);\n // we try again create the temp file\n debug('writing a temp file %s', destiny);\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } else {\n this.logger.error({ err }, 'error on write file: @{err.message}');\n throw err;\n }\n }\n }\n\n private async checkCreateFolder(pathName: string): Promise<void> {\n // Check if folder exists and create it if not\n const dir = path.dirname(pathName);\n try {\n await accessPromise(dir);\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('folder does not exist %o', dir);\n await mkdirPromise(dir, { recursive: true });\n debug('folder %o created', dir);\n } else {\n debug('error on check folder %o', dir);\n throw err;\n }\n }\n }\n\n private async _lockAndReadJSON(name: string): Promise<Manifest> {\n const fileName: string = this._getStorage(name);\n debug('lock and read a file %o', fileName);\n try {\n const data = await readFileNext<Manifest>(fileName, {\n lock: true,\n parse: true,\n });\n return data;\n } catch (err) {\n this.logger.error({ err }, 'error on lock file: @{err.message}');\n debug('error on lock and read json for file: %o', name);\n\n throw err;\n }\n }\n\n private async _unlockJSON(name: string): Promise<void> {\n await unlockFileNext(this._getStorage(name));\n }\n}\n"],"m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AAC;IAC3C,MAAM,qBAAqB,GAAG;GAChC,OAAO;IACL,MAAM,4BAA4B,GAAG;IACrC,MAAM;GACR;EACF;CACF;CAEA,MAAc,iBAAiB,MAAiC;EAC9D,MAAM,WAAmB,KAAK,YAAY,IAAI;EAC9C,MAAM,2BAA2B,QAAQ;EACzC,IAAI;GAKF,OAAO,MAJY,aAAuB,UAAU;IAClD,MAAM;IACN,OAAO;GACT,CAAC;EAEH,SAAS,KAAK;GACZ,KAAK,OAAO,MAAM,EAAE,IAAI,GAAG,oCAAoC;GAC/D,MAAM,4CAA4C,IAAI;GAEtD,MAAM;EACR;CACF;CAEA,MAAc,YAAY,MAA6B;EACrD,MAAM,eAAe,KAAK,YAAY,IAAI,CAAC;CAC7C;AACF"}
1
+ {"version":3,"file":"local-fs.mjs","names":[],"sources":["../src/local-fs.ts"],"sourcesContent":["import buildDebug from 'debug';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { Readable, Writable } from 'node:stream';\nimport { addAbortSignal } from 'node:stream';\nimport sanitzers from 'sanitize-filename';\n\nimport type { VerdaccioError, pluginUtils } from '@verdaccio/core';\nimport { errorUtils } from '@verdaccio/core';\nimport { readFileNext, unlockFileNext } from '@verdaccio/file-locking';\nimport type { Logger, Manifest } from '@verdaccio/types';\n\nimport {\n accessPromise,\n mkdirPromise,\n openPromise,\n readFilePromise,\n renamePromise,\n rmdirPromise,\n statPromise,\n unlinkPromise,\n writeFilePromise,\n} from './fs';\n\nexport const fileExist = 'EEXISTS';\nexport const noSuchFile = 'ENOENT';\nexport const resourceNotAvailable = 'EAGAIN';\nexport const packageJSONFileName = 'package.json';\n\nexport type ILocalFSPackageManager = pluginUtils.StorageHandler & { path: string };\n\nconst debug = buildDebug('verdaccio:plugin:local-storage:local-fs');\n\nexport const fSError = function (message: string, code = 409): VerdaccioError {\n const err: VerdaccioError = errorUtils.getCode(code, message);\n // FIXME: we should return http-status codes here instead, future improvement\n // @ts-ignore\n err.code = message;\n\n return err;\n};\n\nconst tempFile = function (str): string {\n return `${str}.tmp${String(Math.random()).slice(2)}`;\n};\n\nexport async function renameTmp(src: string, dst: string): Promise<void> {\n debug('rename %s to %s', src, dst);\n try {\n await renamePromise(src, dst);\n } catch (err: any) {\n debug('error rename %s error %s', src, err?.message);\n await unlinkPromise(src);\n }\n}\n\nexport default class LocalFS implements ILocalFSPackageManager {\n public path: string;\n public logger: Logger;\n\n public constructor(path: string, logger: Logger) {\n this.path = path;\n this.logger = logger;\n }\n\n /**\n * This function allows to update the package\n * This function handle the update package logic, for this plugin\n * we need to lock/unlock handlers for thread-safely and then apply\n * the `handleUpdate` and return the result.\n *\n * The lock could fail on several steps so we need to ensure the\n * file does not get locked if the whole process fails.\n *\n Algorithm:\n 1. lock package.json for writing\n 2. read package.json\n 3. apply external update package handler\n 4. return manifest (write is being hanlded into the core)\n 5. rename package.json.tmp package.json\n * @param {*} packageName\n * The update package handler could be different based\n * on the action and handled into the core.\n * @param {*} handleUpdate\n */\n public async updatePackage(\n packageName: string,\n handleUpdate: (manifest: Manifest) => Promise<Manifest>\n ): Promise<Manifest> {\n // this plugin lock files on write, we handle all possible scenarios\n let locked = false;\n let manifestUpdated: Manifest;\n try {\n const manifest = await this._lockAndReadJSON(packageJSONFileName);\n locked = true;\n manifestUpdated = await handleUpdate(manifest);\n if (locked) {\n debug('unlock %s', packageJSONFileName);\n await this._unlockJSON(packageJSONFileName);\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n } else {\n this.logger.debug({ packageName }, 'the package @{packageName} has been updated');\n return manifestUpdated;\n }\n } catch (err: any) {\n // we ensure lock the file\n this.logger.error(\n { err, packageName },\n 'error on update package @{packageName}: @{err.message}'\n );\n if (locked) {\n try {\n await this._unlockJSON(packageJSONFileName);\n } catch {\n // unlock could fail, we bubble up error\n throw errorUtils.getInternalError('resource temporarily unavailable');\n }\n // after unlock bubble up the original error (e.g. thrown by the handler)\n throw err;\n } else {\n if (err.code === resourceNotAvailable) {\n throw errorUtils.getInternalError('resource temporarily unavailable');\n } else if (err.code === noSuchFile) {\n throw errorUtils.getNotFound();\n } else {\n throw err;\n }\n }\n }\n }\n\n public async deletePackage(packageName: string): Promise<void> {\n debug('delete a file/package %o', packageName);\n\n return await unlinkPromise(this._getStorage(packageName));\n }\n\n public async removePackage(): Promise<void> {\n debug('remove a package folder %o', this.path);\n\n await rmdirPromise(this._getStorage('.'));\n }\n\n /**\n * Verify if the package exists already.\n * @param name package name\n * @returns\n */\n public async hasPackage(): Promise<boolean> {\n const pathName: string = this._getStorage(packageJSONFileName);\n try {\n const stat = await statPromise(pathName);\n return stat.isFile();\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('dir: %o does not exist %s', pathName, err?.code);\n return false;\n } else {\n this.logger.error({ err }, 'error on verify a package exist: @{err.message}');\n throw errorUtils.getInternalError('error on verify a package exist');\n }\n }\n }\n\n /**\n * Create a package in the local storage, if package already exist fails.\n * @param name package name\n * @param manifest package manifest\n */\n public async createPackage(name: string, manifest: Manifest): Promise<void> {\n debug('create a new package %o', name);\n const pathPackage = this._getStorage(packageJSONFileName);\n try {\n // https://nodejs.org/dist/latest-v17.x/docs/api/fs.html#file-system-flags\n // 'wx': Like 'w' but fails if the path exists\n await openPromise(pathPackage, 'wx');\n } catch (err: any) {\n // cannot override a pacakge that already exist\n if (err.code === 'EEXIST') {\n debug('file %o cannot be created, it already exists: %o', name);\n throw fSError(fileExist);\n }\n }\n // Create a new file and it´s folder if does not exist previously\n await this.writeFile(pathPackage, this._convertToString(manifest));\n }\n\n public async savePackage(name: string, value: Manifest): Promise<void> {\n debug('save a package %o', name);\n\n await this.writeFile(this._getStorage(packageJSONFileName), this._convertToString(value));\n }\n\n public async readPackage(name: string): Promise<Manifest> {\n debug('read a package %o', name);\n try {\n const res = await this._readStorageFile(this._getStorage(packageJSONFileName));\n const data: any = JSON.parse(res.toString('utf8'));\n\n debug('read storage file %o has succeeded', name);\n return data;\n } catch (err: any) {\n if (err.code !== noSuchFile) {\n debug('parse error');\n this.logger.error({ err, name }, 'error on parse @{name}: @{err.message}');\n }\n throw err;\n }\n }\n\n public async hasTarball(fileName: string): Promise<boolean> {\n const pathName: string = this._getStorage(fileName);\n return new Promise((resolve) => {\n accessPromise(pathName)\n .then(() => {\n resolve(true);\n })\n .catch(() => resolve(false));\n });\n }\n\n /**\n * Best-effort removal of a temporary file. Error and abort can both try to\n * clean the same file from event listeners, so a missing file is fine and\n * nothing may throw — a rejection here becomes an uncaught exception.\n */\n private async removeTempFile(temporalName): Promise<void> {\n debug('remove temporal file %o', temporalName);\n try {\n await unlinkPromise(temporalName);\n debug('removed temporal file %o', temporalName);\n } catch (err: any) {\n if (err?.code !== 'ENOENT') {\n this.logger.warn(\n { temporalName, err: err.message },\n 'unable to remove temporal file @{temporalName}: @{err}'\n );\n }\n }\n }\n\n /**\n * Write a tarball into the storage\n * @param fileName package name\n * @param param1\n * @returns\n */\n public async writeTarball(fileName: string, { signal }): Promise<Writable> {\n debug('write a tarball %o', fileName);\n const pathName: string = this._getStorage(fileName);\n await this.checkCreateFolder(pathName);\n // create a temporary file to avoid conflicts or prev corruption files\n const temporalName = path.join(\n this.path,\n sanitzers(`${fileName}.tmp-${String(Math.random()).replace(/^0\\./, '')}`)\n );\n\n debug('write a temporal name %o', temporalName);\n let opened = false;\n // an errored or aborted download must never be renamed into place: that\n // would publish a truncated tarball under the final name\n let failed = false;\n const writeStream = fs.createWriteStream(temporalName);\n\n writeStream.on('open', () => {\n opened = true;\n });\n\n writeStream.on('error', async (err) => {\n failed = true;\n if (opened) {\n this.logger.error(\n { err, fileName },\n 'error on open write tarball for @{fileName}: @{err.message}'\n );\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n this.logger.error(\n { err, fileName },\n 'error on writing tarball for @{fileName}: @{err.message}'\n );\n await this.removeTempFile(temporalName);\n }\n });\n\n // the 'close' event is emitted when the stream and any of its\n // underlying resources (a file descriptor, for example) have been closed.\n writeStream.once('close', async () => {\n if (failed) {\n // the error/abort listeners own the cleanup of the temporal file\n return;\n }\n try {\n await renameTmp(temporalName, pathName);\n } catch (err) {\n this.logger.error(\n { err, temporalName, pathName },\n 'error on rename temporal file @{temporalName} to @{pathName}: @{err.message},' +\n 'please report this bug'\n );\n }\n });\n\n // if upload is aborted, we clean up the temporal file\n signal?.addEventListener(\n 'abort',\n async () => {\n failed = true;\n if (opened) {\n // close always happens, even if error\n writeStream.once('close', async () => {\n await this.removeTempFile(temporalName);\n });\n } else {\n await this.removeTempFile(temporalName);\n }\n },\n { once: true }\n );\n\n return writeStream;\n }\n\n /**\n * Read a tarball from the storage\n * @param tarballName tarball name eg: foo-1.0.0.tgz\n * @param options {signal} abort signal\n * @returns Readable stream\n */\n public async readTarball(tarballName: string, { signal }): Promise<Readable> {\n const pathName: string = this._getStorage(tarballName);\n debug('read a tarball %o', pathName);\n const readStream = addAbortSignal(signal, fs.createReadStream(pathName));\n readStream.on('open', function (fileDescriptorId: number) {\n // if abort, the descriptor is null\n debug('file descriptor id %o', fileDescriptorId);\n if (fileDescriptorId) {\n // sync on purpose: the size must be emitted before the first data\n // chunk flushes the response headers (an async fstat races it)\n let size: number | undefined;\n try {\n size = fs.fstatSync(fileDescriptorId).size;\n } catch {\n // the stream 'error' event surfaces any real problem\n }\n if (size !== undefined) {\n debug('file size %o', size);\n readStream.emit('content-length', size);\n }\n }\n });\n readStream.on('error', (error) => {\n debug('no tarball found %o for %s message %s', pathName, tarballName, error.message);\n });\n return readStream;\n }\n\n private async _readStorageFile(name: string): Promise<any> {\n debug('reading the file: %o', name);\n try {\n return await readFilePromise(name);\n } catch (err: any) {\n debug('error reading the file: %o with error %o', name, err.message);\n throw err;\n }\n }\n\n private _convertToString(value: Manifest): string {\n return JSON.stringify(value);\n }\n\n public _getStorage(fileName = ''): string {\n const storagePath: string = path.join(this.path, sanitzers(fileName));\n debug('get storage %s', storagePath);\n return storagePath;\n }\n\n private async writeTempFileAndRename(dest: string, fileContent: string): Promise<any> {\n const tempFilePath = tempFile(dest);\n try {\n // write file on temp location\n await this.checkCreateFolder(tempFilePath);\n await writeFilePromise(tempFilePath, fileContent);\n debug('creating a new file:: %o', dest);\n // rename tmp file to original\n await renameTmp(tempFilePath, dest);\n } catch (err: any) {\n debug('error on write the file: %o', dest);\n throw err;\n }\n }\n\n private async writeFile(destiny: string, fileContent: string): Promise<void> {\n try {\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } catch (err: any) {\n if (err && err.code === noSuchFile) {\n await this.checkCreateFolder(destiny);\n // we try again create the temp file\n debug('writing a temp file %s', destiny);\n await this.writeTempFileAndRename(destiny, fileContent);\n debug('write file success %s', destiny);\n } else {\n this.logger.error({ err }, 'error on write file: @{err.message}');\n throw err;\n }\n }\n }\n\n private async checkCreateFolder(pathName: string): Promise<void> {\n // Check if folder exists and create it if not\n const dir = path.dirname(pathName);\n try {\n await accessPromise(dir);\n } catch (err: any) {\n if (err.code === noSuchFile) {\n debug('folder does not exist %o', dir);\n await mkdirPromise(dir, { recursive: true });\n debug('folder %o created', dir);\n } else {\n debug('error on check folder %o', dir);\n throw err;\n }\n }\n }\n\n private async _lockAndReadJSON(name: string): Promise<Manifest> {\n const fileName: string = this._getStorage(name);\n debug('lock and read a file %o', fileName);\n try {\n const data = await readFileNext<Manifest>(fileName, {\n lock: true,\n parse: true,\n });\n return data;\n } catch (err) {\n this.logger.error({ err }, 'error on lock file: @{err.message}');\n debug('error on lock and read json for file: %o', name);\n\n throw err;\n }\n }\n\n private async _unlockJSON(name: string): Promise<void> {\n await unlockFileNext(this._getStorage(name));\n }\n}\n"],"mappings":";;;;;;;;;AAwBA,IAAa,YAAY;AACzB,IAAa,aAAa;AAC1B,IAAa,uBAAuB;AACpC,IAAa,sBAAsB;AAInC,IAAM,QAAQ,WAAW,yCAAyC;AAElE,IAAa,UAAU,SAAU,SAAiB,OAAO,KAAqB;CAC5E,MAAM,MAAsB,WAAW,QAAQ,MAAM,OAAO;CAG5D,IAAI,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Y,aAAuB,UAAU;IAClD,MAAM;IACN,OAAO;GACT,CAAC;EAEH,SAAS,KAAK;GACZ,KAAK,OAAO,MAAM,EAAE,IAAI,GAAG,oCAAoC;GAC/D,MAAM,4CAA4C,IAAI;GAEtD,MAAM;EACR;CACF;CAEA,MAAc,YAAY,MAA6B;EACrD,MAAM,eAAe,KAAK,YAAY,IAAI,CAAC;CAC7C;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verdaccio/local-storage",
3
- "version": "14.0.0-next-9.32",
3
+ "version": "14.0.0-next-9.34",
4
4
  "description": "Verdaccio Local Storage Plugin",
5
5
  "keywords": [
6
6
  "private",
@@ -36,7 +36,7 @@
36
36
  "node": ">=24"
37
37
  },
38
38
  "dependencies": {
39
- "@verdaccio/core": "9.0.0-next-9.32",
39
+ "@verdaccio/core": "9.0.0-next-9.34",
40
40
  "@verdaccio/file-locking": "14.0.0-next-9.4",
41
41
  "debug": "4.4.3",
42
42
  "globby": "11.1.0",
@@ -46,8 +46,8 @@
46
46
  },
47
47
  "devDependencies": {
48
48
  "@types/lodash-es": "4.17.12",
49
- "@verdaccio/logger": "9.0.0-next-9.32",
50
- "@verdaccio/types": "14.0.0-next-9.15",
49
+ "@verdaccio/logger": "9.0.0-next-9.34",
50
+ "@verdaccio/types": "14.0.0-next-9.16",
51
51
  "rimraf": "6.1.3",
52
52
  "vite": "8.2.2",
53
53
  "vitest": "4.1.11"