verdaccio 6.7.4 → 6.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/bin/verdaccio +5 -1
- package/build/_virtual/_rolldown/runtime.js +23 -0
- package/build/api/debug/index.js +23 -26
- package/build/api/debug/index.js.map +1 -0
- package/build/api/debug/index.mjs +19 -0
- package/build/api/debug/index.mjs.map +1 -0
- package/build/api/endpoint/api/dist-tags.js +62 -75
- package/build/api/endpoint/api/dist-tags.js.map +1 -0
- package/build/api/endpoint/api/dist-tags.mjs +56 -0
- package/build/api/endpoint/api/dist-tags.mjs.map +1 -0
- package/build/api/endpoint/api/package.js +91 -99
- package/build/api/endpoint/api/package.js.map +1 -0
- package/build/api/endpoint/api/package.mjs +89 -0
- package/build/api/endpoint/api/package.mjs.map +1 -0
- package/build/api/endpoint/api/ping.js +13 -11
- package/build/api/endpoint/api/ping.js.map +1 -0
- package/build/api/endpoint/api/ping.mjs +11 -0
- package/build/api/endpoint/api/ping.mjs.map +1 -0
- package/build/api/endpoint/api/publish.d.ts +2 -2
- package/build/api/endpoint/api/publish.js +278 -343
- package/build/api/endpoint/api/publish.js.map +1 -0
- package/build/api/endpoint/api/publish.mjs +280 -0
- package/build/api/endpoint/api/publish.mjs.map +1 -0
- package/build/api/endpoint/api/search.js +57 -105
- package/build/api/endpoint/api/search.js.map +1 -0
- package/build/api/endpoint/api/search.mjs +54 -0
- package/build/api/endpoint/api/search.mjs.map +1 -0
- package/build/api/endpoint/api/star.js +60 -71
- package/build/api/endpoint/api/star.js.map +1 -0
- package/build/api/endpoint/api/star.mjs +54 -0
- package/build/api/endpoint/api/star.mjs.map +1 -0
- package/build/api/endpoint/api/stars.js +40 -40
- package/build/api/endpoint/api/stars.js.map +1 -0
- package/build/api/endpoint/api/stars.mjs +35 -0
- package/build/api/endpoint/api/stars.mjs.map +1 -0
- package/build/api/endpoint/api/user.js +69 -82
- package/build/api/endpoint/api/user.js.map +1 -0
- package/build/api/endpoint/api/user.mjs +64 -0
- package/build/api/endpoint/api/user.mjs.map +1 -0
- package/build/api/endpoint/api/v1/profile.js +50 -67
- package/build/api/endpoint/api/v1/profile.js.map +1 -0
- package/build/api/endpoint/api/v1/profile.mjs +46 -0
- package/build/api/endpoint/api/v1/profile.mjs.map +1 -0
- package/build/api/endpoint/api/v1/search.d.ts +2 -1
- package/build/api/endpoint/api/v1/search.js +149 -168
- package/build/api/endpoint/api/v1/search.js.map +1 -0
- package/build/api/endpoint/api/v1/search.mjs +154 -0
- package/build/api/endpoint/api/v1/search.mjs.map +1 -0
- package/build/api/endpoint/api/v1/token.js +122 -155
- package/build/api/endpoint/api/v1/token.js.map +1 -0
- package/build/api/endpoint/api/v1/token.mjs +119 -0
- package/build/api/endpoint/api/v1/token.mjs.map +1 -0
- package/build/api/endpoint/api/whoami.js +13 -13
- package/build/api/endpoint/api/whoami.js.map +1 -0
- package/build/api/endpoint/api/whoami.mjs +11 -0
- package/build/api/endpoint/api/whoami.mjs.map +1 -0
- package/build/api/endpoint/index.js +58 -67
- package/build/api/endpoint/index.js.map +1 -0
- package/build/api/endpoint/index.mjs +54 -0
- package/build/api/endpoint/index.mjs.map +1 -0
- package/build/api/index.js +85 -106
- package/build/api/index.js.map +1 -0
- package/build/api/index.mjs +78 -0
- package/build/api/index.mjs.map +1 -0
- package/build/api/middleware.js +60 -54
- package/build/api/middleware.js.map +1 -0
- package/build/api/middleware.mjs +55 -0
- package/build/api/middleware.mjs.map +1 -0
- package/build/api/web/api/index.js +25 -29
- package/build/api/web/api/index.js.map +1 -0
- package/build/api/web/api/index.mjs +23 -0
- package/build/api/web/api/index.mjs.map +1 -0
- package/build/api/web/api/package.js +142 -161
- package/build/api/web/api/package.js.map +1 -0
- package/build/api/web/api/package.mjs +139 -0
- package/build/api/web/api/package.mjs.map +1 -0
- package/build/api/web/api/search.js +37 -50
- package/build/api/web/api/search.js.map +1 -0
- package/build/api/web/api/search.mjs +36 -0
- package/build/api/web/api/search.mjs.map +1 -0
- package/build/api/web/api/user.js +52 -73
- package/build/api/web/api/user.js.map +1 -0
- package/build/api/web/api/user.mjs +49 -0
- package/build/api/web/api/user.mjs.map +1 -0
- package/build/api/web/api/utils.js +9 -10
- package/build/api/web/api/utils.js.map +1 -0
- package/build/api/web/api/utils.mjs +11 -0
- package/build/api/web/api/utils.mjs.map +1 -0
- package/build/api/web/index.js +76 -88
- package/build/api/web/index.js.map +1 -0
- package/build/api/web/index.mjs +70 -0
- package/build/api/web/index.mjs.map +1 -0
- package/build/index.js +43 -60
- package/build/index.mjs +5 -0
- package/build/lib/auth-utils.js +12 -14
- package/build/lib/auth-utils.js.map +1 -0
- package/build/lib/auth-utils.mjs +11 -0
- package/build/lib/auth-utils.mjs.map +1 -0
- package/build/lib/bootstrap.js +125 -157
- package/build/lib/bootstrap.js.map +1 -0
- package/build/lib/bootstrap.mjs +125 -0
- package/build/lib/bootstrap.mjs.map +1 -0
- package/build/lib/cli/cli.js +22 -24
- package/build/lib/cli/cli.js.map +1 -0
- package/build/lib/cli/cli.mjs +23 -0
- package/build/lib/cli/cli.mjs.map +1 -0
- package/build/lib/cli/commands/info.js +34 -25
- package/build/lib/cli/commands/info.js.map +1 -0
- package/build/lib/cli/commands/info.mjs +32 -0
- package/build/lib/cli/commands/info.mjs.map +1 -0
- package/build/lib/cli/commands/init.js +61 -79
- package/build/lib/cli/commands/init.js.map +1 -0
- package/build/lib/cli/commands/init.mjs +70 -0
- package/build/lib/cli/commands/init.mjs.map +1 -0
- package/build/lib/cli/commands/version.js +14 -16
- package/build/lib/cli/commands/version.js.map +1 -0
- package/build/lib/cli/commands/version.mjs +14 -0
- package/build/lib/cli/commands/version.mjs.map +1 -0
- package/build/lib/cli/utils.d.ts +2 -2
- package/build/lib/cli/utils.js +16 -15
- package/build/lib/cli/utils.js.map +1 -0
- package/build/lib/cli/utils.mjs +14 -0
- package/build/lib/cli/utils.mjs.map +1 -0
- package/build/lib/cli.js +11 -14
- package/build/lib/cli.js.map +1 -0
- package/build/lib/cli.mjs +12 -0
- package/build/lib/cli.mjs.map +1 -0
- package/build/lib/config.js +19 -21
- package/build/lib/config.js.map +1 -0
- package/build/lib/config.mjs +16 -0
- package/build/lib/config.mjs.map +1 -0
- package/build/lib/constants.js +100 -93
- package/build/lib/constants.js.map +1 -0
- package/build/lib/constants.mjs +28 -0
- package/build/lib/constants.mjs.map +1 -0
- package/build/lib/experiments.js +19 -27
- package/build/lib/experiments.js.map +1 -0
- package/build/lib/experiments.mjs +20 -0
- package/build/lib/experiments.mjs.map +1 -0
- package/build/lib/local-storage.d.ts +5 -2
- package/build/lib/local-storage.js +606 -757
- package/build/lib/local-storage.js.map +1 -0
- package/build/lib/local-storage.mjs +600 -0
- package/build/lib/local-storage.mjs.map +1 -0
- package/build/lib/logger/index.js +24 -19
- package/build/lib/logger/index.js.map +1 -0
- package/build/lib/logger/index.mjs +17 -0
- package/build/lib/logger/index.mjs.map +1 -0
- package/build/lib/metadata-utils.js +24 -36
- package/build/lib/metadata-utils.js.map +1 -0
- package/build/lib/metadata-utils.mjs +23 -0
- package/build/lib/metadata-utils.mjs.map +1 -0
- package/build/lib/run-server.js +83 -114
- package/build/lib/run-server.js.map +1 -0
- package/build/lib/run-server.mjs +82 -0
- package/build/lib/run-server.mjs.map +1 -0
- package/build/lib/storage-utils.d.ts +120 -8
- package/build/lib/storage-utils.js +390 -251
- package/build/lib/storage-utils.js.map +1 -0
- package/build/lib/storage-utils.mjs +400 -0
- package/build/lib/storage-utils.mjs.map +1 -0
- package/build/lib/storage.d.ts +127 -57
- package/build/lib/storage.js +674 -681
- package/build/lib/storage.js.map +1 -0
- package/build/lib/storage.mjs +665 -0
- package/build/lib/storage.mjs.map +1 -0
- package/build/lib/up-storage.js +490 -599
- package/build/lib/up-storage.js.map +1 -0
- package/build/lib/up-storage.mjs +484 -0
- package/build/lib/up-storage.mjs.map +1 -0
- package/build/lib/uplink-util.js +21 -31
- package/build/lib/uplink-util.js.map +1 -0
- package/build/lib/uplink-util.mjs +24 -0
- package/build/lib/uplink-util.mjs.map +1 -0
- package/build/lib/utils.js +172 -231
- package/build/lib/utils.js.map +1 -0
- package/build/lib/utils.mjs +188 -0
- package/build/lib/utils.mjs.map +1 -0
- package/package.json +105 -100
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage-utils.js","names":[],"sources":["../../src/lib/storage-utils.ts"],"sourcesContent":["import createDebug from 'debug';\nimport _ from 'lodash';\n\nimport { pkgUtils } from '@verdaccio/core';\nimport { SearchMemoryIndexer } from '@verdaccio/search-indexer';\nimport {\n AbbreviatedManifest,\n AbbreviatedVersions,\n DistFile,\n Manifest,\n Version,\n} from '@verdaccio/types';\nimport { generateRandomHexString } from '@verdaccio/utils';\n\nimport { API_ERROR, DIST_TAGS, HTTP_STATUS, STORAGE, USERS } from './constants';\nimport LocalStorage from './local-storage';\nimport { logger } from './logger';\nimport { ErrorCode, isObject, normalizeDistTags } from './utils';\n\nconst debug = createDebug('verdaccio:storage-utils');\n\n/**\n * Create an empty package manifest with all the internal bookkeeping\n * sections (`_uplinks`, `_distfiles`, `_attachments`, `_rev`) initialized.\n * Used as the starting point when a package is seen for the first time.\n * @param name package name\n * @return an empty manifest for the given package\n */\nexport function generatePackageTemplate(name: string): Manifest {\n return {\n // standard things\n name,\n versions: {},\n time: {},\n [USERS]: {},\n [DIST_TAGS]: {},\n _uplinks: {},\n _distfiles: {},\n _attachments: {},\n _rev: '',\n };\n}\n\n/**\n * Normalize a manifest read from storage: ensure the object sections\n * (`versions`, `dist-tags`, `_distfiles`, `_attachments`, `_uplinks`, `time`)\n * exist, default the revision and `_id`, and normalize the dist-tags shape.\n * The manifest is mutated in place.\n * @param pkg package manifest reference\n * @return the same manifest, normalized\n */\nexport function normalizePackage(pkg: Manifest): Manifest {\n const pkgProperties = ['versions', 'dist-tags', '_distfiles', '_attachments', '_uplinks', 'time'];\n\n pkgProperties.forEach((key): void => {\n const pkgProp = pkg[key];\n\n if (_.isNil(pkgProp) || isObject(pkgProp) === false) {\n pkg[key] = {};\n }\n });\n\n if (_.isString(pkg._rev) === false) {\n debug('package %o has no revision, setting default', pkg.name);\n pkg._rev = STORAGE.DEFAULT_REVISION;\n }\n\n if (_.isString(pkg._id) === false) {\n pkg._id = pkg.name;\n }\n\n // normalize dist-tags\n normalizeDistTags(pkg);\n\n return pkg;\n}\n\n/**\n * Produce the next revision id in the `<counter>-<hash>` format used by the\n * storage layer, incrementing the counter of the previous revision.\n * @param rev previous revision id, eg. `2-a1b2c3`\n * @return the next revision id\n */\nexport function generateRevision(rev: string): string {\n const _rev = rev.split('-');\n\n return (+_rev[0] || 0) + 1 + '-' + generateRandomHexString();\n}\n\n/**\n * Pick the most relevant readme for a package: the manifest readme or the\n * `latest` version readme first, otherwise the first readme found across the\n * `next`, `beta`, `alpha`, `test`, `dev` and `canary` dist-tags, in that order.\n * @param pkg package manifest\n * @return the readme content, or an empty string when none is available\n */\nexport function getLatestReadme(pkg: Manifest): string {\n const versions = pkg['versions'] || {};\n const distTags = pkg[DIST_TAGS] || {};\n // FIXME: here is a bit tricky add the types\n const latestVersion: Version | any = distTags['latest'] ? versions[distTags['latest']] || {} : {};\n let readme = _.trim(pkg.readme || latestVersion.readme || '');\n if (readme) {\n return readme;\n }\n\n // In case of empty readme - trying to get ANY readme in the following order: 'next','beta','alpha','test','dev','canary'\n const readmeDistTagsPriority = ['next', 'beta', 'alpha', 'test', 'dev', 'canary'];\n readmeDistTagsPriority.map(function (tag): string | void {\n if (readme) {\n return readme;\n }\n const version: Version | any = distTags[tag] ? versions[distTags[tag]] || {} : {};\n readme = _.trim(version.readme || readme);\n });\n return readme;\n}\n\n/**\n * Remove the readme from a version object: only one readme is kept per\n * package (see getLatestReadme), never one per version. The version is\n * mutated in place.\n * @param version version metadata\n * @return the same version without its readme\n */\nexport function cleanUpReadme(version: Version): Version {\n if (_.isNil(version) === false) {\n // @ts-ignore\n delete version.readme;\n }\n\n return version;\n}\n\n/**\n * Manifest properties allowed in responses served to clients; everything\n * else is verdaccio-internal bookkeeping and is stripped by cleanUpLinksRef.\n */\nexport const WHITELIST = [\n '_rev',\n 'name',\n 'versions',\n 'dist-tags',\n 'readme',\n 'time',\n '_id',\n 'users',\n];\n\n/**\n * Strip verdaccio-internal sections (`_distfiles`, `_attachments`, ...) from\n * a manifest before serving it to a client. The manifest is mutated in place.\n * @param keepUpLinkData whether the `_uplinks` section should be preserved\n * @param result manifest to clean up\n * @return the same manifest with only whitelisted properties\n */\nexport function cleanUpLinksRef(keepUpLinkData: boolean, result: Manifest): Manifest {\n const propertyToKeep = [...WHITELIST];\n if (keepUpLinkData === true) {\n propertyToKeep.push('_uplinks');\n }\n\n for (const i in result) {\n if (propertyToKeep.indexOf(i) === -1) {\n // Remove sections like '_uplinks' from response\n delete result[i];\n }\n }\n\n return result;\n}\n\n/**\n * Verify a package does not exist locally yet; part of the publish flow.\n * @param name package name\n * @param localStorage local storage instance\n * @throws conflict error when the package already exists locally\n */\nexport async function checkPackageLocal(name: string, localStorage: LocalStorage): Promise<void> {\n debug('checking if %o already exists locally', name);\n try {\n const results = await localStorage.getPackageMetadataAsync(name);\n if (results) {\n debug('package %o already exists locally', name);\n throw ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST);\n }\n } catch (err: any) {\n if (err.status === HTTP_STATUS.NOT_FOUND) {\n debug('package %o does not exist locally', name);\n return;\n }\n throw err;\n }\n}\n\n/**\n * Create a new package in the local storage and register its latest version\n * in the in-memory search indexer.\n * @param name package name\n * @param metadata package manifest to store\n * @param localStorage local storage instance\n */\nexport function publishPackage(\n name: string,\n metadata: any,\n localStorage: LocalStorage\n): Promise<void> {\n debug('publishing a new package for %o', name);\n return new Promise((resolve, reject): void => {\n localStorage.addPackage(name, metadata, (err, latest): void => {\n if (!_.isNull(err)) {\n return reject(err);\n } else if (!_.isUndefined(latest)) {\n SearchMemoryIndexer.add(latest).catch((reason) => {\n debug('indexer has failed on add item %o', reason);\n logger.error('indexer has failed on add item');\n });\n }\n return resolve();\n });\n });\n}\n\n/**\n * Verify a package does not exist on any uplink yet; part of the publish\n * flow. Uplink failures other than 404 reject the publish, unless\n * `publish.allow_offline` is enabled in the configuration.\n * @param name package name\n * @param isAllowPublishOffline whether publishing with unreachable uplinks is allowed\n * @param syncMetadata bound Storage._syncUplinksMetadata function\n * @throws conflict error when the package exists upstream, service unavailable when uplinks are offline\n */\nexport function checkPackageRemote(\n name: string,\n isAllowPublishOffline: boolean,\n syncMetadata: any\n): Promise<void> {\n debug('checking if %o already exists on uplinks', name);\n return new Promise((resolve, reject): void => {\n syncMetadata(name, null, {}, (err, packageJsonLocal, upLinksErrors): void => {\n // something weird\n if (err && err.status !== HTTP_STATUS.NOT_FOUND) {\n return reject(err);\n }\n\n // checking package exist already\n if (_.isNil(packageJsonLocal) === false) {\n debug('package %o already exists on an uplink', name);\n return reject(ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST));\n }\n\n for (let errorItem = 0; errorItem < upLinksErrors.length; errorItem++) {\n // checking error\n // if uplink fails with a status other than 404, we report failure\n if (_.isNil(upLinksErrors[errorItem][0]) === false) {\n if (upLinksErrors[errorItem][0].status !== HTTP_STATUS.NOT_FOUND) {\n if (isAllowPublishOffline) {\n debug('uplink offline for %o, publish offline is allowed', name);\n return resolve();\n }\n\n debug('uplink offline for %o, rejecting publish', name);\n return reject(ErrorCode.getServiceUnavailable(API_ERROR.UPLINK_OFFLINE_PUBLISH));\n }\n }\n }\n\n return resolve();\n });\n });\n}\n\n/**\n * Merge the `time` field of a remote manifest into the cached one; remote\n * entries win on conflicts. Returns a new manifest, the inputs are untouched.\n * @param cacheManifest local cached manifest\n * @param remoteManifest manifest fetched from an uplink\n * @return the cached manifest with the merged time field\n */\nexport function mergeUplinkTimeIntoLocal(cacheManifest: Manifest, remoteManifest: Manifest): any {\n if ('time' in remoteManifest) {\n debug('merging remote time field into local manifest for %o', cacheManifest.name);\n // remote override cache time conflicts\n return { ...cacheManifest, time: { ...cacheManifest.time, ...remoteManifest.time } };\n }\n\n return cacheManifest;\n}\n\n/**\n * Build the search item emitted for a local package during a search stream,\n * based on its latest version: npm-search compatible maintainers\n * (`{ username, email }`), publisher (from `_npmUser`, falling back to the\n * first maintainer), license and links.\n * @param data package manifest\n * @param time modified time attached to the search item\n * @return the search item, or undefined when the package has no usable latest version\n */\nexport function prepareSearchPackage(data: Manifest, time: unknown): any {\n const latest = pkgUtils.getLatest(data);\n\n if (!latest || !data.versions[latest]) {\n debug('no latest version found for %o, skipping search item', data.name);\n return;\n }\n\n debug('preparing search item for %o@%o', data.name, latest);\n if (latest && data.versions[latest]) {\n const version: Version = data.versions[latest];\n const versions: any = { [latest]: 'latest' };\n // packument maintainers carry `name`, but the npm search API contract uses\n // `username` and the npm CLI crashes on entries without it — emit both\n const rawMaintainers = version.maintainers || [version.author].filter(Boolean);\n const maintainers = Array.isArray(rawMaintainers)\n ? rawMaintainers.map((maintainer: any) =>\n typeof maintainer === 'string'\n ? { username: maintainer, email: '' }\n : {\n ...maintainer,\n username: maintainer?.username ?? maintainer?.name ?? '',\n email: maintainer?.email ?? '',\n }\n )\n : [];\n // npmjs fills `publisher` with the user who published the version; use\n // `_npmUser` when the publishing client provided it and fall back to the\n // first maintainer, otherwise the npm CLI renders \"published by ???\"\n const npmUser = (version as any)._npmUser;\n const publisher = npmUser?.name\n ? { username: npmUser.name, email: npmUser.email ?? '' }\n : (maintainers[0] ?? {});\n const pkg: any = {\n name: version.name,\n description: version.description,\n [DIST_TAGS]: { latest },\n maintainers,\n publisher,\n author: version.author,\n repository: version.repository,\n readmeFilename: version.readmeFilename || '',\n homepage: version.homepage,\n keywords: version.keywords,\n time: {\n modified: time,\n },\n bugs: version.bugs,\n license: version.license,\n versions,\n };\n\n return pkg;\n }\n}\n\n/**\n * Whether the tarball url path ends with the given file name\n * (any query string or fragment is ignored, like the path parsing\n * in updateVersions).\n */\nexport function tarballMatchesFilename(tarball: string, filename: string): boolean {\n return tarball.split(/[?#]/)[0].endsWith(`/${filename}`);\n}\n\n/**\n * Build a distfile record from a version's dist metadata when its tarball\n * url matches the given file name.\n */\nexport function distFileFromVersion(\n version: Version | undefined,\n filename: string\n): DistFile | null {\n const dist = version?.dist;\n\n if (dist?.tarball && tarballMatchesFilename(dist.tarball, filename)) {\n return { url: dist.tarball, sha: dist.shasum };\n }\n\n return null;\n}\n\n/**\n * Resolve the distfile record for a tarball filename. Prefers the\n * `_distfiles` bookkeeping, but falls back to the version metadata when the\n * record is missing (storages written by other verdaccio versions cache\n * versions without their distfile records, which made those tarballs\n * permanently unavailable).\n * @param manifest cached manifest\n * @param filename tarball file name, eg. pkg-1.0.0.tgz\n */\nexport function lookupDistFile(manifest: Manifest, filename: string): DistFile | null {\n const distFile = manifest?._distfiles?.[filename];\n if (_.isNil(distFile) === false) {\n return distFile;\n }\n\n const versions = manifest?.versions ?? {};\n\n // tarballs are conventionally named <basename>-<version>.tgz, so the\n // version can usually be derived from the filename without scanning\n // manifests that carry thousands of versions\n const basename = manifest?.name?.replace(/^.*\\//, '');\n if (basename && filename.startsWith(`${basename}-`) && filename.endsWith('.tgz')) {\n const versionId = filename.slice(basename.length + 1, -'.tgz'.length);\n const distFromVersion = distFileFromVersion(versions[versionId], filename);\n\n if (distFromVersion) {\n debug('distfile record missing for %o, using version %o dist', filename, versionId);\n return distFromVersion;\n }\n }\n\n // unconventional tarball names: fall back to a scan\n for (const versionId in versions) {\n const distFromVersion = distFileFromVersion(versions[versionId], filename);\n\n if (distFromVersion) {\n debug('distfile record missing for %o, using version %o dist', filename, versionId);\n return distFromVersion;\n }\n }\n\n debug('no distfile record or version dist found for %o', filename);\n return null;\n}\n\n/**\n * Check whether the package metadata has enough data to be published.\n * @param pkg package manifest\n * @return true when the manifest carries a versions section\n */\nexport function isPublishablePackage(pkg: Manifest): boolean {\n const keys: string[] = Object.keys(pkg);\n\n return keys.includes('versions');\n}\n\n/**\n * Whether a version declares an install lifecycle script (`install`,\n * `preinstall` or `postinstall`); surfaced in abbreviated manifests as\n * `hasInstallScript` so clients can warn about script execution.\n * @param version version metadata\n * @return true when an install script is present\n */\nexport function hasInstallScript(version: Version) {\n if (version?.scripts) {\n const scripts = Object.keys(version.scripts);\n return (\n scripts.find((item) => {\n return ['install', 'preinstall', 'postinstall'].includes(item);\n }) !== undefined\n );\n }\n return false;\n}\n\n/**\n * Convert a full manifest into the abbreviated format served when the client\n * requests `application/vnd.npm.install-v1+json` (npm install), keeping only\n * the fields the npm registry contract defines for installation.\n * https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md\n * @param manifest full package manifest\n * @return the abbreviated manifest\n */\nexport function convertAbbreviatedManifest(manifest: Manifest): AbbreviatedManifest {\n if (debug.enabled) {\n debug(\n 'converting %o to abbreviated manifest with %o versions',\n manifest.name,\n Object.keys(manifest.versions).length\n );\n }\n const abbreviatedVersions = Object.keys(manifest.versions).reduce(\n (acc: AbbreviatedVersions, version: string) => {\n const _version = manifest.versions[version];\n // This should be align with this document\n // https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object\n const _version_abbreviated = {\n name: _version.name,\n version: _version.version,\n description: _version.description,\n deprecated: _version.deprecated,\n bin: _version.bin,\n dist: _version.dist,\n engines: _version.engines,\n cpu: _version.cpu,\n os: _version.os,\n funding: _version.funding,\n directories: _version.directories,\n dependencies: _version.dependencies,\n devDependencies: _version.devDependencies,\n peerDependencies: _version.peerDependencies,\n peerDependenciesMeta: _version.peerDependenciesMeta,\n optionalDependencies: _version.optionalDependencies,\n bundleDependencies: _version.bundleDependencies,\n // npm cli specifics\n _hasShrinkwrap: _version._hasShrinkwrap,\n hasInstallScript: hasInstallScript(_version),\n };\n acc[version] = _version_abbreviated;\n return acc;\n },\n {}\n );\n\n const convertedManifest = {\n name: manifest['name'],\n [DIST_TAGS]: manifest[DIST_TAGS],\n versions: abbreviatedVersions,\n // @ts-ignore\n modified: manifest?.time?.modified,\n // NOTE: special case for pnpm https://github.com/pnpm/rfcs/pull/2\n time: manifest?.time,\n };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QACxD,KAA0B,YAAoB;EAC7C,MAAM,WAAW,SAAS,SAAS;EAyBnC,IAAI,WAAW;GArBb,MAAM,SAAS;GACf,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,YAAY,SAAS;GACrB,KAAK,SAAS;GACd,MAAM,SAAS;GACf,SAAS,SAAS;GAClB,KAAK,SAAS;GACd,IAAI,SAAS;GACb,SAAS,SAAS;GAClB,aAAa,SAAS;GACtB,cAAc,SAAS;GACvB,iBAAiB,SAAS;GAC1B,kBAAkB,SAAS;GAC3B,sBAAsB,SAAS;GAC/B,sBAAsB,SAAS;GAC/B,oBAAoB,SAAS;GAE7B,gBAAgB,SAAS;GACzB,kBAAkB,iBAAiB,QAAQ;EAE9B;EACf,OAAO;CACT,GACA,CAAC,CACH;CAaA,OAAO;EAVL,MAAM,SAAS;GACd,sBAAA,YAAY,SAAS,sBAAA;EACtB,UAAU;EAEV,UAAU,UAAU,MAAM;EAE1B,MAAM,UAAU;CAIX;AACT"}
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import { API_ERROR, DIST_TAGS, HTTP_STATUS, STORAGE, USERS } from "./constants.mjs";
|
|
2
|
+
import { logger } from "./logger/index.mjs";
|
|
3
|
+
import { ErrorCode, isObject, normalizeDistTags } from "./utils.mjs";
|
|
4
|
+
import _ from "lodash";
|
|
5
|
+
import { pkgUtils } from "@verdaccio/core";
|
|
6
|
+
import { generateRandomHexString } from "@verdaccio/utils";
|
|
7
|
+
import createDebug from "debug";
|
|
8
|
+
import { SearchMemoryIndexer } from "@verdaccio/search-indexer";
|
|
9
|
+
//#region src/lib/storage-utils.ts
|
|
10
|
+
var debug = createDebug("verdaccio:storage-utils");
|
|
11
|
+
/**
|
|
12
|
+
* Create an empty package manifest with all the internal bookkeeping
|
|
13
|
+
* sections (`_uplinks`, `_distfiles`, `_attachments`, `_rev`) initialized.
|
|
14
|
+
* Used as the starting point when a package is seen for the first time.
|
|
15
|
+
* @param name package name
|
|
16
|
+
* @return an empty manifest for the given package
|
|
17
|
+
*/
|
|
18
|
+
function generatePackageTemplate(name) {
|
|
19
|
+
return {
|
|
20
|
+
name,
|
|
21
|
+
versions: {},
|
|
22
|
+
time: {},
|
|
23
|
+
[USERS]: {},
|
|
24
|
+
[DIST_TAGS]: {},
|
|
25
|
+
_uplinks: {},
|
|
26
|
+
_distfiles: {},
|
|
27
|
+
_attachments: {},
|
|
28
|
+
_rev: ""
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Normalize a manifest read from storage: ensure the object sections
|
|
33
|
+
* (`versions`, `dist-tags`, `_distfiles`, `_attachments`, `_uplinks`, `time`)
|
|
34
|
+
* exist, default the revision and `_id`, and normalize the dist-tags shape.
|
|
35
|
+
* The manifest is mutated in place.
|
|
36
|
+
* @param pkg package manifest reference
|
|
37
|
+
* @return the same manifest, normalized
|
|
38
|
+
*/
|
|
39
|
+
function normalizePackage(pkg) {
|
|
40
|
+
[
|
|
41
|
+
"versions",
|
|
42
|
+
"dist-tags",
|
|
43
|
+
"_distfiles",
|
|
44
|
+
"_attachments",
|
|
45
|
+
"_uplinks",
|
|
46
|
+
"time"
|
|
47
|
+
].forEach((key) => {
|
|
48
|
+
const pkgProp = pkg[key];
|
|
49
|
+
if (_.isNil(pkgProp) || isObject(pkgProp) === false) pkg[key] = {};
|
|
50
|
+
});
|
|
51
|
+
if (_.isString(pkg._rev) === false) {
|
|
52
|
+
debug("package %o has no revision, setting default", pkg.name);
|
|
53
|
+
pkg._rev = STORAGE.DEFAULT_REVISION;
|
|
54
|
+
}
|
|
55
|
+
if (_.isString(pkg._id) === false) pkg._id = pkg.name;
|
|
56
|
+
normalizeDistTags(pkg);
|
|
57
|
+
return pkg;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Produce the next revision id in the `<counter>-<hash>` format used by the
|
|
61
|
+
* storage layer, incrementing the counter of the previous revision.
|
|
62
|
+
* @param rev previous revision id, eg. `2-a1b2c3`
|
|
63
|
+
* @return the next revision id
|
|
64
|
+
*/
|
|
65
|
+
function generateRevision(rev) {
|
|
66
|
+
return (+rev.split("-")[0] || 0) + 1 + "-" + generateRandomHexString();
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Pick the most relevant readme for a package: the manifest readme or the
|
|
70
|
+
* `latest` version readme first, otherwise the first readme found across the
|
|
71
|
+
* `next`, `beta`, `alpha`, `test`, `dev` and `canary` dist-tags, in that order.
|
|
72
|
+
* @param pkg package manifest
|
|
73
|
+
* @return the readme content, or an empty string when none is available
|
|
74
|
+
*/
|
|
75
|
+
function getLatestReadme(pkg) {
|
|
76
|
+
const versions = pkg["versions"] || {};
|
|
77
|
+
const distTags = pkg["dist-tags"] || {};
|
|
78
|
+
const latestVersion = distTags["latest"] ? versions[distTags["latest"]] || {} : {};
|
|
79
|
+
let readme = _.trim(pkg.readme || latestVersion.readme || "");
|
|
80
|
+
if (readme) return readme;
|
|
81
|
+
[
|
|
82
|
+
"next",
|
|
83
|
+
"beta",
|
|
84
|
+
"alpha",
|
|
85
|
+
"test",
|
|
86
|
+
"dev",
|
|
87
|
+
"canary"
|
|
88
|
+
].map(function(tag) {
|
|
89
|
+
if (readme) return readme;
|
|
90
|
+
const version = distTags[tag] ? versions[distTags[tag]] || {} : {};
|
|
91
|
+
readme = _.trim(version.readme || readme);
|
|
92
|
+
});
|
|
93
|
+
return readme;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Remove the readme from a version object: only one readme is kept per
|
|
97
|
+
* package (see getLatestReadme), never one per version. The version is
|
|
98
|
+
* mutated in place.
|
|
99
|
+
* @param version version metadata
|
|
100
|
+
* @return the same version without its readme
|
|
101
|
+
*/
|
|
102
|
+
function cleanUpReadme(version) {
|
|
103
|
+
if (_.isNil(version) === false) delete version.readme;
|
|
104
|
+
return version;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Manifest properties allowed in responses served to clients; everything
|
|
108
|
+
* else is verdaccio-internal bookkeeping and is stripped by cleanUpLinksRef.
|
|
109
|
+
*/
|
|
110
|
+
var WHITELIST = [
|
|
111
|
+
"_rev",
|
|
112
|
+
"name",
|
|
113
|
+
"versions",
|
|
114
|
+
"dist-tags",
|
|
115
|
+
"readme",
|
|
116
|
+
"time",
|
|
117
|
+
"_id",
|
|
118
|
+
"users"
|
|
119
|
+
];
|
|
120
|
+
/**
|
|
121
|
+
* Strip verdaccio-internal sections (`_distfiles`, `_attachments`, ...) from
|
|
122
|
+
* a manifest before serving it to a client. The manifest is mutated in place.
|
|
123
|
+
* @param keepUpLinkData whether the `_uplinks` section should be preserved
|
|
124
|
+
* @param result manifest to clean up
|
|
125
|
+
* @return the same manifest with only whitelisted properties
|
|
126
|
+
*/
|
|
127
|
+
function cleanUpLinksRef(keepUpLinkData, result) {
|
|
128
|
+
const propertyToKeep = [...WHITELIST];
|
|
129
|
+
if (keepUpLinkData === true) propertyToKeep.push("_uplinks");
|
|
130
|
+
for (const i in result) if (propertyToKeep.indexOf(i) === -1) delete result[i];
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Verify a package does not exist locally yet; part of the publish flow.
|
|
135
|
+
* @param name package name
|
|
136
|
+
* @param localStorage local storage instance
|
|
137
|
+
* @throws conflict error when the package already exists locally
|
|
138
|
+
*/
|
|
139
|
+
async function checkPackageLocal(name, localStorage) {
|
|
140
|
+
debug("checking if %o already exists locally", name);
|
|
141
|
+
try {
|
|
142
|
+
if (await localStorage.getPackageMetadataAsync(name)) {
|
|
143
|
+
debug("package %o already exists locally", name);
|
|
144
|
+
throw ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST);
|
|
145
|
+
}
|
|
146
|
+
} catch (err) {
|
|
147
|
+
if (err.status === HTTP_STATUS.NOT_FOUND) {
|
|
148
|
+
debug("package %o does not exist locally", name);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
throw err;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Create a new package in the local storage and register its latest version
|
|
156
|
+
* in the in-memory search indexer.
|
|
157
|
+
* @param name package name
|
|
158
|
+
* @param metadata package manifest to store
|
|
159
|
+
* @param localStorage local storage instance
|
|
160
|
+
*/
|
|
161
|
+
function publishPackage(name, metadata, localStorage) {
|
|
162
|
+
debug("publishing a new package for %o", name);
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
localStorage.addPackage(name, metadata, (err, latest) => {
|
|
165
|
+
if (!_.isNull(err)) return reject(err);
|
|
166
|
+
else if (!_.isUndefined(latest)) SearchMemoryIndexer.add(latest).catch((reason) => {
|
|
167
|
+
debug("indexer has failed on add item %o", reason);
|
|
168
|
+
logger.error("indexer has failed on add item");
|
|
169
|
+
});
|
|
170
|
+
return resolve();
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Verify a package does not exist on any uplink yet; part of the publish
|
|
176
|
+
* flow. Uplink failures other than 404 reject the publish, unless
|
|
177
|
+
* `publish.allow_offline` is enabled in the configuration.
|
|
178
|
+
* @param name package name
|
|
179
|
+
* @param isAllowPublishOffline whether publishing with unreachable uplinks is allowed
|
|
180
|
+
* @param syncMetadata bound Storage._syncUplinksMetadata function
|
|
181
|
+
* @throws conflict error when the package exists upstream, service unavailable when uplinks are offline
|
|
182
|
+
*/
|
|
183
|
+
function checkPackageRemote(name, isAllowPublishOffline, syncMetadata) {
|
|
184
|
+
debug("checking if %o already exists on uplinks", name);
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
syncMetadata(name, null, {}, (err, packageJsonLocal, upLinksErrors) => {
|
|
187
|
+
if (err && err.status !== HTTP_STATUS.NOT_FOUND) return reject(err);
|
|
188
|
+
if (_.isNil(packageJsonLocal) === false) {
|
|
189
|
+
debug("package %o already exists on an uplink", name);
|
|
190
|
+
return reject(ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST));
|
|
191
|
+
}
|
|
192
|
+
for (let errorItem = 0; errorItem < upLinksErrors.length; errorItem++) if (_.isNil(upLinksErrors[errorItem][0]) === false) {
|
|
193
|
+
if (upLinksErrors[errorItem][0].status !== HTTP_STATUS.NOT_FOUND) {
|
|
194
|
+
if (isAllowPublishOffline) {
|
|
195
|
+
debug("uplink offline for %o, publish offline is allowed", name);
|
|
196
|
+
return resolve();
|
|
197
|
+
}
|
|
198
|
+
debug("uplink offline for %o, rejecting publish", name);
|
|
199
|
+
return reject(ErrorCode.getServiceUnavailable(API_ERROR.UPLINK_OFFLINE_PUBLISH));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return resolve();
|
|
203
|
+
});
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Merge the `time` field of a remote manifest into the cached one; remote
|
|
208
|
+
* entries win on conflicts. Returns a new manifest, the inputs are untouched.
|
|
209
|
+
* @param cacheManifest local cached manifest
|
|
210
|
+
* @param remoteManifest manifest fetched from an uplink
|
|
211
|
+
* @return the cached manifest with the merged time field
|
|
212
|
+
*/
|
|
213
|
+
function mergeUplinkTimeIntoLocal(cacheManifest, remoteManifest) {
|
|
214
|
+
if ("time" in remoteManifest) {
|
|
215
|
+
debug("merging remote time field into local manifest for %o", cacheManifest.name);
|
|
216
|
+
return {
|
|
217
|
+
...cacheManifest,
|
|
218
|
+
time: {
|
|
219
|
+
...cacheManifest.time,
|
|
220
|
+
...remoteManifest.time
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
return cacheManifest;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Build the search item emitted for a local package during a search stream,
|
|
228
|
+
* based on its latest version: npm-search compatible maintainers
|
|
229
|
+
* (`{ username, email }`), publisher (from `_npmUser`, falling back to the
|
|
230
|
+
* first maintainer), license and links.
|
|
231
|
+
* @param data package manifest
|
|
232
|
+
* @param time modified time attached to the search item
|
|
233
|
+
* @return the search item, or undefined when the package has no usable latest version
|
|
234
|
+
*/
|
|
235
|
+
function prepareSearchPackage(data, time) {
|
|
236
|
+
const latest = pkgUtils.getLatest(data);
|
|
237
|
+
if (!latest || !data.versions[latest]) {
|
|
238
|
+
debug("no latest version found for %o, skipping search item", data.name);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
debug("preparing search item for %o@%o", data.name, latest);
|
|
242
|
+
if (latest && data.versions[latest]) {
|
|
243
|
+
const version = data.versions[latest];
|
|
244
|
+
const versions = { [latest]: "latest" };
|
|
245
|
+
const rawMaintainers = version.maintainers || [version.author].filter(Boolean);
|
|
246
|
+
const maintainers = Array.isArray(rawMaintainers) ? rawMaintainers.map((maintainer) => typeof maintainer === "string" ? {
|
|
247
|
+
username: maintainer,
|
|
248
|
+
email: ""
|
|
249
|
+
} : {
|
|
250
|
+
...maintainer,
|
|
251
|
+
username: maintainer?.username ?? maintainer?.name ?? "",
|
|
252
|
+
email: maintainer?.email ?? ""
|
|
253
|
+
}) : [];
|
|
254
|
+
const npmUser = version._npmUser;
|
|
255
|
+
const publisher = npmUser?.name ? {
|
|
256
|
+
username: npmUser.name,
|
|
257
|
+
email: npmUser.email ?? ""
|
|
258
|
+
} : maintainers[0] ?? {};
|
|
259
|
+
return {
|
|
260
|
+
name: version.name,
|
|
261
|
+
description: version.description,
|
|
262
|
+
[DIST_TAGS]: { latest },
|
|
263
|
+
maintainers,
|
|
264
|
+
publisher,
|
|
265
|
+
author: version.author,
|
|
266
|
+
repository: version.repository,
|
|
267
|
+
readmeFilename: version.readmeFilename || "",
|
|
268
|
+
homepage: version.homepage,
|
|
269
|
+
keywords: version.keywords,
|
|
270
|
+
time: { modified: time },
|
|
271
|
+
bugs: version.bugs,
|
|
272
|
+
license: version.license,
|
|
273
|
+
versions
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Whether the tarball url path ends with the given file name
|
|
279
|
+
* (any query string or fragment is ignored, like the path parsing
|
|
280
|
+
* in updateVersions).
|
|
281
|
+
*/
|
|
282
|
+
function tarballMatchesFilename(tarball, filename) {
|
|
283
|
+
return tarball.split(/[?#]/)[0].endsWith(`/${filename}`);
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Build a distfile record from a version's dist metadata when its tarball
|
|
287
|
+
* url matches the given file name.
|
|
288
|
+
*/
|
|
289
|
+
function distFileFromVersion(version, filename) {
|
|
290
|
+
const dist = version?.dist;
|
|
291
|
+
if (dist?.tarball && tarballMatchesFilename(dist.tarball, filename)) return {
|
|
292
|
+
url: dist.tarball,
|
|
293
|
+
sha: dist.shasum
|
|
294
|
+
};
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Resolve the distfile record for a tarball filename. Prefers the
|
|
299
|
+
* `_distfiles` bookkeeping, but falls back to the version metadata when the
|
|
300
|
+
* record is missing (storages written by other verdaccio versions cache
|
|
301
|
+
* versions without their distfile records, which made those tarballs
|
|
302
|
+
* permanently unavailable).
|
|
303
|
+
* @param manifest cached manifest
|
|
304
|
+
* @param filename tarball file name, eg. pkg-1.0.0.tgz
|
|
305
|
+
*/
|
|
306
|
+
function lookupDistFile(manifest, filename) {
|
|
307
|
+
const distFile = manifest?._distfiles?.[filename];
|
|
308
|
+
if (_.isNil(distFile) === false) return distFile;
|
|
309
|
+
const versions = manifest?.versions ?? {};
|
|
310
|
+
const basename = manifest?.name?.replace(/^.*\//, "");
|
|
311
|
+
if (basename && filename.startsWith(`${basename}-`) && filename.endsWith(".tgz")) {
|
|
312
|
+
const versionId = filename.slice(basename.length + 1, -4);
|
|
313
|
+
const distFromVersion = distFileFromVersion(versions[versionId], filename);
|
|
314
|
+
if (distFromVersion) {
|
|
315
|
+
debug("distfile record missing for %o, using version %o dist", filename, versionId);
|
|
316
|
+
return distFromVersion;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
for (const versionId in versions) {
|
|
320
|
+
const distFromVersion = distFileFromVersion(versions[versionId], filename);
|
|
321
|
+
if (distFromVersion) {
|
|
322
|
+
debug("distfile record missing for %o, using version %o dist", filename, versionId);
|
|
323
|
+
return distFromVersion;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
debug("no distfile record or version dist found for %o", filename);
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Check whether the package metadata has enough data to be published.
|
|
331
|
+
* @param pkg package manifest
|
|
332
|
+
* @return true when the manifest carries a versions section
|
|
333
|
+
*/
|
|
334
|
+
function isPublishablePackage(pkg) {
|
|
335
|
+
return Object.keys(pkg).includes("versions");
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Whether a version declares an install lifecycle script (`install`,
|
|
339
|
+
* `preinstall` or `postinstall`); surfaced in abbreviated manifests as
|
|
340
|
+
* `hasInstallScript` so clients can warn about script execution.
|
|
341
|
+
* @param version version metadata
|
|
342
|
+
* @return true when an install script is present
|
|
343
|
+
*/
|
|
344
|
+
function hasInstallScript(version) {
|
|
345
|
+
if (version?.scripts) return Object.keys(version.scripts).find((item) => {
|
|
346
|
+
return [
|
|
347
|
+
"install",
|
|
348
|
+
"preinstall",
|
|
349
|
+
"postinstall"
|
|
350
|
+
].includes(item);
|
|
351
|
+
}) !== void 0;
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Convert a full manifest into the abbreviated format served when the client
|
|
356
|
+
* requests `application/vnd.npm.install-v1+json` (npm install), keeping only
|
|
357
|
+
* the fields the npm registry contract defines for installation.
|
|
358
|
+
* https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md
|
|
359
|
+
* @param manifest full package manifest
|
|
360
|
+
* @return the abbreviated manifest
|
|
361
|
+
*/
|
|
362
|
+
function convertAbbreviatedManifest(manifest) {
|
|
363
|
+
if (debug.enabled) debug("converting %o to abbreviated manifest with %o versions", manifest.name, Object.keys(manifest.versions).length);
|
|
364
|
+
const abbreviatedVersions = Object.keys(manifest.versions).reduce((acc, version) => {
|
|
365
|
+
const _version = manifest.versions[version];
|
|
366
|
+
acc[version] = {
|
|
367
|
+
name: _version.name,
|
|
368
|
+
version: _version.version,
|
|
369
|
+
description: _version.description,
|
|
370
|
+
deprecated: _version.deprecated,
|
|
371
|
+
bin: _version.bin,
|
|
372
|
+
dist: _version.dist,
|
|
373
|
+
engines: _version.engines,
|
|
374
|
+
cpu: _version.cpu,
|
|
375
|
+
os: _version.os,
|
|
376
|
+
funding: _version.funding,
|
|
377
|
+
directories: _version.directories,
|
|
378
|
+
dependencies: _version.dependencies,
|
|
379
|
+
devDependencies: _version.devDependencies,
|
|
380
|
+
peerDependencies: _version.peerDependencies,
|
|
381
|
+
peerDependenciesMeta: _version.peerDependenciesMeta,
|
|
382
|
+
optionalDependencies: _version.optionalDependencies,
|
|
383
|
+
bundleDependencies: _version.bundleDependencies,
|
|
384
|
+
_hasShrinkwrap: _version._hasShrinkwrap,
|
|
385
|
+
hasInstallScript: hasInstallScript(_version)
|
|
386
|
+
};
|
|
387
|
+
return acc;
|
|
388
|
+
}, {});
|
|
389
|
+
return {
|
|
390
|
+
name: manifest["name"],
|
|
391
|
+
[DIST_TAGS]: manifest[DIST_TAGS],
|
|
392
|
+
versions: abbreviatedVersions,
|
|
393
|
+
modified: manifest?.time?.modified,
|
|
394
|
+
time: manifest?.time
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
//#endregion
|
|
398
|
+
export { WHITELIST, checkPackageLocal, checkPackageRemote, cleanUpLinksRef, cleanUpReadme, convertAbbreviatedManifest, distFileFromVersion, generatePackageTemplate, generateRevision, getLatestReadme, hasInstallScript, isPublishablePackage, lookupDistFile, mergeUplinkTimeIntoLocal, normalizePackage, prepareSearchPackage, publishPackage, tarballMatchesFilename };
|
|
399
|
+
|
|
400
|
+
//# sourceMappingURL=storage-utils.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storage-utils.mjs","names":[],"sources":["../../src/lib/storage-utils.ts"],"sourcesContent":["import createDebug from 'debug';\nimport _ from 'lodash';\n\nimport { pkgUtils } from '@verdaccio/core';\nimport { SearchMemoryIndexer } from '@verdaccio/search-indexer';\nimport {\n AbbreviatedManifest,\n AbbreviatedVersions,\n DistFile,\n Manifest,\n Version,\n} from '@verdaccio/types';\nimport { generateRandomHexString } from '@verdaccio/utils';\n\nimport { API_ERROR, DIST_TAGS, HTTP_STATUS, STORAGE, USERS } from './constants';\nimport LocalStorage from './local-storage';\nimport { logger } from './logger';\nimport { ErrorCode, isObject, normalizeDistTags } from './utils';\n\nconst debug = createDebug('verdaccio:storage-utils');\n\n/**\n * Create an empty package manifest with all the internal bookkeeping\n * sections (`_uplinks`, `_distfiles`, `_attachments`, `_rev`) initialized.\n * Used as the starting point when a package is seen for the first time.\n * @param name package name\n * @return an empty manifest for the given package\n */\nexport function generatePackageTemplate(name: string): Manifest {\n return {\n // standard things\n name,\n versions: {},\n time: {},\n [USERS]: {},\n [DIST_TAGS]: {},\n _uplinks: {},\n _distfiles: {},\n _attachments: {},\n _rev: '',\n };\n}\n\n/**\n * Normalize a manifest read from storage: ensure the object sections\n * (`versions`, `dist-tags`, `_distfiles`, `_attachments`, `_uplinks`, `time`)\n * exist, default the revision and `_id`, and normalize the dist-tags shape.\n * The manifest is mutated in place.\n * @param pkg package manifest reference\n * @return the same manifest, normalized\n */\nexport function normalizePackage(pkg: Manifest): Manifest {\n const pkgProperties = ['versions', 'dist-tags', '_distfiles', '_attachments', '_uplinks', 'time'];\n\n pkgProperties.forEach((key): void => {\n const pkgProp = pkg[key];\n\n if (_.isNil(pkgProp) || isObject(pkgProp) === false) {\n pkg[key] = {};\n }\n });\n\n if (_.isString(pkg._rev) === false) {\n debug('package %o has no revision, setting default', pkg.name);\n pkg._rev = STORAGE.DEFAULT_REVISION;\n }\n\n if (_.isString(pkg._id) === false) {\n pkg._id = pkg.name;\n }\n\n // normalize dist-tags\n normalizeDistTags(pkg);\n\n return pkg;\n}\n\n/**\n * Produce the next revision id in the `<counter>-<hash>` format used by the\n * storage layer, incrementing the counter of the previous revision.\n * @param rev previous revision id, eg. `2-a1b2c3`\n * @return the next revision id\n */\nexport function generateRevision(rev: string): string {\n const _rev = rev.split('-');\n\n return (+_rev[0] || 0) + 1 + '-' + generateRandomHexString();\n}\n\n/**\n * Pick the most relevant readme for a package: the manifest readme or the\n * `latest` version readme first, otherwise the first readme found across the\n * `next`, `beta`, `alpha`, `test`, `dev` and `canary` dist-tags, in that order.\n * @param pkg package manifest\n * @return the readme content, or an empty string when none is available\n */\nexport function getLatestReadme(pkg: Manifest): string {\n const versions = pkg['versions'] || {};\n const distTags = pkg[DIST_TAGS] || {};\n // FIXME: here is a bit tricky add the types\n const latestVersion: Version | any = distTags['latest'] ? versions[distTags['latest']] || {} : {};\n let readme = _.trim(pkg.readme || latestVersion.readme || '');\n if (readme) {\n return readme;\n }\n\n // In case of empty readme - trying to get ANY readme in the following order: 'next','beta','alpha','test','dev','canary'\n const readmeDistTagsPriority = ['next', 'beta', 'alpha', 'test', 'dev', 'canary'];\n readmeDistTagsPriority.map(function (tag): string | void {\n if (readme) {\n return readme;\n }\n const version: Version | any = distTags[tag] ? versions[distTags[tag]] || {} : {};\n readme = _.trim(version.readme || readme);\n });\n return readme;\n}\n\n/**\n * Remove the readme from a version object: only one readme is kept per\n * package (see getLatestReadme), never one per version. The version is\n * mutated in place.\n * @param version version metadata\n * @return the same version without its readme\n */\nexport function cleanUpReadme(version: Version): Version {\n if (_.isNil(version) === false) {\n // @ts-ignore\n delete version.readme;\n }\n\n return version;\n}\n\n/**\n * Manifest properties allowed in responses served to clients; everything\n * else is verdaccio-internal bookkeeping and is stripped by cleanUpLinksRef.\n */\nexport const WHITELIST = [\n '_rev',\n 'name',\n 'versions',\n 'dist-tags',\n 'readme',\n 'time',\n '_id',\n 'users',\n];\n\n/**\n * Strip verdaccio-internal sections (`_distfiles`, `_attachments`, ...) from\n * a manifest before serving it to a client. The manifest is mutated in place.\n * @param keepUpLinkData whether the `_uplinks` section should be preserved\n * @param result manifest to clean up\n * @return the same manifest with only whitelisted properties\n */\nexport function cleanUpLinksRef(keepUpLinkData: boolean, result: Manifest): Manifest {\n const propertyToKeep = [...WHITELIST];\n if (keepUpLinkData === true) {\n propertyToKeep.push('_uplinks');\n }\n\n for (const i in result) {\n if (propertyToKeep.indexOf(i) === -1) {\n // Remove sections like '_uplinks' from response\n delete result[i];\n }\n }\n\n return result;\n}\n\n/**\n * Verify a package does not exist locally yet; part of the publish flow.\n * @param name package name\n * @param localStorage local storage instance\n * @throws conflict error when the package already exists locally\n */\nexport async function checkPackageLocal(name: string, localStorage: LocalStorage): Promise<void> {\n debug('checking if %o already exists locally', name);\n try {\n const results = await localStorage.getPackageMetadataAsync(name);\n if (results) {\n debug('package %o already exists locally', name);\n throw ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST);\n }\n } catch (err: any) {\n if (err.status === HTTP_STATUS.NOT_FOUND) {\n debug('package %o does not exist locally', name);\n return;\n }\n throw err;\n }\n}\n\n/**\n * Create a new package in the local storage and register its latest version\n * in the in-memory search indexer.\n * @param name package name\n * @param metadata package manifest to store\n * @param localStorage local storage instance\n */\nexport function publishPackage(\n name: string,\n metadata: any,\n localStorage: LocalStorage\n): Promise<void> {\n debug('publishing a new package for %o', name);\n return new Promise((resolve, reject): void => {\n localStorage.addPackage(name, metadata, (err, latest): void => {\n if (!_.isNull(err)) {\n return reject(err);\n } else if (!_.isUndefined(latest)) {\n SearchMemoryIndexer.add(latest).catch((reason) => {\n debug('indexer has failed on add item %o', reason);\n logger.error('indexer has failed on add item');\n });\n }\n return resolve();\n });\n });\n}\n\n/**\n * Verify a package does not exist on any uplink yet; part of the publish\n * flow. Uplink failures other than 404 reject the publish, unless\n * `publish.allow_offline` is enabled in the configuration.\n * @param name package name\n * @param isAllowPublishOffline whether publishing with unreachable uplinks is allowed\n * @param syncMetadata bound Storage._syncUplinksMetadata function\n * @throws conflict error when the package exists upstream, service unavailable when uplinks are offline\n */\nexport function checkPackageRemote(\n name: string,\n isAllowPublishOffline: boolean,\n syncMetadata: any\n): Promise<void> {\n debug('checking if %o already exists on uplinks', name);\n return new Promise((resolve, reject): void => {\n syncMetadata(name, null, {}, (err, packageJsonLocal, upLinksErrors): void => {\n // something weird\n if (err && err.status !== HTTP_STATUS.NOT_FOUND) {\n return reject(err);\n }\n\n // checking package exist already\n if (_.isNil(packageJsonLocal) === false) {\n debug('package %o already exists on an uplink', name);\n return reject(ErrorCode.getConflict(API_ERROR.PACKAGE_EXIST));\n }\n\n for (let errorItem = 0; errorItem < upLinksErrors.length; errorItem++) {\n // checking error\n // if uplink fails with a status other than 404, we report failure\n if (_.isNil(upLinksErrors[errorItem][0]) === false) {\n if (upLinksErrors[errorItem][0].status !== HTTP_STATUS.NOT_FOUND) {\n if (isAllowPublishOffline) {\n debug('uplink offline for %o, publish offline is allowed', name);\n return resolve();\n }\n\n debug('uplink offline for %o, rejecting publish', name);\n return reject(ErrorCode.getServiceUnavailable(API_ERROR.UPLINK_OFFLINE_PUBLISH));\n }\n }\n }\n\n return resolve();\n });\n });\n}\n\n/**\n * Merge the `time` field of a remote manifest into the cached one; remote\n * entries win on conflicts. Returns a new manifest, the inputs are untouched.\n * @param cacheManifest local cached manifest\n * @param remoteManifest manifest fetched from an uplink\n * @return the cached manifest with the merged time field\n */\nexport function mergeUplinkTimeIntoLocal(cacheManifest: Manifest, remoteManifest: Manifest): any {\n if ('time' in remoteManifest) {\n debug('merging remote time field into local manifest for %o', cacheManifest.name);\n // remote override cache time conflicts\n return { ...cacheManifest, time: { ...cacheManifest.time, ...remoteManifest.time } };\n }\n\n return cacheManifest;\n}\n\n/**\n * Build the search item emitted for a local package during a search stream,\n * based on its latest version: npm-search compatible maintainers\n * (`{ username, email }`), publisher (from `_npmUser`, falling back to the\n * first maintainer), license and links.\n * @param data package manifest\n * @param time modified time attached to the search item\n * @return the search item, or undefined when the package has no usable latest version\n */\nexport function prepareSearchPackage(data: Manifest, time: unknown): any {\n const latest = pkgUtils.getLatest(data);\n\n if (!latest || !data.versions[latest]) {\n debug('no latest version found for %o, skipping search item', data.name);\n return;\n }\n\n debug('preparing search item for %o@%o', data.name, latest);\n if (latest && data.versions[latest]) {\n const version: Version = data.versions[latest];\n const versions: any = { [latest]: 'latest' };\n // packument maintainers carry `name`, but the npm search API contract uses\n // `username` and the npm CLI crashes on entries without it — emit both\n const rawMaintainers = version.maintainers || [version.author].filter(Boolean);\n const maintainers = Array.isArray(rawMaintainers)\n ? rawMaintainers.map((maintainer: any) =>\n typeof maintainer === 'string'\n ? { username: maintainer, email: '' }\n : {\n ...maintainer,\n username: maintainer?.username ?? maintainer?.name ?? '',\n email: maintainer?.email ?? '',\n }\n )\n : [];\n // npmjs fills `publisher` with the user who published the version; use\n // `_npmUser` when the publishing client provided it and fall back to the\n // first maintainer, otherwise the npm CLI renders \"published by ???\"\n const npmUser = (version as any)._npmUser;\n const publisher = npmUser?.name\n ? { username: npmUser.name, email: npmUser.email ?? '' }\n : (maintainers[0] ?? {});\n const pkg: any = {\n name: version.name,\n description: version.description,\n [DIST_TAGS]: { latest },\n maintainers,\n publisher,\n author: version.author,\n repository: version.repository,\n readmeFilename: version.readmeFilename || '',\n homepage: version.homepage,\n keywords: version.keywords,\n time: {\n modified: time,\n },\n bugs: version.bugs,\n license: version.license,\n versions,\n };\n\n return pkg;\n }\n}\n\n/**\n * Whether the tarball url path ends with the given file name\n * (any query string or fragment is ignored, like the path parsing\n * in updateVersions).\n */\nexport function tarballMatchesFilename(tarball: string, filename: string): boolean {\n return tarball.split(/[?#]/)[0].endsWith(`/${filename}`);\n}\n\n/**\n * Build a distfile record from a version's dist metadata when its tarball\n * url matches the given file name.\n */\nexport function distFileFromVersion(\n version: Version | undefined,\n filename: string\n): DistFile | null {\n const dist = version?.dist;\n\n if (dist?.tarball && tarballMatchesFilename(dist.tarball, filename)) {\n return { url: dist.tarball, sha: dist.shasum };\n }\n\n return null;\n}\n\n/**\n * Resolve the distfile record for a tarball filename. Prefers the\n * `_distfiles` bookkeeping, but falls back to the version metadata when the\n * record is missing (storages written by other verdaccio versions cache\n * versions without their distfile records, which made those tarballs\n * permanently unavailable).\n * @param manifest cached manifest\n * @param filename tarball file name, eg. pkg-1.0.0.tgz\n */\nexport function lookupDistFile(manifest: Manifest, filename: string): DistFile | null {\n const distFile = manifest?._distfiles?.[filename];\n if (_.isNil(distFile) === false) {\n return distFile;\n }\n\n const versions = manifest?.versions ?? {};\n\n // tarballs are conventionally named <basename>-<version>.tgz, so the\n // version can usually be derived from the filename without scanning\n // manifests that carry thousands of versions\n const basename = manifest?.name?.replace(/^.*\\//, '');\n if (basename && filename.startsWith(`${basename}-`) && filename.endsWith('.tgz')) {\n const versionId = filename.slice(basename.length + 1, -'.tgz'.length);\n const distFromVersion = distFileFromVersion(versions[versionId], filename);\n\n if (distFromVersion) {\n debug('distfile record missing for %o, using version %o dist', filename, versionId);\n return distFromVersion;\n }\n }\n\n // unconventional tarball names: fall back to a scan\n for (const versionId in versions) {\n const distFromVersion = distFileFromVersion(versions[versionId], filename);\n\n if (distFromVersion) {\n debug('distfile record missing for %o, using version %o dist', filename, versionId);\n return distFromVersion;\n }\n }\n\n debug('no distfile record or version dist found for %o', filename);\n return null;\n}\n\n/**\n * Check whether the package metadata has enough data to be published.\n * @param pkg package manifest\n * @return true when the manifest carries a versions section\n */\nexport function isPublishablePackage(pkg: Manifest): boolean {\n const keys: string[] = Object.keys(pkg);\n\n return keys.includes('versions');\n}\n\n/**\n * Whether a version declares an install lifecycle script (`install`,\n * `preinstall` or `postinstall`); surfaced in abbreviated manifests as\n * `hasInstallScript` so clients can warn about script execution.\n * @param version version metadata\n * @return true when an install script is present\n */\nexport function hasInstallScript(version: Version) {\n if (version?.scripts) {\n const scripts = Object.keys(version.scripts);\n return (\n scripts.find((item) => {\n return ['install', 'preinstall', 'postinstall'].includes(item);\n }) !== undefined\n );\n }\n return false;\n}\n\n/**\n * Convert a full manifest into the abbreviated format served when the client\n * requests `application/vnd.npm.install-v1+json` (npm install), keeping only\n * the fields the npm registry contract defines for installation.\n * https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md\n * @param manifest full package manifest\n * @return the abbreviated manifest\n */\nexport function convertAbbreviatedManifest(manifest: Manifest): AbbreviatedManifest {\n if (debug.enabled) {\n debug(\n 'converting %o to abbreviated manifest with %o versions',\n manifest.name,\n Object.keys(manifest.versions).length\n );\n }\n const abbreviatedVersions = Object.keys(manifest.versions).reduce(\n (acc: AbbreviatedVersions, version: string) => {\n const _version = manifest.versions[version];\n // This should be align with this document\n // https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md#abbreviated-version-object\n const _version_abbreviated = {\n name: _version.name,\n version: _version.version,\n description: _version.description,\n deprecated: _version.deprecated,\n bin: _version.bin,\n dist: _version.dist,\n engines: _version.engines,\n cpu: _version.cpu,\n os: _version.os,\n funding: _version.funding,\n directories: _version.directories,\n dependencies: _version.dependencies,\n devDependencies: _version.devDependencies,\n peerDependencies: _version.peerDependencies,\n peerDependenciesMeta: _version.peerDependenciesMeta,\n optionalDependencies: _version.optionalDependencies,\n bundleDependencies: _version.bundleDependencies,\n // npm cli specifics\n _hasShrinkwrap: _version._hasShrinkwrap,\n hasInstallScript: hasInstallScript(_version),\n };\n acc[version] = _version_abbreviated;\n return acc;\n },\n {}\n );\n\n const convertedManifest = {\n name: manifest['name'],\n [DIST_TAGS]: manifest[DIST_TAGS],\n versions: abbreviatedVersions,\n // @ts-ignore\n modified: manifest?.time?.modified,\n // NOTE: special case for pnpm https://github.com/pnpm/rfcs/pull/2\n time: manifest?.time,\n };\n\n // @ts-ignore\n return convertedManifest;\n}\n"],"mappings":";;;;;;;;;AAmBA,IAAM,QAAQ,YAAY,yBAAyB;;;;;;;;AASnD,SAAgB,wBAAwB,MAAwB;CAC9D,OAAO;EAEL;EACA,UAAU,CAAC;EACX,MAAM,CAAC;GACN,QAAQ,CAAC;GACT,YAAY,CAAC;EACd,UAAU,CAAC;EACX,YAAY,CAAC;EACb,cAAc,CAA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